|
| 1 | +# Copyright 2025 © BeeAI a Series of LF Projects, LLC |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +from beeai_sdk.platform.client import PlatformClient, get_platform_client |
| 7 | + |
| 8 | + |
| 9 | +class Variables(dict[str, str]): |
| 10 | + async def save( |
| 11 | + self: Variables | dict[str, str | None] | dict[str, str], |
| 12 | + *, |
| 13 | + client: PlatformClient | None = None, |
| 14 | + ) -> None: |
| 15 | + """ |
| 16 | + Save variables to the BeeAI platform. Does not delete keys unless explicitly set to None. |
| 17 | +
|
| 18 | + Can be used as a class method: Variables.save({"key": "value", ...}) |
| 19 | + ...or as an instance method: variables.save() |
| 20 | + """ |
| 21 | + async with client or get_platform_client() as client: |
| 22 | + _ = ( |
| 23 | + await client.put( |
| 24 | + url="/api/v1/variables", |
| 25 | + json={"variables": self}, |
| 26 | + ) |
| 27 | + ).raise_for_status() |
| 28 | + |
| 29 | + async def load(self: Variables | None = None, *, client: PlatformClient | None = None) -> Variables: |
| 30 | + """ |
| 31 | + Load variables from the BeeAI platform. |
| 32 | +
|
| 33 | + Can be used as a class method: variables = Variables.load() |
| 34 | + ...or as an instance method to update the instance: variables.load() |
| 35 | + """ |
| 36 | + async with client or get_platform_client() as client: |
| 37 | + new_variables: dict[str, str] = ( |
| 38 | + (await client.get(url="/api/v1/variables")).raise_for_status().json()["variables"] |
| 39 | + ) |
| 40 | + if isinstance(self, Variables): |
| 41 | + self.clear() |
| 42 | + self.update(new_variables) |
| 43 | + return self |
| 44 | + return Variables(new_variables) |
0 commit comments