beru-sdk 1.0.0a13__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
beru_sdk/__init__.py ADDED
@@ -0,0 +1,24 @@
1
+ """Beru's apps API from Python: chat with a Beru instance's agents and run its workflows from your
2
+ app, as your own users, with the replies streamed. Beru keeps the agents, their tools and every run.
3
+
4
+ from beru_sdk import Beru
5
+
6
+ beru = Beru("https://beru.example.com", api_key="beru_sk_…") # or BERU_URL, BERU_APP_KEY
7
+ chat = beru.chats.create(agent="<agent id>", user="u_123")
8
+ for event in beru.chats.send(chat["id"], "Where is my order?"):
9
+ if event.type == "message.delta":
10
+ print(event.text, end="")
11
+
12
+ AsyncBeru has the same calls, awaited.
13
+ """
14
+ from ._async import AsyncBeru, AsyncRunStream
15
+ from ._core import BeruError, Event, Result, RunFailed
16
+ from ._sync import Beru, RunStream
17
+
18
+ __all__ = ["Beru", "AsyncBeru", "RunStream", "AsyncRunStream", "Event", "Result", "BeruError", "RunFailed"]
19
+ try:
20
+ from importlib.metadata import version as _version
21
+
22
+ __version__ = _version("beru-sdk")
23
+ except Exception: # noqa: BLE001 — run from a checkout, not installed
24
+ __version__ = "0"
beru_sdk/_async.py ADDED
@@ -0,0 +1,216 @@
1
+ """The client for asyncio code: an async web framework, a Temporal activity, a task queue worker."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ from typing import Any, AsyncIterator, Dict, List, Optional
6
+
7
+ import httpx
8
+
9
+ from ._core import (API, DEFAULT_TIMEOUT, RECONNECTS, STREAM_READ_TIMEOUT, BeruError, Event, Result, SSEParser,
10
+ Tally, error_from, settings)
11
+
12
+
13
+ class _Dropped(Exception):
14
+ pass
15
+
16
+
17
+ async def _alines(chunks) -> AsyncIterator[str]:
18
+ buf = ""
19
+ async for chunk in chunks:
20
+ buf += chunk
21
+ while True:
22
+ i = buf.find("\n")
23
+ if i < 0:
24
+ break
25
+ line, buf = buf[:i], buf[i + 1:]
26
+ yield line.rstrip("\r")
27
+ if buf:
28
+ yield buf.rstrip("\r")
29
+
30
+
31
+ class AsyncRunStream:
32
+ """A run's events as they happen: `async for` over it, or await text() / result()."""
33
+
34
+ def __init__(self, client: "AsyncBeru", method: str, path: str, body: Any = None, params: Optional[Dict[str, Any]] = None):
35
+ self._client = client
36
+ self._req = (method, path, body, params)
37
+ self._tally = Tally()
38
+ self._gen: Optional[AsyncIterator[Event]] = None
39
+
40
+ @property
41
+ def run_id(self) -> Optional[str]:
42
+ return self._tally.run
43
+
44
+ def __aiter__(self) -> "AsyncRunStream":
45
+ return self
46
+
47
+ async def __anext__(self) -> Event:
48
+ if self._gen is None:
49
+ self._gen = self._events()
50
+ return await self._gen.__anext__()
51
+
52
+ async def __aenter__(self) -> "AsyncRunStream":
53
+ return self
54
+
55
+ async def __aexit__(self, *exc) -> None:
56
+ await self.close()
57
+
58
+ async def close(self) -> None:
59
+ """Stop listening. The run itself carries on in Beru."""
60
+ if self._gen is not None:
61
+ await self._gen.aclose()
62
+
63
+ async def _events(self) -> AsyncIterator[Event]:
64
+ c, (method, path, body, params) = self._client, self._req
65
+ attempts = 0
66
+ while True:
67
+ try:
68
+ async with c._http.stream(method, c._url(path), json=body, params=params,
69
+ headers={**c._headers, "Accept": "text/event-stream"},
70
+ timeout=httpx.Timeout(c._timeout, read=STREAM_READ_TIMEOUT)) as response:
71
+ if response.status_code >= 400:
72
+ await response.aread()
73
+ raise error_from(response.status_code, response.content, response.headers)
74
+ parser = SSEParser()
75
+ async for line in _alines(response.aiter_text()):
76
+ ev = parser.feed(line)
77
+ if ev is None:
78
+ continue
79
+ self._tally.note(ev)
80
+ yield ev
81
+ if ev.type == "run.finished":
82
+ return
83
+ raise _Dropped()
84
+ except (httpx.TransportError, _Dropped):
85
+ if self._tally.run is None or attempts >= c._reconnects:
86
+ raise BeruError("The stream ended before the run did.", 0, "stream_lost") from None
87
+ attempts += 1
88
+ await asyncio.sleep(min(0.25 * 2 ** attempts, 5.0))
89
+ method, path, body = "GET", f"/runs/{self._tally.run}/events", None
90
+ params = {"after": self._tally.last_id} if self._tally.last_id else None
91
+
92
+ async def result(self) -> Result:
93
+ """Wait for the end. Raises RunFailed when the run failed."""
94
+ async for _ in self:
95
+ pass
96
+ return self._tally.result()
97
+
98
+ async def text(self) -> str:
99
+ res = await self.result()
100
+ return res.message if res.message is not None else res.text
101
+
102
+ async def cancel(self) -> Dict[str, Any]:
103
+ if self.run_id is None:
104
+ async for ev in self:
105
+ if ev.type == "run.started":
106
+ break
107
+ if self.run_id is None:
108
+ return {"stopping": False}
109
+ out = await self._client._call("POST", f"/runs/{self.run_id}/cancel")
110
+ await self.close()
111
+ return out
112
+
113
+
114
+ class _Chats:
115
+ def __init__(self, c: "AsyncBeru"):
116
+ self._c = c
117
+
118
+ async def create(self, agent: str, user: str, title: Optional[str] = None) -> Dict[str, Any]:
119
+ body = {"agent": agent, "user": user, **({"title": title} if title else {})}
120
+ return await self._c._call("POST", "/chats", json=body)
121
+
122
+ async def list(self, user: str) -> List[Dict[str, Any]]:
123
+ return (await self._c._call("GET", "/chats", params={"user": user}))["chats"]
124
+
125
+ async def messages(self, chat: str) -> List[Dict[str, Any]]:
126
+ return (await self._c._call("GET", f"/chats/{chat}/messages"))["messages"]
127
+
128
+ def send(self, chat: str, text: str) -> AsyncRunStream:
129
+ return AsyncRunStream(self._c, "POST", f"/chats/{chat}/messages", {"text": text})
130
+
131
+
132
+ class _Workflows:
133
+ def __init__(self, c: "AsyncBeru"):
134
+ self._c = c
135
+
136
+ def run(self, workflow: str, input: Optional[Dict[str, Any]] = None, user: Optional[str] = None) -> AsyncRunStream:
137
+ body: Dict[str, Any] = {"input": input or {}}
138
+ if user is not None:
139
+ body["user"] = user
140
+ return AsyncRunStream(self._c, "POST", f"/workflows/{workflow}/runs", body)
141
+
142
+ async def start(self, workflow: str, input: Optional[Dict[str, Any]] = None, user: Optional[str] = None) -> str:
143
+ stream = self.run(workflow, input, user)
144
+ try:
145
+ async for ev in stream:
146
+ if ev.type == "run.started":
147
+ break
148
+ finally:
149
+ await stream.close()
150
+ if stream.run_id is None:
151
+ raise BeruError("Beru did not start the run.", 0, "not_started")
152
+ return stream.run_id
153
+
154
+ async def get_run(self, workflow: str, run: str) -> Dict[str, Any]:
155
+ return await self._c._call("GET", f"/workflows/{workflow}/runs/{run}")
156
+
157
+
158
+ class _Runs:
159
+ def __init__(self, c: "AsyncBeru"):
160
+ self._c = c
161
+
162
+ def events(self, run: str, after: Optional[str] = None) -> AsyncRunStream:
163
+ stream = AsyncRunStream(self._c, "GET", f"/runs/{run}/events", None, {"after": after} if after else None)
164
+ stream._tally.run = run
165
+ return stream
166
+
167
+ async def cancel(self, run: str) -> Dict[str, Any]:
168
+ return await self._c._call("POST", f"/runs/{run}/cancel")
169
+
170
+
171
+ class _Users:
172
+ def __init__(self, c: "AsyncBeru"):
173
+ self._c = c
174
+
175
+ async def forget(self, user: str) -> Dict[str, Any]:
176
+ return await self._c._call("DELETE", f"/users/{user}")
177
+
178
+
179
+ class AsyncBeru:
180
+ """The asyncio client: the same calls as Beru, awaited.
181
+
182
+ async with AsyncBeru("https://beru.example.com", api_key="beru_sk_…") as beru:
183
+ run = await beru.workflows.start("<workflow id>", input={"order": 42})
184
+ """
185
+
186
+ def __init__(self, base_url: Optional[str] = None, api_key: Optional[str] = None, *,
187
+ timeout: float = DEFAULT_TIMEOUT, http_client: Optional[httpx.AsyncClient] = None,
188
+ reconnects: int = RECONNECTS):
189
+ self._base, self._headers = settings(base_url, api_key)
190
+ self._timeout = timeout
191
+ self._own = http_client is None
192
+ self._http = http_client or httpx.AsyncClient(timeout=timeout)
193
+ self._reconnects = reconnects
194
+ self.chats = _Chats(self)
195
+ self.workflows = _Workflows(self)
196
+ self.runs = _Runs(self)
197
+ self.users = _Users(self)
198
+
199
+ def _url(self, path: str) -> str:
200
+ return f"{self._base}{API}{path}"
201
+
202
+ async def _call(self, method: str, path: str, *, json: Any = None, params: Optional[Dict[str, Any]] = None) -> Any:
203
+ response = await self._http.request(method, self._url(path), json=json, params=params, headers=self._headers)
204
+ if response.status_code >= 400:
205
+ raise error_from(response.status_code, response.content, response.headers)
206
+ return response.json() if response.content else {}
207
+
208
+ async def aclose(self) -> None:
209
+ if self._own:
210
+ await self._http.aclose()
211
+
212
+ async def __aenter__(self) -> "AsyncBeru":
213
+ return self
214
+
215
+ async def __aexit__(self, *exc) -> None:
216
+ await self.aclose()
beru_sdk/_core.py ADDED
@@ -0,0 +1,178 @@
1
+ """What the sync and async clients share: settings, errors, events and the stream format.
2
+
3
+ The apps API is /api/apps/v1 on a Beru instance (Beru's docs: "Apps API reference"). Its streams are
4
+ server-sent events, Event stream v1: each event has a name, a JSON body that repeats it in `type`,
5
+ and, on the last event made from one point in the run, an `id` to resume from.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ from dataclasses import dataclass, field
12
+ from typing import Any, Dict, Iterator, List, Optional
13
+
14
+ API = "/api/apps/v1"
15
+ DEFAULT_TIMEOUT = 60.0
16
+ # A stream may be quiet for a long tool call; Beru sends a keep-alive every 15 seconds.
17
+ STREAM_READ_TIMEOUT = 90.0
18
+ RECONNECTS = 5
19
+
20
+
21
+ class BeruError(Exception):
22
+ """An error answer from Beru: its HTTP status, its `code` and its message."""
23
+
24
+ def __init__(self, message: str, status: int = 0, code: str = "error", retry_after: Optional[float] = None):
25
+ super().__init__(message)
26
+ self.message = message
27
+ self.status = status
28
+ self.code = code
29
+ self.retry_after = retry_after
30
+
31
+
32
+ class RunFailed(BeruError):
33
+ """A run that ended with status `failed`."""
34
+
35
+ def __init__(self, message: str, run: Optional[str] = None):
36
+ super().__init__(message, 0, "run_failed")
37
+ self.run = run
38
+
39
+
40
+ @dataclass
41
+ class Event:
42
+ """One v1 event: `type`, its body in `data`, and the `id` to resume from (on some events)."""
43
+ type: str
44
+ data: Dict[str, Any] = field(default_factory=dict)
45
+ id: Optional[str] = None
46
+
47
+ def __getattr__(self, name: str) -> Any:
48
+ try:
49
+ return self.data[name]
50
+ except KeyError:
51
+ raise AttributeError(name) from None
52
+
53
+ def get(self, key: str, default: Any = None) -> Any:
54
+ return self.data.get(key, default)
55
+
56
+
57
+ @dataclass
58
+ class Result:
59
+ """How a run ended (run.finished): `status` done or stopped, the chat's `message` or the
60
+ workflow's `output`, `usage`, and any `questions` the agent asked."""
61
+ run: Optional[str]
62
+ status: str
63
+ message: Optional[str] = None
64
+ output: Any = None
65
+ usage: Optional[Dict[str, Any]] = None
66
+ questions: List[Dict[str, Any]] = field(default_factory=list)
67
+ text: str = "" # the reply's deltas, joined
68
+
69
+
70
+ def settings(base_url: Optional[str], api_key: Optional[str]):
71
+ base_url = (base_url or os.environ.get("BERU_URL") or "").rstrip("/")
72
+ api_key = api_key or os.environ.get("BERU_APP_KEY")
73
+ if not base_url:
74
+ raise ValueError("Give Beru's base URL (base_url=, or BERU_URL).")
75
+ if not api_key:
76
+ raise ValueError("Give the app's key (api_key=, or BERU_APP_KEY).")
77
+ return base_url, {"Authorization": f"Bearer {api_key}", "Accept": "application/json",
78
+ "User-Agent": "beru-sdk-python"}
79
+
80
+
81
+ def error_from(status: int, body: bytes, headers) -> BeruError:
82
+ try:
83
+ data = json.loads(body or b"{}")
84
+ except ValueError:
85
+ data = {}
86
+ message = (data.get("message") or data.get("detail") or f"HTTP {status}") if isinstance(data, dict) else f"HTTP {status}"
87
+ code = data.get("code", "error") if isinstance(data, dict) else "error"
88
+ retry = headers.get("retry-after")
89
+ try:
90
+ retry_after = float(retry) if retry else None
91
+ except ValueError:
92
+ retry_after = None
93
+ return BeruError(str(message), status, str(code), retry_after)
94
+
95
+
96
+ class SSEParser:
97
+ """Server-sent events from lines, as the stream arrives."""
98
+
99
+ def __init__(self) -> None:
100
+ self._id: Optional[str] = None
101
+ self._event: Optional[str] = None
102
+ self._data: List[str] = []
103
+
104
+ def feed(self, line: str) -> Optional[Event]:
105
+ if line == "":
106
+ if not self._data and self._event is None:
107
+ self._id = None
108
+ return None
109
+ raw = "\n".join(self._data)
110
+ ev_id, name = self._id, self._event
111
+ self._id, self._event, self._data = None, None, []
112
+ try:
113
+ body = json.loads(raw) if raw else {}
114
+ except ValueError:
115
+ body = {"raw": raw}
116
+ kind = name or (body.get("type") if isinstance(body, dict) else None) or "message"
117
+ return Event(type=kind, data=body if isinstance(body, dict) else {"value": body}, id=ev_id)
118
+ if line.startswith(":"):
119
+ return None # a keep-alive
120
+ name, _, value = line.partition(":")
121
+ value = value[1:] if value.startswith(" ") else value
122
+ if name == "id":
123
+ self._id = value
124
+ elif name == "event":
125
+ self._event = value
126
+ elif name == "data":
127
+ self._data.append(value)
128
+ return None
129
+
130
+
131
+ def lines_of(chunks: Iterator[str]) -> Iterator[str]:
132
+ """Lines from text chunks, keeping a partial line until its end arrives."""
133
+ buf = ""
134
+ for chunk in chunks:
135
+ buf += chunk
136
+ while True:
137
+ i = buf.find("\n")
138
+ if i < 0:
139
+ break
140
+ line, buf = buf[:i], buf[i + 1:]
141
+ yield line.rstrip("\r")
142
+ if buf:
143
+ yield buf.rstrip("\r")
144
+
145
+
146
+ class Tally:
147
+ """What a stream has said so far: the run, where to resume, the reply, how it ended."""
148
+
149
+ def __init__(self) -> None:
150
+ self.run: Optional[str] = None
151
+ self.last_id: Optional[str] = None
152
+ self.text: List[str] = []
153
+ self.questions: List[Dict[str, Any]] = []
154
+ self.finished: Optional[Event] = None
155
+ self.error: Optional[Event] = None
156
+
157
+ def note(self, ev: Event) -> None:
158
+ if ev.id is not None:
159
+ self.last_id = ev.id
160
+ if ev.type == "run.started" and ev.get("run"):
161
+ self.run = str(ev.get("run"))
162
+ elif ev.type == "message.delta":
163
+ self.text.append(str(ev.get("text") or ""))
164
+ elif ev.type == "question":
165
+ self.questions.append({k: v for k, v in ev.data.items() if k != "type"})
166
+ elif ev.type == "error":
167
+ self.error = ev
168
+ elif ev.type == "run.finished":
169
+ self.finished = ev
170
+
171
+ def result(self) -> Result:
172
+ fin = self.finished.data if self.finished else {}
173
+ status = str(fin.get("status") or ("failed" if self.error else "done"))
174
+ if status == "failed":
175
+ msg = (self.error.get("message") if self.error else None) or fin.get("error") or "The run failed"
176
+ raise RunFailed(str(msg), self.run)
177
+ return Result(run=self.run, status=status, message=fin.get("message"), output=fin.get("output"),
178
+ usage=fin.get("usage"), questions=list(self.questions), text="".join(self.text))
beru_sdk/_sync.py ADDED
@@ -0,0 +1,220 @@
1
+ """The client for ordinary code: a web request, a script, a worker thread."""
2
+ from __future__ import annotations
3
+
4
+ import time
5
+ from typing import Any, Dict, Iterator, List, Optional
6
+
7
+ import httpx
8
+
9
+ from ._core import (API, DEFAULT_TIMEOUT, RECONNECTS, STREAM_READ_TIMEOUT, BeruError, Event, Result, SSEParser,
10
+ Tally, error_from, lines_of, settings)
11
+
12
+
13
+ class _Dropped(Exception):
14
+ """The connection ended before run.finished."""
15
+
16
+
17
+ class RunStream:
18
+ """A run's events as they happen: iterate it, or call text() / result() to wait for the end.
19
+
20
+ Beru keeps the run going if the connection drops; this reconnects from the last event it saw.
21
+ Iterate it once: a second loop continues where the first stopped.
22
+ """
23
+
24
+ def __init__(self, client: "Beru", method: str, path: str, body: Any = None, params: Optional[Dict[str, Any]] = None):
25
+ self._client = client
26
+ self._req = (method, path, body, params)
27
+ self._tally = Tally()
28
+ self._gen: Optional[Iterator[Event]] = None
29
+
30
+ @property
31
+ def run_id(self) -> Optional[str]:
32
+ """The run's id, once run.started has arrived."""
33
+ return self._tally.run
34
+
35
+ def __iter__(self) -> "RunStream":
36
+ return self
37
+
38
+ def __next__(self) -> Event:
39
+ if self._gen is None:
40
+ self._gen = self._events()
41
+ return next(self._gen)
42
+
43
+ def __enter__(self) -> "RunStream":
44
+ return self
45
+
46
+ def __exit__(self, *exc) -> None:
47
+ self.close()
48
+
49
+ def close(self) -> None:
50
+ """Stop listening. The run itself carries on in Beru."""
51
+ if self._gen is not None:
52
+ self._gen.close()
53
+
54
+ def _events(self) -> Iterator[Event]:
55
+ c, (method, path, body, params) = self._client, self._req
56
+ attempts = 0
57
+ while True:
58
+ try:
59
+ with c._http.stream(method, c._url(path), json=body, params=params,
60
+ headers={**c._headers, "Accept": "text/event-stream"},
61
+ timeout=httpx.Timeout(c._timeout, read=STREAM_READ_TIMEOUT)) as response:
62
+ if response.status_code >= 400:
63
+ response.read()
64
+ raise error_from(response.status_code, response.content, response.headers)
65
+ parser = SSEParser()
66
+ for line in lines_of(response.iter_text()):
67
+ ev = parser.feed(line)
68
+ if ev is None:
69
+ continue
70
+ self._tally.note(ev)
71
+ yield ev
72
+ if ev.type == "run.finished":
73
+ return
74
+ raise _Dropped()
75
+ except (httpx.TransportError, _Dropped):
76
+ # Only a run Beru has started can be rejoined: a request that never got that far
77
+ # is not sent again, so a message is never sent twice.
78
+ if self._tally.run is None or attempts >= c._reconnects:
79
+ raise BeruError("The stream ended before the run did.", 0, "stream_lost") from None
80
+ attempts += 1
81
+ time.sleep(min(0.25 * 2 ** attempts, 5.0))
82
+ method, path, body = "GET", f"/runs/{self._tally.run}/events", None
83
+ params = {"after": self._tally.last_id} if self._tally.last_id else None
84
+
85
+ def result(self) -> Result:
86
+ """Wait for the end. Raises RunFailed when the run failed."""
87
+ for _ in self:
88
+ pass
89
+ return self._tally.result()
90
+
91
+ def text(self) -> str:
92
+ """Wait for the end and give the reply's text."""
93
+ res = self.result()
94
+ return res.message if res.message is not None else res.text
95
+
96
+ def cancel(self) -> Dict[str, Any]:
97
+ """Stop the run in Beru."""
98
+ if self.run_id is None:
99
+ for ev in self:
100
+ if ev.type == "run.started":
101
+ break
102
+ if self.run_id is None:
103
+ return {"stopping": False}
104
+ out = self._client._call("POST", f"/runs/{self.run_id}/cancel")
105
+ self.close()
106
+ return out
107
+
108
+
109
+ class _Chats:
110
+ def __init__(self, c: "Beru"):
111
+ self._c = c
112
+
113
+ def create(self, agent: str, user: str, title: Optional[str] = None) -> Dict[str, Any]:
114
+ """A chat for one of your users with one of the app's agents."""
115
+ body = {"agent": agent, "user": user, **({"title": title} if title else {})}
116
+ return self._c._call("POST", "/chats", json=body)
117
+
118
+ def list(self, user: str) -> List[Dict[str, Any]]:
119
+ return self._c._call("GET", "/chats", params={"user": user})["chats"]
120
+
121
+ def messages(self, chat: str) -> List[Dict[str, Any]]:
122
+ return self._c._call("GET", f"/chats/{chat}/messages")["messages"]
123
+
124
+ def send(self, chat: str, text: str) -> RunStream:
125
+ """Send a message; the reply streams. `.text()` waits for it whole."""
126
+ return RunStream(self._c, "POST", f"/chats/{chat}/messages", {"text": text})
127
+
128
+
129
+ class _Workflows:
130
+ def __init__(self, c: "Beru"):
131
+ self._c = c
132
+
133
+ def run(self, workflow: str, input: Optional[Dict[str, Any]] = None, user: Optional[str] = None) -> RunStream:
134
+ """Run a workflow; its steps stream. `.result().output` waits for its result."""
135
+ body: Dict[str, Any] = {"input": input or {}}
136
+ if user is not None:
137
+ body["user"] = user
138
+ return RunStream(self._c, "POST", f"/workflows/{workflow}/runs", body)
139
+
140
+ def start(self, workflow: str, input: Optional[Dict[str, Any]] = None, user: Optional[str] = None) -> str:
141
+ """Start a workflow and return its run id at once; the run carries on in Beru. Follow it
142
+ later with `runs.events(run)` or check it with `workflows.get_run(workflow, run)`."""
143
+ stream = self.run(workflow, input, user)
144
+ try:
145
+ for ev in stream:
146
+ if ev.type == "run.started":
147
+ break
148
+ finally:
149
+ stream.close()
150
+ if stream.run_id is None:
151
+ raise BeruError("Beru did not start the run.", 0, "not_started")
152
+ return stream.run_id
153
+
154
+ def get_run(self, workflow: str, run: str) -> Dict[str, Any]:
155
+ """A run's status (running, done, stopped, failed) and, once done, its output."""
156
+ return self._c._call("GET", f"/workflows/{workflow}/runs/{run}")
157
+
158
+
159
+ class _Runs:
160
+ def __init__(self, c: "Beru"):
161
+ self._c = c
162
+
163
+ def events(self, run: str, after: Optional[str] = None) -> RunStream:
164
+ """Follow a run (again), from after an event id if given."""
165
+ stream = RunStream(self._c, "GET", f"/runs/{run}/events", None, {"after": after} if after else None)
166
+ stream._tally.run = run
167
+ return stream
168
+
169
+ def cancel(self, run: str) -> Dict[str, Any]:
170
+ return self._c._call("POST", f"/runs/{run}/cancel")
171
+
172
+
173
+ class _Users:
174
+ def __init__(self, c: "Beru"):
175
+ self._c = c
176
+
177
+ def forget(self, user: str) -> Dict[str, Any]:
178
+ """Delete one of your users' chats, runs and record in Beru."""
179
+ return self._c._call("DELETE", f"/users/{user}")
180
+
181
+
182
+ class Beru:
183
+ """A Beru instance's apps API, with an app's key.
184
+
185
+ beru = Beru("https://beru.example.com", api_key="beru_sk_…") # or BERU_URL, BERU_APP_KEY
186
+ chat = beru.chats.create(agent="<agent id>", user="u_123")
187
+ print(beru.chats.send(chat["id"], "Where is my order?").text())
188
+ """
189
+
190
+ def __init__(self, base_url: Optional[str] = None, api_key: Optional[str] = None, *,
191
+ timeout: float = DEFAULT_TIMEOUT, http_client: Optional[httpx.Client] = None,
192
+ reconnects: int = RECONNECTS):
193
+ self._base, self._headers = settings(base_url, api_key)
194
+ self._timeout = timeout
195
+ self._own = http_client is None
196
+ self._http = http_client or httpx.Client(timeout=timeout)
197
+ self._reconnects = reconnects
198
+ self.chats = _Chats(self)
199
+ self.workflows = _Workflows(self)
200
+ self.runs = _Runs(self)
201
+ self.users = _Users(self)
202
+
203
+ def _url(self, path: str) -> str:
204
+ return f"{self._base}{API}{path}"
205
+
206
+ def _call(self, method: str, path: str, *, json: Any = None, params: Optional[Dict[str, Any]] = None) -> Any:
207
+ response = self._http.request(method, self._url(path), json=json, params=params, headers=self._headers)
208
+ if response.status_code >= 400:
209
+ raise error_from(response.status_code, response.content, response.headers)
210
+ return response.json() if response.content else {}
211
+
212
+ def close(self) -> None:
213
+ if self._own:
214
+ self._http.close()
215
+
216
+ def __enter__(self) -> "Beru":
217
+ return self
218
+
219
+ def __exit__(self, *exc) -> None:
220
+ self.close()
beru_sdk/py.typed ADDED
File without changes
@@ -0,0 +1,46 @@
1
+ Metadata-Version: 2.5
2
+ Name: beru-sdk
3
+ Version: 1.0.0a13
4
+ Summary: Use a Beru instance as your app's AI layer: chats with its agents and runs of its workflows, streamed.
5
+ Project-URL: Documentation, https://docs.beru-cloud.dev/agents/apps-sdk
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Typing :: Typed
10
+ Requires-Python: >=3.9
11
+ Requires-Dist: httpx>=0.24
12
+ Description-Content-Type: text/markdown
13
+
14
+ # beru-sdk
15
+
16
+ Use a [Beru](https://docs.beru-cloud.dev) instance as your app's AI layer from Python: chat with its
17
+ agents and run its workflows as your own users, with the answers streamed. Beru keeps the agents,
18
+ their tools and every run.
19
+
20
+ You need an app and its key from **Settings → Apps** on your instance (developer mode). Keep the key
21
+ on your server.
22
+
23
+ ```python
24
+ from beru_sdk import Beru
25
+
26
+ beru = Beru("https://beru.example.com", api_key="beru_sk_…") # or BERU_URL and BERU_APP_KEY
27
+
28
+ chat = beru.chats.create(agent="<agent id>", user="u_123")
29
+ for event in beru.chats.send(chat["id"], "Where is my order?"):
30
+ if event.type == "message.delta":
31
+ print(event.text, end="")
32
+
33
+ # Or wait for the whole reply
34
+ reply = beru.chats.send(chat["id"], "And when will it arrive?").text()
35
+
36
+ # Workflows: wait for the result, or start one and come back for it
37
+ result = beru.workflows.run("<workflow id>", input={"order": 42}, user="u_123").result()
38
+ run = beru.workflows.start("<workflow id>", input={"order": 42})
39
+ status = beru.workflows.get_run("<workflow id>", run)
40
+ ```
41
+
42
+ `AsyncBeru` has the same calls, awaited, for asyncio code. A stream that drops is rejoined from the
43
+ last event; a message is never sent twice. Errors are `BeruError` with Beru's `status`, `code` and
44
+ `retry_after`; a run that fails raises `RunFailed`.
45
+
46
+ The calls and events are documented in Beru's docs: *Use Beru from your app* and *Apps API reference*.
@@ -0,0 +1,9 @@
1
+ beru_sdk/__init__.py,sha256=NrkogEGPjcjYkGPtgE6aeZoWe2YPhKvTDGday9fTPFU,1027
2
+ beru_sdk/_async.py,sha256=qqj2gs-UoPilfpoaBTmd4ClLfvxJZGDPjqhUQTx58gg,8186
3
+ beru_sdk/_core.py,sha256=3SPS8_keRyNilQ8plHKAF768sXoKWjTJzSfAMisK5p0,6573
4
+ beru_sdk/_sync.py,sha256=pH-o5geIcw8IC_89msImjdnfNmhGqw4ccJKMhqxnnR4,8714
5
+ beru_sdk/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ beru_sdk-1.0.0a13.dist-info/METADATA,sha256=3CNKM2xD2AhDHatR4caW1LZ7SpgwcfLSj9RGtOstjSg,1879
7
+ beru_sdk-1.0.0a13.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ beru_sdk-1.0.0a13.dist-info/licenses/LICENSE,sha256=sc0VpMz94IMTZ_Rt-288yEXA6DUElnKIL47KZ3Yd2Vo,1073
9
+ beru_sdk-1.0.0a13.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 The Beru authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.