agentos-sdk-python 0.1.0__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.
@@ -0,0 +1,197 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, AsyncIterator, Iterable, Mapping
5
+ from urllib.parse import urljoin
6
+
7
+ import httpx
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class SseEvent:
12
+ event: str
13
+ data: str
14
+
15
+
16
+ class ApiError(Exception):
17
+ def __init__(self, message: str, status: int, data: Any) -> None:
18
+ super().__init__(message)
19
+ self.status = status
20
+ self.data = data
21
+
22
+
23
+ class ApiClient:
24
+ def __init__(
25
+ self,
26
+ base_url: str | None = None,
27
+ connect_timeout: float = 5.0,
28
+ receive_timeout: float = 10.0,
29
+ http_client: httpx.AsyncClient | None = None,
30
+ ) -> None:
31
+ self.base_url = base_url or "http://localhost:8888"
32
+ timeout = httpx.Timeout(receive_timeout, connect=connect_timeout)
33
+ self._client = http_client or httpx.AsyncClient(timeout=timeout)
34
+ self._owns_client = http_client is None
35
+
36
+ async def aclose(self) -> None:
37
+ if self._owns_client:
38
+ await self._client.aclose()
39
+
40
+ async def request(
41
+ self,
42
+ path: str,
43
+ *,
44
+ method: str | None = None,
45
+ query: Mapping[str, Any] | None = None,
46
+ data: Any = None,
47
+ headers: Mapping[str, str] | None = None,
48
+ ) -> Any:
49
+ response = await self._client.request(
50
+ method or ("GET" if data is None else "POST"),
51
+ self.build_url(path),
52
+ params=_clean_query(query),
53
+ json=data if data is not None else None,
54
+ headers=dict(headers or {}),
55
+ )
56
+ return self._parse_response(response)
57
+
58
+ async def request_stream(
59
+ self,
60
+ path: str,
61
+ *,
62
+ method: str | None = None,
63
+ query: Mapping[str, Any] | None = None,
64
+ data: Any = None,
65
+ headers: Mapping[str, str] | None = None,
66
+ ) -> httpx.Response:
67
+ request = self._client.build_request(
68
+ method or ("GET" if data is None else "POST"),
69
+ self.build_url(path),
70
+ params=_clean_query(query),
71
+ json=data if data is not None else None,
72
+ headers=dict(headers or {}),
73
+ )
74
+ response = await self._client.send(request, stream=True)
75
+ if response.is_error:
76
+ body = await _read_body(response)
77
+ await response.aclose()
78
+ raise ApiError(
79
+ f"Request failed with status {response.status_code}",
80
+ response.status_code,
81
+ body,
82
+ )
83
+ return response
84
+
85
+ async def request_bytes(
86
+ self,
87
+ path: str,
88
+ *,
89
+ method: str = "GET",
90
+ data: Any = None,
91
+ headers: Mapping[str, str] | None = None,
92
+ ) -> bytes:
93
+ response = await self._client.request(
94
+ method,
95
+ self.build_url(path),
96
+ json=data if data is not None else None,
97
+ headers=dict(headers or {}),
98
+ )
99
+ if response.is_error:
100
+ raise ApiError(
101
+ f"Request failed with status {response.status_code}",
102
+ response.status_code,
103
+ _decode_body(response),
104
+ )
105
+ return response.content
106
+
107
+ async def request_multipart(
108
+ self,
109
+ path: str,
110
+ *,
111
+ data: Mapping[str, Any],
112
+ files: Mapping[str, Any],
113
+ ) -> Any:
114
+ response = await self._client.post(self.build_url(path), data=data, files=files)
115
+ if response.is_error:
116
+ raise ApiError(
117
+ f"Request failed with status {response.status_code}",
118
+ response.status_code,
119
+ _decode_body(response),
120
+ )
121
+ return _decode_body(response)
122
+
123
+ def build_url(self, path: str) -> str:
124
+ normalized_base = self.base_url if self.base_url.endswith("/") else f"{self.base_url}/"
125
+ normalized_path = path[1:] if path.startswith("/") else path
126
+ return urljoin(normalized_base, normalized_path)
127
+
128
+ def _parse_response(self, response: httpx.Response) -> Any:
129
+ body = _decode_body(response)
130
+ if response.is_error:
131
+ raise ApiError(
132
+ f"Request failed with status {response.status_code}",
133
+ response.status_code,
134
+ body,
135
+ )
136
+ return body
137
+
138
+
139
+ async def iter_sse(response: httpx.Response) -> AsyncIterator[SseEvent]:
140
+ buffer: list[str] = []
141
+ async for line in response.aiter_lines():
142
+ buffer.append(line)
143
+ if line == "":
144
+ for event in parse_sse_lines(buffer):
145
+ yield event
146
+ buffer.clear()
147
+ if buffer:
148
+ for event in parse_sse_lines(buffer):
149
+ yield event
150
+ await response.aclose()
151
+
152
+
153
+ def parse_sse_lines(lines: Iterable[str]) -> Iterable[SseEvent]:
154
+ current_event = ""
155
+ current_data: list[str] = []
156
+ for raw_line in lines:
157
+ line = raw_line[:-1] if raw_line.endswith("\r") else raw_line
158
+ if line.startswith("event:"):
159
+ current_event = line[6:].strip()
160
+ elif line.startswith("data:"):
161
+ current_data.append(line[5:].strip())
162
+ elif line == "" and current_data:
163
+ yield SseEvent(event=current_event or "message", data="\n".join(current_data))
164
+ current_event = ""
165
+ current_data = []
166
+ if current_data:
167
+ yield SseEvent(event=current_event or "message", data="\n".join(current_data))
168
+
169
+
170
+ async def _read_body(response: httpx.Response) -> Any:
171
+ content = await response.aread()
172
+ if not content:
173
+ return None
174
+ text = content.decode(errors="replace")
175
+ try:
176
+ return response.json()
177
+ except ValueError:
178
+ return text
179
+
180
+
181
+ def _decode_body(response: httpx.Response) -> Any:
182
+ if not response.content:
183
+ return None
184
+ try:
185
+ return response.json()
186
+ except ValueError:
187
+ return response.text
188
+
189
+
190
+ def _clean_query(query: Mapping[str, Any] | None) -> dict[str, str]:
191
+ if not query:
192
+ return {}
193
+ return {
194
+ key: value.isoformat() if hasattr(value, "isoformat") else str(value)
195
+ for key, value in query.items()
196
+ if value is not None and value != ""
197
+ }
@@ -0,0 +1,234 @@
1
+ Metadata-Version: 2.4
2
+ Name: agentos-sdk-python
3
+ Version: 0.1.0
4
+ Summary: Async Python SDK for AgentOS APIs.
5
+ Project-URL: Repository, https://gitlab.litevar.com/litevar/agentos/agentos-sdk-python
6
+ Project-URL: Issues, https://gitlab.litevar.com/litevar/agentos/agentos-sdk-python/-/issues
7
+ Author: LiteVar
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: agentkit,agentos,async,modelkit,sdk,toolkit
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: httpx<1,>=0.27
25
+ Provides-Extra: dev
26
+ Requires-Dist: build<2,>=1.2; extra == 'dev'
27
+ Requires-Dist: pytest-asyncio<1,>=0.23; extra == 'dev'
28
+ Requires-Dist: pytest<9,>=8; extra == 'dev'
29
+ Requires-Dist: ruff<1,>=0.5; extra == 'dev'
30
+ Requires-Dist: twine<7,>=6; extra == 'dev'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # AgentOS SDK for Python
34
+
35
+ Async Python SDK for AgentOS APIs. The package is a thin client over AgentOS HTTP and SSE endpoints with small compatibility helpers for bearer tokens, stream callbacks, Pythonic method names, and request defaults.
36
+
37
+ ## Install
38
+
39
+ ```bash
40
+ pip install agentos-sdk-python
41
+ ```
42
+
43
+ For local development:
44
+
45
+ ```bash
46
+ python3 -m venv .venv
47
+ .venv/bin/python -m pip install -e ".[dev]"
48
+ ```
49
+
50
+ ## Quickstart
51
+
52
+ ```python
53
+ from agentos_sdk import AgentOSSDK
54
+
55
+
56
+ async def main():
57
+ async with AgentOSSDK(base_url="http://localhost:8888") as sdk:
58
+ version = await sdk.agentos.get_version()
59
+ print(version)
60
+
61
+ await sdk.agentos.register_bundle(
62
+ {"bundleId": "com.demo.app", "appGroupId": "com.demo.group"}
63
+ )
64
+
65
+ tasks = await sdk.cronkit.list_tasks(limit=10)
66
+ print(tasks)
67
+ ```
68
+
69
+ `AgentOSSDK` also exposes TS-style camelCase aliases for common migration paths, such as `registerBundle`, `listTasks`, `chatSimple`, `listModels`, and `loadTool`.
70
+
71
+ ## Transport
72
+
73
+ The SDK uses `httpx.AsyncClient` and defaults to `http://localhost:8888`.
74
+
75
+ ```python
76
+ from agentos_sdk import AgentOSSDK
77
+
78
+ sdk = AgentOSSDK(
79
+ base_url="http://localhost:8888",
80
+ connect_timeout=5.0,
81
+ receive_timeout=10.0,
82
+ )
83
+ ```
84
+
85
+ Use `async with AgentOSSDK(...)` or call `await sdk.aclose()` when done.
86
+
87
+ ## Token Handling
88
+
89
+ `sdk.agentos.register_bundle(...)` stores the active app token. Protected facade methods in `sdk.agentkit` and `sdk.cronkit` use that token automatically.
90
+
91
+ If a protected call fails with HTTP `401`, HTTP `403`, or recognizable invalid-token text, the SDK re-runs registration for the same bundle once and retries the call.
92
+
93
+ ## AgentOS Events
94
+
95
+ ```python
96
+ from agentos_sdk import AgentOSEventHandler, AgentOSSDK
97
+
98
+
99
+ class Handler(AgentOSEventHandler):
100
+ async def on_welcome(self, welcome):
101
+ print("welcome", welcome)
102
+
103
+ async def on_call_app(self, call):
104
+ print("call app", call)
105
+
106
+ async def on_done(self):
107
+ print("subscription ended")
108
+
109
+ async def on_error(self, error):
110
+ raise error
111
+
112
+
113
+ async with AgentOSSDK() as sdk:
114
+ await sdk.agentos.register_bundle({"bundleId": "com.demo.app"})
115
+ await sdk.agentos.subscribe(Handler())
116
+ ```
117
+
118
+ ## AgentKit
119
+
120
+ ```python
121
+ from agentos_sdk import AgentMessageHandler, AgentOSSDK, ToolReturn
122
+
123
+
124
+ class ChatHandler(AgentMessageHandler):
125
+ async def on_message(self, session_id, message):
126
+ print("message", session_id, message)
127
+
128
+ async def on_chunk(self, session_id, chunk):
129
+ print("chunk", session_id, chunk)
130
+
131
+ async def on_function_call(self, session_id, function_call):
132
+ return ToolReturn(function_call["id"], {"ok": True})
133
+
134
+ async def on_done(self):
135
+ print("done")
136
+
137
+ async def on_error(self, error):
138
+ raise error
139
+
140
+
141
+ async with AgentOSSDK() as sdk:
142
+ await sdk.agentos.register_bundle({"bundleId": "com.demo.app"})
143
+ session = await sdk.agentkit.init_session()
144
+ await sdk.agentkit.chat(
145
+ session,
146
+ {"content": [{"type": "text", "message": "Hello"}]},
147
+ ChatHandler(),
148
+ )
149
+ ```
150
+
151
+ Direct AgentKit methods include `get_agent`, `create_agent`, `update_agent`, `delete_agent`, `init_session`, `init_simple`, `chat`, `chat_simple`, `history`, `stop`, `clear`, `callback`, and `stream_callback`.
152
+
153
+ ## CronKit
154
+
155
+ ```python
156
+ async with AgentOSSDK() as sdk:
157
+ await sdk.agentos.register_bundle({"bundleId": "com.demo.app"})
158
+ task = await sdk.cronkit.create_task(
159
+ request={
160
+ "name": "Daily summary",
161
+ "schedule": "0 9 * * *",
162
+ "spec": {
163
+ "systemPrompt": "You are a scheduled agent.",
164
+ "content": [{"type": "text", "message": "Summarize today."}],
165
+ },
166
+ }
167
+ )
168
+ await sdk.cronkit.run_task_now(cron_id=task["cronId"])
169
+ ```
170
+
171
+ CronKit create requests default `concurrency` to `skipIfRunning`, `enabled` to `True`, and `spec.timeoutSeconds` to `3600`.
172
+
173
+ ## ModelKit
174
+
175
+ ```python
176
+ async with AgentOSSDK() as sdk:
177
+ models = await sdk.modelkit.list_models()
178
+ chat_models = await sdk.modelkit.list_models_by_task("chat")
179
+
180
+ completion = await sdk.modelkit.chat.create(
181
+ {
182
+ "model": "qwen3-1.7b",
183
+ "messages": [{"role": "user", "content": "Hello"}],
184
+ "maxTokens": 128,
185
+ }
186
+ )
187
+
188
+ async for chunk in sdk.modelkit.chat.create_stream(
189
+ {"model": "qwen3-1.7b", "messages": [{"role": "user", "content": "Stream"}]}
190
+ ):
191
+ print(chunk)
192
+ ```
193
+
194
+ ModelKit also supports:
195
+
196
+ - `sdk.modelkit.embedding.create(...)`
197
+ - `sdk.modelkit.asr.transcribe(...)`
198
+ - `sdk.modelkit.tts.synthesize(...)`
199
+ - `sdk.modelkit.tts.list_voices()`
200
+
201
+ ## ToolKit
202
+
203
+ ```python
204
+ async with AgentOSSDK() as sdk:
205
+ tools = await sdk.toolkit.list_tool()
206
+ definition = await sdk.toolkit.load_tool("tool-id")
207
+ raw_json = definition.to_json() if definition else None
208
+
209
+ async for event in sdk.toolkit.subscribe_tool_events("daemon-api-key"):
210
+ print(event)
211
+ ```
212
+
213
+ `load_tool()` returns an `OpenToolDefinition` wrapper that preserves the raw JSON definition. It does not execute tools or implement browser/daemon OpenTool bridging.
214
+
215
+ ## Direct Clients
216
+
217
+ The low-level clients are available for explicit-token or custom transport usage:
218
+
219
+ ```python
220
+ from agentos_sdk.clients import AgentKitClient, CronKitClient, ModelKitClient
221
+ from agentos_sdk.transport import ApiClient
222
+
223
+ api = ApiClient(base_url="http://localhost:8888")
224
+ agentkit = AgentKitClient(api)
225
+ agent = await agentkit.get_agent("bearer-token", "agent-id")
226
+ ```
227
+
228
+ ## Development
229
+
230
+ ```bash
231
+ .venv/bin/python -m compileall agentos_sdk
232
+ .venv/bin/python -m pytest -q
233
+ .venv/bin/ruff check .
234
+ ```
@@ -0,0 +1,18 @@
1
+ agentos_sdk/__init__.py,sha256=7U22SmKkmvg4OGpm38TkxHb7hCW4tMZvC0qxHbrpoII,338
2
+ agentos_sdk/handlers.py,sha256=SFqO37CURI_wP3u74gg-jIi0AkMTU1-Ll6CkPxrEH1o,2345
3
+ agentos_sdk/normalizers.py,sha256=5UWKFsoWyneNs_h591HlbTpyT0t8Y-uhVXCw4d-bS5M,4667
4
+ agentos_sdk/protocol.py,sha256=tO9ZFNHeAsmAyXaHqEz_87Bg6jX4X3rlltO92QtYnaI,1020
5
+ agentos_sdk/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
6
+ agentos_sdk/sdk.py,sha256=wL4nVDtSNNyNw16t5_uH_5a9xzsY7hkOiPokqFM_w50,18088
7
+ agentos_sdk/transport.py,sha256=4LZcHakho7gcAP0Vp7bcloaphtwt8zkn1I-0fGm-2pQ,6118
8
+ agentos_sdk/clients/__init__.py,sha256=00BGApsygO3CoCFZsRGSyEF426mr2CvO_EK-enRdX_Q,360
9
+ agentos_sdk/clients/agentkit.py,sha256=0_tQ6V-syoNnz2yVrU0VSUOBIUL0DIP74W-leZUul2s,5384
10
+ agentos_sdk/clients/appkit.py,sha256=06O68CSCcFtpIWets9cvt7j2il19Fmrh0op91JVJXmg,825
11
+ agentos_sdk/clients/cronkit.py,sha256=DiprjNhV3VEXXY5i15Ghgj5WgjHeoVfIEqs2zhuTRcY,4858
12
+ agentos_sdk/clients/modelkit.py,sha256=NkWOJ1dqFjkQMrON2kKDW9OZ2lyGOVz-E6wx98VIUXc,4660
13
+ agentos_sdk/clients/systemkit.py,sha256=1afOdJ_SUuMLP6b28FG2E2POf9OZisNHHBcm8YW0b6s,641
14
+ agentos_sdk/clients/toolkit.py,sha256=ZGyYYrNcTJ2RealHWYynSF-rXHbRnjMpUi3w83cP6eo,1415
15
+ agentos_sdk_python-0.1.0.dist-info/METADATA,sha256=5DA2E5jc30Yb24wpGqYHpwwuyZerxwYA5V7gs8aRKK0,6962
16
+ agentos_sdk_python-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
17
+ agentos_sdk_python-0.1.0.dist-info/licenses/LICENSE,sha256=oarEto4UtUv6Y2Yeph34qL9zLBJEp0ZjuXrrwQ9uVdg,1064
18
+ agentos_sdk_python-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 LiteVar
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.