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,134 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Mapping
4
+
5
+
6
+ CHAT_FIELD_ALIASES = {
7
+ "toolChoice": "tool_choice",
8
+ "maxTokens": "max_tokens",
9
+ "topP": "top_p",
10
+ "presencePenalty": "presence_penalty",
11
+ "frequencyPenalty": "frequency_penalty",
12
+ "logitBias": "logit_bias",
13
+ "responseFormat": "response_format",
14
+ "streamOptions": "stream_options",
15
+ "topLogprobs": "top_logprobs",
16
+ "reasoningEffort": "reasoning_effort",
17
+ "enableThinking": "enable_thinking",
18
+ }
19
+
20
+
21
+ def normalize_llm_config(config: Mapping[str, Any] | None) -> dict[str, Any] | None:
22
+ if not config:
23
+ return None
24
+ return {
25
+ "modelId": config.get("modelId"),
26
+ "baseUrl": config.get("baseUrl"),
27
+ "apiKey": config.get("apiKey"),
28
+ "model": config.get("model"),
29
+ "temperature": config.get("temperature", 0),
30
+ "maxTokens": config.get("maxTokens", 4096),
31
+ "contextWindowSize": config.get("contextWindowSize"),
32
+ "topP": config.get("topP", 1),
33
+ "supportsToolCall": config.get(
34
+ "supportsToolCall", config.get("supportsToolCalling", True)
35
+ ),
36
+ "supportsReasoning": config.get(
37
+ "supportsReasoning", config.get("supportsDeepThinking", True)
38
+ ),
39
+ }
40
+
41
+
42
+ def normalize_simple_capability(capability: Mapping[str, Any]) -> dict[str, Any]:
43
+ result = dict(capability)
44
+ normalized = normalize_llm_config(capability.get("llmConfig"))
45
+ if normalized is None:
46
+ result.pop("llmConfig", None)
47
+ else:
48
+ result["llmConfig"] = normalized
49
+ return result
50
+
51
+
52
+ def normalize_capability(capability: Mapping[str, Any]) -> dict[str, Any]:
53
+ result = normalize_simple_capability(capability)
54
+ result["timeoutSeconds"] = capability.get("timeoutSeconds", 3600)
55
+ result["taskPipelineStrategy"] = capability.get("taskPipelineStrategy", "parallel")
56
+ if "reflectPromptList" in capability and capability["reflectPromptList"] is not None:
57
+ result["reflectPromptList"] = [
58
+ {**item, "llmConfig": normalize_llm_config(item.get("llmConfig"))}
59
+ for item in capability["reflectPromptList"]
60
+ ]
61
+ if "llmConfigList" in capability and capability["llmConfigList"] is not None:
62
+ result["llmConfigList"] = [normalize_llm_config(item) for item in capability["llmConfigList"]]
63
+ return result
64
+
65
+
66
+ def normalize_user_task(user_task: Mapping[str, Any]) -> dict[str, Any]:
67
+ result = dict(user_task)
68
+ normalized = normalize_llm_config(user_task.get("llmConfig"))
69
+ if normalized is None:
70
+ result.pop("llmConfig", None)
71
+ else:
72
+ result["llmConfig"] = normalized
73
+ return result
74
+
75
+
76
+ def cron_create_defaults(request: Mapping[str, Any]) -> dict[str, Any]:
77
+ spec = dict(request.get("spec", {}))
78
+ spec["timeoutSeconds"] = spec.get("timeoutSeconds", 3600)
79
+ return {
80
+ "concurrency": "skipIfRunning",
81
+ "enabled": True,
82
+ **dict(request),
83
+ "spec": spec,
84
+ }
85
+
86
+
87
+ def serialize_chat_request(request: Mapping[str, Any]) -> dict[str, Any]:
88
+ result: dict[str, Any] = {}
89
+ for key, value in request.items():
90
+ result[CHAT_FIELD_ALIASES.get(key, key)] = value
91
+ return result
92
+
93
+
94
+ def normalize_agent_event_name(event_type: str) -> str:
95
+ if event_type == "agentmessage":
96
+ return "message"
97
+ if event_type == "agentmessagechunk":
98
+ return "chunk"
99
+ return event_type
100
+
101
+
102
+ def normalize_model_info(item: Mapping[str, Any]) -> dict[str, Any]:
103
+ task = str(item.get("task", item.get("type", ""))).lower()
104
+ if task not in {"chat", "embedding", "asr", "tts"}:
105
+ task = "chat"
106
+ raw_caps = item.get("capabilities") if isinstance(item.get("capabilities"), dict) else {}
107
+ return {
108
+ "id": str(item.get("id", "")),
109
+ "name": str(item.get("name", "")),
110
+ "alias": str(item.get("alias", "")),
111
+ "description": item.get("description"),
112
+ "task": task,
113
+ "contextWindowSize": item.get("contextWindowSize"),
114
+ "input": _modalities(item.get("input")),
115
+ "output": _modalities(item.get("output")),
116
+ "capabilities": {
117
+ "vision": bool(raw_caps.get("vision")),
118
+ "tool_call": bool(raw_caps.get("tool_call")),
119
+ "stream": bool(raw_caps.get("stream", True)),
120
+ },
121
+ "isRemote": bool(item.get("isRemote", False)),
122
+ "isCustom": bool(item.get("isCustom", False)),
123
+ }
124
+
125
+
126
+ def _modalities(value: Any) -> list[str]:
127
+ if not isinstance(value, list) or not value:
128
+ return ["text"]
129
+ result = [
130
+ str(item).lower()
131
+ for item in value
132
+ if str(item).lower() in {"text", "image", "audio", "video"}
133
+ ]
134
+ return result or ["text"]
@@ -0,0 +1,51 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Literal, NotRequired, TypedDict
4
+
5
+ JsonMap = dict[str, Any]
6
+ ContentType = Literal["text", "imageUrl"]
7
+ ModelTask = Literal["chat", "embedding", "asr", "tts"]
8
+ Modality = Literal["text", "image", "audio", "video"]
9
+
10
+
11
+ class Content(TypedDict):
12
+ type: str
13
+ message: str
14
+
15
+
16
+ class AppBundle(TypedDict):
17
+ bundleId: str
18
+ appGroupId: NotRequired[str]
19
+
20
+
21
+ class AccessToken(TypedDict):
22
+ token: str
23
+ bundleId: NotRequired[str]
24
+ appGroupId: NotRequired[str]
25
+
26
+
27
+ class Session(TypedDict):
28
+ sessionId: str
29
+
30
+
31
+ class ToolReturn(TypedDict):
32
+ id: str
33
+ result: Any
34
+
35
+
36
+ class EventToolReturn(TypedDict):
37
+ event: str
38
+ toolReturn: ToolReturn
39
+
40
+
41
+ class OpenToolDefinition:
42
+ def __init__(self, raw: JsonMap) -> None:
43
+ self.raw = raw
44
+ info = raw.get("info")
45
+ self.info = info if isinstance(info, dict) else {}
46
+
47
+ def to_json(self) -> JsonMap:
48
+ return dict(self.raw)
49
+
50
+ def toJson(self) -> JsonMap:
51
+ return self.to_json()
agentos_sdk/py.typed ADDED
@@ -0,0 +1 @@
1
+
agentos_sdk/sdk.py ADDED
@@ -0,0 +1,485 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import json
5
+ from dataclasses import dataclass
6
+ from typing import Any, Awaitable, Callable, Mapping
7
+
8
+ import httpx
9
+
10
+ from agentos_sdk.clients.agentkit import AgentKitClient
11
+ from agentos_sdk.clients.appkit import AppKitClient
12
+ from agentos_sdk.clients.cronkit import CronKitClient
13
+ from agentos_sdk.clients.modelkit import ModelKitClient
14
+ from agentos_sdk.clients.systemkit import SystemKitClient
15
+ from agentos_sdk.clients.toolkit import ToolKitClient
16
+ from agentos_sdk.handlers import AgentMessageHandler, AgentOSEventHandler, ToolReturn
17
+ from agentos_sdk.transport import ApiClient, ApiError
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class _AppAuthKey:
22
+ bundle_id: str
23
+ app_group_id: str | None = None
24
+
25
+
26
+ @dataclass
27
+ class _AppAuthContext:
28
+ key: _AppAuthKey
29
+ token: str
30
+
31
+
32
+ class AgentOSSDK:
33
+ def __init__(
34
+ self,
35
+ *,
36
+ base_url: str | None = None,
37
+ connect_timeout: float = 5.0,
38
+ receive_timeout: float = 10.0,
39
+ api_client: ApiClient | None = None,
40
+ http_client: httpx.AsyncClient | None = None,
41
+ ) -> None:
42
+ self.api_client = api_client or ApiClient(
43
+ base_url=base_url,
44
+ connect_timeout=connect_timeout,
45
+ receive_timeout=receive_timeout,
46
+ http_client=http_client,
47
+ )
48
+ self.systemKit = SystemKitClient(self.api_client)
49
+ self.appKit = AppKitClient(self.api_client)
50
+ self.agentKit = AgentKitClient(self.api_client)
51
+ self.cronKit = CronKitClient(self.api_client)
52
+ self.modelKit = ModelKitClient(self.api_client)
53
+ self.toolKit = ToolKitClient(self.api_client)
54
+ self._tokens: dict[_AppAuthKey, str] = {}
55
+ self._token_contexts: dict[str, _AppAuthKey] = {}
56
+ self._refresh_locks: dict[_AppAuthKey, asyncio.Lock] = {}
57
+ self._active_key: _AppAuthKey | None = None
58
+ self.agentos = AgentOSModule(self)
59
+ self.agentkit = AgentKitModule(self)
60
+ self.cronkit = CronKitModule(self)
61
+ self.modelkit = ModelKitModule(self)
62
+ self.toolkit = ToolKitModule(self)
63
+
64
+ async def __aenter__(self) -> AgentOSSDK:
65
+ return self
66
+
67
+ async def __aexit__(self, exc_type, exc, tb) -> None:
68
+ await self.aclose()
69
+
70
+ async def aclose(self) -> None:
71
+ await self.api_client.aclose()
72
+
73
+ async def dispose(self) -> None:
74
+ await self.aclose()
75
+
76
+ async def register_bundle(self, bundle: Mapping[str, Any]) -> dict[str, Any]:
77
+ info = await self.appKit.register_bundle(bundle)
78
+ key = _AppAuthKey(bundle_id=bundle["bundleId"], app_group_id=bundle.get("appGroupId"))
79
+ self._cache_token(key, info["token"], activate=True)
80
+ return info
81
+
82
+ async def _require_auth_context(self) -> _AppAuthContext:
83
+ if self._active_key is None:
84
+ raise RuntimeError("Bearer token is not set. Call agentos.register_bundle() first.")
85
+ token = self._tokens.get(self._active_key)
86
+ if not token:
87
+ raise RuntimeError("Bearer token is not set. Call agentos.register_bundle() first.")
88
+ return _AppAuthContext(self._active_key, token)
89
+
90
+ async def _with_app_auth_retry(self, action: Callable[[str], Awaitable[Any]]) -> Any:
91
+ context = await self._require_auth_context()
92
+ try:
93
+ return await action(context.token)
94
+ except Exception as error:
95
+ if not self._should_recover_app_auth(error):
96
+ raise
97
+ refreshed = await self._refresh_app_token(context, context.token)
98
+ return await action(refreshed)
99
+
100
+ def _cache_token(self, key: _AppAuthKey, token: str, *, activate: bool) -> None:
101
+ previous = self._tokens.get(key)
102
+ if previous and previous != token:
103
+ self._token_contexts.pop(previous, None)
104
+ self._tokens[key] = token
105
+ self._token_contexts[token] = key
106
+ if activate:
107
+ self._active_key = key
108
+
109
+ async def _refresh_app_token(self, context: _AppAuthContext, failed_token: str) -> str:
110
+ key = self._token_contexts.get(failed_token, context.key)
111
+ current = self._tokens.get(key)
112
+ if current and current != failed_token:
113
+ return current
114
+ lock = self._refresh_locks.setdefault(key, asyncio.Lock())
115
+ async with lock:
116
+ current = self._tokens.get(key)
117
+ if current and current != failed_token:
118
+ return current
119
+ self._tokens.pop(key, None)
120
+ self._token_contexts.pop(failed_token, None)
121
+ bundle: dict[str, Any] = {"bundleId": key.bundle_id}
122
+ if key.app_group_id:
123
+ bundle["appGroupId"] = key.app_group_id
124
+ info = await self.appKit.register_bundle(bundle)
125
+ self._cache_token(key, info["token"], activate=False)
126
+ return info["token"]
127
+
128
+ def _should_recover_app_auth(self, error: Exception) -> bool:
129
+ if isinstance(error, ApiError) and error.status in {401, 403}:
130
+ return True
131
+ text = _collect_error_text(error).lower()
132
+ return any(
133
+ marker in text
134
+ for marker in ["invalid app token", "token expired", "unauthorized", "forbidden", "auth"]
135
+ )
136
+
137
+
138
+ class AgentOSModule:
139
+ def __init__(self, sdk: AgentOSSDK) -> None:
140
+ self._sdk = sdk
141
+
142
+ async def get_version(self) -> dict[str, Any]:
143
+ return await self._sdk.systemKit.get_version()
144
+
145
+ async def get_root(self) -> dict[str, Any]:
146
+ return await self._sdk.systemKit.get_root()
147
+
148
+ async def get_ready(self) -> dict[str, Any]:
149
+ return await self._sdk.systemKit.get_ready()
150
+
151
+ async def register_bundle(self, bundle: Mapping[str, Any]) -> dict[str, Any]:
152
+ return await self._sdk.register_bundle(bundle)
153
+
154
+ async def subscribe(self, handler: AgentOSEventHandler) -> None:
155
+ context = await self._sdk._require_auth_context()
156
+ try:
157
+ async for event in self._sdk.appKit.subscribe(context.token):
158
+ data = json.loads(event.data)
159
+ if event.event == "welcome":
160
+ await _call_handler(handler, "on_welcome", "onWelcome", data)
161
+ elif event.event == "callApp":
162
+ await _call_handler(handler, "on_call_app", "onCallApp", data)
163
+ elif event.event == "error":
164
+ await _call_handler(
165
+ handler,
166
+ "on_error",
167
+ "onError",
168
+ RuntimeError(str(data.get("error", data))),
169
+ )
170
+ await _call_handler(handler, "on_done", "onDone")
171
+ except Exception as error:
172
+ await _call_handler(handler, "on_error", "onError", error)
173
+
174
+ getVersion = get_version
175
+ getRoot = get_root
176
+ getReady = get_ready
177
+ registerBundle = register_bundle
178
+
179
+
180
+ class CronKitModule:
181
+ def __init__(self, sdk: AgentOSSDK) -> None:
182
+ self._sdk = sdk
183
+
184
+ async def get_task(self, *, cron_id: str) -> dict[str, Any]:
185
+ return await self._sdk._with_app_auth_retry(
186
+ lambda token: self._sdk.cronKit.get_task(token, cron_id)
187
+ )
188
+
189
+ async def list_tasks(
190
+ self,
191
+ *,
192
+ enabled: bool | None = None,
193
+ offset: int | None = None,
194
+ limit: int | None = None,
195
+ ) -> list[dict[str, Any]]:
196
+ return await self._sdk._with_app_auth_retry(
197
+ lambda token: self._sdk.cronKit.list_tasks(
198
+ token, enabled=enabled, offset=offset, limit=limit
199
+ )
200
+ )
201
+
202
+ async def create_task(self, *, request: Mapping[str, Any]) -> dict[str, Any]:
203
+ return await self._sdk._with_app_auth_retry(
204
+ lambda token: self._sdk.cronKit.create_task(token, request)
205
+ )
206
+
207
+ async def update_task(self, *, request: Mapping[str, Any]) -> dict[str, Any]:
208
+ return await self._sdk._with_app_auth_retry(
209
+ lambda token: self._sdk.cronKit.update_task(token, request)
210
+ )
211
+
212
+ async def delete_task(self, *, cron_id: str) -> dict[str, Any]:
213
+ return await self._sdk._with_app_auth_retry(
214
+ lambda token: self._sdk.cronKit.delete_task(token, cron_id)
215
+ )
216
+
217
+ async def enable_task(self, *, cron_id: str) -> dict[str, Any]:
218
+ return await self._sdk._with_app_auth_retry(
219
+ lambda token: self._sdk.cronKit.enable_task(token, cron_id)
220
+ )
221
+
222
+ async def disable_task(self, *, cron_id: str) -> dict[str, Any]:
223
+ return await self._sdk._with_app_auth_retry(
224
+ lambda token: self._sdk.cronKit.disable_task(token, cron_id)
225
+ )
226
+
227
+ async def run_task_now(self, *, cron_id: str, scheduled_at=None) -> dict[str, Any]:
228
+ return await self._sdk._with_app_auth_retry(
229
+ lambda token: self._sdk.cronKit.run_task_now(token, cron_id, scheduled_at)
230
+ )
231
+
232
+ async def get_run(self, *, run_id: str) -> dict[str, Any]:
233
+ return await self._sdk._with_app_auth_retry(
234
+ lambda token: self._sdk.cronKit.get_run(token, run_id)
235
+ )
236
+
237
+ async def list_runs(self, **options) -> list[dict[str, Any]]:
238
+ return await self._sdk._with_app_auth_retry(
239
+ lambda token: self._sdk.cronKit.list_runs(token, **options)
240
+ )
241
+
242
+ async def list_run_messages(
243
+ self, *, run_id: str, offset: int | None = None, limit: int | None = None
244
+ ) -> list[dict[str, Any]]:
245
+ return await self._sdk._with_app_auth_retry(
246
+ lambda token: self._sdk.cronKit.list_run_messages(
247
+ token, run_id, offset=offset, limit=limit
248
+ )
249
+ )
250
+
251
+ async def delete_run(self, *, run_id: str) -> dict[str, Any]:
252
+ return await self._sdk._with_app_auth_retry(
253
+ lambda token: self._sdk.cronKit.delete_run(token, run_id)
254
+ )
255
+
256
+ getTask = get_task
257
+ listTasks = list_tasks
258
+ createTask = create_task
259
+ updateTask = update_task
260
+ deleteTask = delete_task
261
+ enableTask = enable_task
262
+ disableTask = disable_task
263
+ runTaskNow = run_task_now
264
+ getRun = get_run
265
+ listRuns = list_runs
266
+ listRunMessages = list_run_messages
267
+ deleteRun = delete_run
268
+
269
+
270
+ class AgentKitModule:
271
+ def __init__(self, sdk: AgentOSSDK) -> None:
272
+ self._sdk = sdk
273
+
274
+ async def get_agent(self, *, agent_id: str) -> dict[str, Any]:
275
+ return await self._sdk._with_app_auth_retry(
276
+ lambda token: self._sdk.agentKit.get_agent(token, agent_id)
277
+ )
278
+
279
+ async def create_agent(self, *, agent: Mapping[str, Any]) -> dict[str, Any]:
280
+ return await self._sdk._with_app_auth_retry(
281
+ lambda token: self._sdk.agentKit.create_agent(token, agent)
282
+ )
283
+
284
+ async def update_agent(
285
+ self, *, agent_id: str, agent: Mapping[str, Any]
286
+ ) -> dict[str, Any]:
287
+ return await self._sdk._with_app_auth_retry(
288
+ lambda token: self._sdk.agentKit.update_agent(token, agent_id, agent)
289
+ )
290
+
291
+ async def delete_agent(self, *, agent_id: str) -> dict[str, Any]:
292
+ return await self._sdk._with_app_auth_retry(
293
+ lambda token: self._sdk.agentKit.delete_agent(token, agent_id)
294
+ )
295
+
296
+ async def init_session(
297
+ self, *, agent_id: str | None = None, capability: Mapping[str, Any] | None = None
298
+ ) -> dict[str, Any]:
299
+ return await self._sdk._with_app_auth_retry(
300
+ lambda token: self._sdk.agentKit.init_session(
301
+ token, agent_id=agent_id, capability=capability
302
+ )
303
+ )
304
+
305
+ async def init_simple(self, *, simple_capability: Mapping[str, Any]) -> dict[str, Any]:
306
+ return await self._sdk._with_app_auth_retry(
307
+ lambda token: self._sdk.agentKit.init_simple(token, simple_capability)
308
+ )
309
+
310
+ async def chat(
311
+ self, session: Mapping[str, Any], user_task: Mapping[str, Any], handler: AgentMessageHandler
312
+ ) -> None:
313
+ session_id = session["sessionId"]
314
+ try:
315
+ stream = await self._sdk._with_app_auth_retry(
316
+ lambda token: _identity(self._sdk.agentKit.chat(token, session_id, user_task))
317
+ )
318
+ async for event in stream:
319
+ data = json.loads(event.data)
320
+ if event.event == "message":
321
+ await _call_handler(handler, "on_message", "onMessage", session_id, data)
322
+ elif event.event == "chunk":
323
+ await _call_handler(handler, "on_chunk", "onChunk", session_id, data)
324
+ elif event.event == "functionCall":
325
+ await self._handle_function_call(session_id, data, handler)
326
+ await _call_handler(handler, "on_done", "onDone")
327
+ except Exception as error:
328
+ await _call_handler(handler, "on_error", "onError", error)
329
+
330
+ async def chat_simple(self, *, session_id: str, user_task: Mapping[str, Any]) -> dict[str, Any]:
331
+ return await self._sdk._with_app_auth_retry(
332
+ lambda token: self._sdk.agentKit.chat_simple(token, session_id, user_task)
333
+ )
334
+
335
+ async def history(self, *, session_id: str) -> list[Any]:
336
+ return await self._sdk._with_app_auth_retry(
337
+ lambda token: self._sdk.agentKit.history(token, session_id)
338
+ )
339
+
340
+ async def stop(self, *, session_id: str, task_id: str | None = None) -> dict[str, Any]:
341
+ return await self._sdk._with_app_auth_retry(
342
+ lambda token: self._sdk.agentKit.stop(token, session_id, task_id)
343
+ )
344
+
345
+ async def clear(self, *, session_id: str) -> dict[str, Any]:
346
+ return await self._sdk._with_app_auth_retry(
347
+ lambda token: self._sdk.agentKit.clear(token, session_id)
348
+ )
349
+
350
+ async def callback(
351
+ self, *, session_id: str, tool_return: Mapping[str, Any] | ToolReturn
352
+ ) -> dict[str, Any]:
353
+ body = tool_return.to_json() if isinstance(tool_return, ToolReturn) else dict(tool_return)
354
+ return await self._sdk._with_app_auth_retry(
355
+ lambda token: self._sdk.agentKit.callback(token, session_id, body)
356
+ )
357
+
358
+ async def stream_callback(
359
+ self, *, session_id: str, event_tool_return: Mapping[str, Any]
360
+ ) -> dict[str, Any]:
361
+ return await self._sdk._with_app_auth_retry(
362
+ lambda token: self._sdk.agentKit.stream_callback(token, session_id, event_tool_return)
363
+ )
364
+
365
+ async def _handle_function_call(
366
+ self, default_session_id: str, payload: Mapping[str, Any], handler: AgentMessageHandler
367
+ ) -> None:
368
+ function_call = payload["functionCall"]
369
+ session_id = payload.get("sessionId") or default_session_id
370
+ is_stream = (
371
+ payload.get("stream") is True
372
+ or payload.get("isStream") is True
373
+ or function_call.get("stream") is True
374
+ or function_call.get("isStream") is True
375
+ )
376
+ if is_stream:
377
+ pending = []
378
+
379
+ def on_tool_return(event_tool_return: dict[str, Any]) -> None:
380
+ pending.append(
381
+ self.stream_callback(session_id=session_id, event_tool_return=event_tool_return)
382
+ )
383
+
384
+ await _call_handler(
385
+ handler,
386
+ "on_stream_function_call",
387
+ "onStreamFunctionCall",
388
+ session_id,
389
+ function_call,
390
+ on_tool_return,
391
+ )
392
+ if pending:
393
+ await asyncio.gather(*pending)
394
+ return
395
+ tool_return = await _call_handler(
396
+ handler, "on_function_call", "onFunctionCall", session_id, function_call
397
+ )
398
+ await self.callback(session_id=session_id, tool_return=tool_return)
399
+
400
+ getAgent = get_agent
401
+ createAgent = create_agent
402
+ updateAgent = update_agent
403
+ deleteAgent = delete_agent
404
+ initSession = init_session
405
+ initSimple = init_simple
406
+ chatSimple = chat_simple
407
+ streamCallback = stream_callback
408
+
409
+
410
+ class ModelKitModule:
411
+ def __init__(self, sdk: AgentOSSDK) -> None:
412
+ self._sdk = sdk
413
+
414
+ @property
415
+ def chat(self):
416
+ return self._sdk.modelKit.chat
417
+
418
+ @property
419
+ def embedding(self):
420
+ return self._sdk.modelKit.embedding
421
+
422
+ @property
423
+ def asr(self):
424
+ return self._sdk.modelKit.asr
425
+
426
+ @property
427
+ def tts(self):
428
+ return self._sdk.modelKit.tts
429
+
430
+ async def list_models(self) -> list[dict[str, Any]]:
431
+ return await self._sdk.modelKit.list_models()
432
+
433
+ async def list_models_by_task(self, task: str) -> list[dict[str, Any]]:
434
+ return await self._sdk.modelKit.list_models_by_task(task)
435
+
436
+ listModels = list_models
437
+ listModelsByTask = list_models_by_task
438
+
439
+
440
+ class ToolKitModule:
441
+ def __init__(self, sdk: AgentOSSDK) -> None:
442
+ self._sdk = sdk
443
+
444
+ async def list_tool(self, all: str | None = None) -> list[dict[str, Any]]:
445
+ return await self._sdk.toolKit.list_tool(all)
446
+
447
+ async def load_tool(self, tool_id: str):
448
+ return await self._sdk.toolKit.load_tool(tool_id)
449
+
450
+ def subscribe_tool_events(self, daemon_api_key: str, snapshot: bool = True):
451
+ return self._sdk.toolKit.subscribe_tool_events(daemon_api_key, snapshot)
452
+
453
+ listTool = list_tool
454
+ loadTool = load_tool
455
+ subscribeToolEvents = subscribe_tool_events
456
+
457
+
458
+ async def _identity(value: Any) -> Any:
459
+ return value
460
+
461
+
462
+ async def _call_handler(
463
+ handler: Any, snake_name: str, camel_name: str, *args: Any, **kwargs: Any
464
+ ) -> Any:
465
+ method = getattr(handler, snake_name, None)
466
+ base_method = getattr(type(handler), snake_name, None)
467
+ if method is None or base_method is getattr(AgentMessageHandler, snake_name, object()):
468
+ method = getattr(handler, camel_name, None)
469
+ return await method(*args, **kwargs)
470
+
471
+
472
+ def _collect_error_text(value: Any) -> str:
473
+ if value is None:
474
+ return ""
475
+ if isinstance(value, ApiError):
476
+ return f"{value} {_collect_error_text(value.data)}"
477
+ if isinstance(value, BaseException):
478
+ return str(value)
479
+ if isinstance(value, str):
480
+ return value
481
+ if isinstance(value, Mapping):
482
+ return " ".join(_collect_error_text(item) for item in value.values())
483
+ if isinstance(value, list):
484
+ return " ".join(_collect_error_text(item) for item in value)
485
+ return str(value)