agentos-sdk-python 0.1.0__py3-none-any.whl → 0.2.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.
agentos_sdk/sdk.py CHANGED
@@ -2,8 +2,9 @@ from __future__ import annotations
2
2
 
3
3
  import asyncio
4
4
  import json
5
+ from copy import deepcopy
5
6
  from dataclasses import dataclass
6
- from typing import Any, Awaitable, Callable, Mapping
7
+ from typing import Any, AsyncGenerator, Awaitable, Callable, Mapping, TypeVar
7
8
 
8
9
  import httpx
9
10
 
@@ -13,9 +14,26 @@ from agentos_sdk.clients.cronkit import CronKitClient
13
14
  from agentos_sdk.clients.modelkit import ModelKitClient
14
15
  from agentos_sdk.clients.systemkit import SystemKitClient
15
16
  from agentos_sdk.clients.toolkit import ToolKitClient
16
- from agentos_sdk.handlers import AgentMessageHandler, AgentOSEventHandler, ToolReturn
17
+ from agentos_sdk.handlers import (
18
+ AgentMessageHandler,
19
+ AgentOSEventHandler,
20
+ EventType,
21
+ FunctionCallLifecycleError,
22
+ ToolReturn,
23
+ )
24
+ from agentos_sdk.protocol import (
25
+ AccessToken,
26
+ AgentMessage,
27
+ HistoryTurnSummary,
28
+ OpenToolDefinition,
29
+ ToolDto,
30
+ ToolStream,
31
+ ToolStreamEvent,
32
+ )
17
33
  from agentos_sdk.transport import ApiClient, ApiError
18
34
 
35
+ _T = TypeVar("_T")
36
+
19
37
 
20
38
  @dataclass(frozen=True)
21
39
  class _AppAuthKey:
@@ -52,6 +70,7 @@ class AgentOSSDK:
52
70
  self.modelKit = ModelKitClient(self.api_client)
53
71
  self.toolKit = ToolKitClient(self.api_client)
54
72
  self._tokens: dict[_AppAuthKey, str] = {}
73
+ self._bundles: dict[_AppAuthKey, dict[str, Any]] = {}
55
74
  self._token_contexts: dict[str, _AppAuthKey] = {}
56
75
  self._refresh_locks: dict[_AppAuthKey, asyncio.Lock] = {}
57
76
  self._active_key: _AppAuthKey | None = None
@@ -73,9 +92,14 @@ class AgentOSSDK:
73
92
  async def dispose(self) -> None:
74
93
  await self.aclose()
75
94
 
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"))
95
+ async def register_bundle(self, bundle: Mapping[str, Any]) -> AccessToken:
96
+ registration_bundle = deepcopy(dict(bundle))
97
+ info = await self.appKit.register_bundle(registration_bundle)
98
+ key = _AppAuthKey(
99
+ bundle_id=registration_bundle["bundleId"],
100
+ app_group_id=registration_bundle.get("appGroupId"),
101
+ )
102
+ self._bundles[key] = registration_bundle
79
103
  self._cache_token(key, info["token"], activate=True)
80
104
  return info
81
105
 
@@ -87,7 +111,7 @@ class AgentOSSDK:
87
111
  raise RuntimeError("Bearer token is not set. Call agentos.register_bundle() first.")
88
112
  return _AppAuthContext(self._active_key, token)
89
113
 
90
- async def _with_app_auth_retry(self, action: Callable[[str], Awaitable[Any]]) -> Any:
114
+ async def _with_app_auth_retry(self, action: Callable[[str], Awaitable[_T]]) -> _T:
91
115
  context = await self._require_auth_context()
92
116
  try:
93
117
  return await action(context.token)
@@ -118,9 +142,13 @@ class AgentOSSDK:
118
142
  return current
119
143
  self._tokens.pop(key, None)
120
144
  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
145
+ fallback_bundle: dict[str, Any] = {
146
+ "bundleId": key.bundle_id,
147
+ "appGroupId": key.app_group_id,
148
+ }
149
+ bundle = deepcopy(self._bundles.get(key, fallback_bundle))
150
+ if bundle.get("appGroupId") is None:
151
+ bundle.pop("appGroupId", None)
124
152
  info = await self.appKit.register_bundle(bundle)
125
153
  self._cache_token(key, info["token"], activate=False)
126
154
  return info["token"]
@@ -148,7 +176,7 @@ class AgentOSModule:
148
176
  async def get_ready(self) -> dict[str, Any]:
149
177
  return await self._sdk.systemKit.get_ready()
150
178
 
151
- async def register_bundle(self, bundle: Mapping[str, Any]) -> dict[str, Any]:
179
+ async def register_bundle(self, bundle: Mapping[str, Any]) -> AccessToken:
152
180
  return await self._sdk.register_bundle(bundle)
153
181
 
154
182
  async def subscribe(self, handler: AgentOSEventHandler) -> None:
@@ -158,15 +186,12 @@ class AgentOSModule:
158
186
  data = json.loads(event.data)
159
187
  if event.event == "welcome":
160
188
  await _call_handler(handler, "on_welcome", "onWelcome", data)
161
- elif event.event == "callApp":
162
- await _call_handler(handler, "on_call_app", "onCallApp", data)
189
+ elif event.event == "appEvent":
190
+ await _call_handler(handler, "on_app_event", "onAppEvent", data)
163
191
  elif event.event == "error":
164
- await _call_handler(
165
- handler,
166
- "on_error",
167
- "onError",
168
- RuntimeError(str(data.get("error", data))),
169
- )
192
+ raise RuntimeError(str(data.get("error", data)))
193
+ else:
194
+ raise RuntimeError(f"Unknown AgentOS event: {event.event}")
170
195
  await _call_handler(handler, "on_done", "onDone")
171
196
  except Exception as error:
172
197
  await _call_handler(handler, "on_error", "onError", error)
@@ -311,30 +336,124 @@ class AgentKitModule:
311
336
  self, session: Mapping[str, Any], user_task: Mapping[str, Any], handler: AgentMessageHandler
312
337
  ) -> None:
313
338
  session_id = session["sessionId"]
339
+ stream = None
314
340
  try:
315
341
  stream = await self._sdk._with_app_auth_retry(
316
342
  lambda token: _identity(self._sdk.agentKit.chat(token, session_id, user_task))
317
343
  )
318
344
  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)
345
+ if event.event == "functionCall":
346
+ await self._handle_function_call(session_id, event.data, handler)
347
+ else:
348
+ data = json.loads(event.data)
349
+ if event.event == "message":
350
+ await _call_handler(
351
+ handler,
352
+ "on_message",
353
+ "onMessage",
354
+ _event_session_id(data, session_id),
355
+ data,
356
+ )
357
+ elif event.event == "chunk":
358
+ await _call_handler(
359
+ handler,
360
+ "on_chunk",
361
+ "onChunk",
362
+ _event_session_id(data, session_id),
363
+ data,
364
+ )
326
365
  await _call_handler(handler, "on_done", "onDone")
327
366
  except Exception as error:
328
- await _call_handler(handler, "on_error", "onError", error)
367
+ try:
368
+ await _call_handler(handler, "on_error", "onError", error)
369
+ except Exception:
370
+ pass
371
+ finally:
372
+ close = getattr(stream, "aclose", None)
373
+ if close is not None:
374
+ await close()
329
375
 
330
376
  async def chat_simple(self, *, session_id: str, user_task: Mapping[str, Any]) -> dict[str, Any]:
331
377
  return await self._sdk._with_app_auth_retry(
332
378
  lambda token: self._sdk.agentKit.chat_simple(token, session_id, user_task)
333
379
  )
334
380
 
335
- async def history(self, *, session_id: str) -> list[Any]:
381
+ async def history(
382
+ self,
383
+ *,
384
+ session_id: str,
385
+ page: int | None = None,
386
+ page_size: int | None = None,
387
+ ) -> list[AgentMessage]:
388
+ return await self._sdk._with_app_auth_retry(
389
+ lambda token: self._sdk.agentKit.history(
390
+ token,
391
+ session_id,
392
+ page=page,
393
+ page_size=page_size,
394
+ )
395
+ )
396
+
397
+ async def history_summary(
398
+ self,
399
+ *,
400
+ session_id: str,
401
+ page: int = 1,
402
+ page_size: int = 30,
403
+ ) -> list[HistoryTurnSummary]:
336
404
  return await self._sdk._with_app_auth_retry(
337
- lambda token: self._sdk.agentKit.history(token, session_id)
405
+ lambda token: self._sdk.agentKit.history_summary(
406
+ token,
407
+ session_id,
408
+ page=page,
409
+ page_size=page_size,
410
+ )
411
+ )
412
+
413
+ async def history_process(
414
+ self,
415
+ *,
416
+ session_id: str,
417
+ original_task_id: str,
418
+ page: int = 1,
419
+ page_size: int = 50,
420
+ ) -> list[AgentMessage]:
421
+ return await self._sdk._with_app_auth_retry(
422
+ lambda token: self._sdk.agentKit.history_process(
423
+ token,
424
+ session_id,
425
+ original_task_id,
426
+ page=page,
427
+ page_size=page_size,
428
+ )
429
+ )
430
+
431
+ async def historySummary(
432
+ self,
433
+ *,
434
+ sessionId: str,
435
+ page: int = 1,
436
+ pageSize: int = 30,
437
+ ) -> list[HistoryTurnSummary]:
438
+ return await self.history_summary(
439
+ session_id=sessionId,
440
+ page=page,
441
+ page_size=pageSize,
442
+ )
443
+
444
+ async def historyProcess(
445
+ self,
446
+ *,
447
+ sessionId: str,
448
+ originalTaskId: str,
449
+ page: int = 1,
450
+ pageSize: int = 50,
451
+ ) -> list[AgentMessage]:
452
+ return await self.history_process(
453
+ session_id=sessionId,
454
+ original_task_id=originalTaskId,
455
+ page=page,
456
+ page_size=pageSize,
338
457
  )
339
458
 
340
459
  async def stop(self, *, session_id: str, task_id: str | None = None) -> dict[str, Any]:
@@ -363,10 +482,26 @@ class AgentKitModule:
363
482
  )
364
483
 
365
484
  async def _handle_function_call(
366
- self, default_session_id: str, payload: Mapping[str, Any], handler: AgentMessageHandler
485
+ self, default_session_id: str, payload_json: str, handler: AgentMessageHandler
367
486
  ) -> None:
368
- function_call = payload["functionCall"]
369
- session_id = payload.get("sessionId") or default_session_id
487
+ session_id = default_session_id
488
+ try:
489
+ raw_payload = json.loads(payload_json)
490
+ if not isinstance(raw_payload, Mapping):
491
+ raise TypeError("functionCall event payload must be an object")
492
+ payload = raw_payload
493
+ session_id = _event_session_id(payload, default_session_id)
494
+ raw_call = payload.get("functionCall")
495
+ if not isinstance(raw_call, Mapping):
496
+ raise TypeError("functionCall event is missing a functionCall object")
497
+ function_call = raw_call
498
+ except Exception as error:
499
+ raise FunctionCallLifecycleError(
500
+ "function_call_parse_failed",
501
+ session_id=session_id,
502
+ cause=error,
503
+ ) from error
504
+
370
505
  is_stream = (
371
506
  payload.get("stream") is True
372
507
  or payload.get("isStream") is True
@@ -374,28 +509,135 @@ class AgentKitModule:
374
509
  or function_call.get("isStream") is True
375
510
  )
376
511
  if is_stream:
377
- pending = []
512
+ pending: list[Awaitable[dict[str, Any]]] = []
513
+ terminal_scheduled = False
378
514
 
379
515
  def on_tool_return(event_tool_return: dict[str, Any]) -> None:
516
+ nonlocal terminal_scheduled
517
+ if event_tool_return.get("event") in {EventType.DONE, EventType.ERROR}:
518
+ terminal_scheduled = True
380
519
  pending.append(
381
520
  self.stream_callback(session_id=session_id, event_tool_return=event_tool_return)
382
521
  )
383
522
 
384
- await _call_handler(
523
+ handler_error: FunctionCallLifecycleError | None = None
524
+ try:
525
+ await _call_handler(
526
+ handler,
527
+ "on_stream_function_call",
528
+ "onStreamFunctionCall",
529
+ session_id,
530
+ function_call,
531
+ on_tool_return,
532
+ )
533
+ except Exception as cause:
534
+ handler_error = self._lifecycle_error(
535
+ "function_call_handler_failed",
536
+ session_id,
537
+ function_call,
538
+ cause,
539
+ "streamCallback",
540
+ )
541
+ if not terminal_scheduled:
542
+ on_tool_return(
543
+ {
544
+ "event": EventType.ERROR,
545
+ "toolReturn": ToolReturn(
546
+ str(function_call.get("id", "")),
547
+ self._handler_error_result(handler_error),
548
+ ).to_json(),
549
+ }
550
+ )
551
+
552
+ results = await asyncio.gather(*pending, return_exceptions=True)
553
+ callback_error = next(
554
+ (result for result in results if isinstance(result, BaseException)),
555
+ None,
556
+ )
557
+ if callback_error is not None:
558
+ raise self._lifecycle_error(
559
+ "function_call_callback_failed",
560
+ session_id,
561
+ function_call,
562
+ callback_error,
563
+ "streamCallback",
564
+ ) from callback_error
565
+ if handler_error is not None:
566
+ if isinstance(handler_error.cause, BaseException):
567
+ raise handler_error from handler_error.cause
568
+ raise handler_error
569
+ return
570
+
571
+ try:
572
+ tool_return = await _call_handler(
385
573
  handler,
386
- "on_stream_function_call",
387
- "onStreamFunctionCall",
574
+ "on_function_call",
575
+ "onFunctionCall",
388
576
  session_id,
389
577
  function_call,
390
- on_tool_return,
391
578
  )
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
579
+ except Exception as cause:
580
+ handler_error = self._lifecycle_error(
581
+ "function_call_handler_failed",
582
+ session_id,
583
+ function_call,
584
+ cause,
585
+ "callback",
586
+ )
587
+ error_return = ToolReturn(
588
+ str(function_call.get("id", "")),
589
+ self._handler_error_result(handler_error),
590
+ )
591
+ try:
592
+ await self.callback(session_id=session_id, tool_return=error_return)
593
+ except Exception as callback_error:
594
+ raise self._lifecycle_error(
595
+ "function_call_callback_failed",
596
+ session_id,
597
+ function_call,
598
+ callback_error,
599
+ "callback",
600
+ ) from callback_error
601
+ raise handler_error from cause
602
+
603
+ try:
604
+ await self.callback(session_id=session_id, tool_return=tool_return)
605
+ except Exception as callback_error:
606
+ raise self._lifecycle_error(
607
+ "function_call_callback_failed",
608
+ session_id,
609
+ function_call,
610
+ callback_error,
611
+ "callback",
612
+ ) from callback_error
613
+
614
+ def _lifecycle_error(
615
+ self,
616
+ stage,
617
+ session_id: str,
618
+ function_call: Mapping[str, Any],
619
+ cause: object,
620
+ callback_mode=None,
621
+ ) -> FunctionCallLifecycleError:
622
+ call_id = function_call.get("id")
623
+ function_name = function_call.get("name")
624
+ return FunctionCallLifecycleError(
625
+ stage,
626
+ session_id=session_id,
627
+ call_id=call_id if isinstance(call_id, str) else None,
628
+ function_name=function_name if isinstance(function_name, str) else None,
629
+ callback_mode=callback_mode,
630
+ cause=cause,
397
631
  )
398
- await self.callback(session_id=session_id, tool_return=tool_return)
632
+
633
+ def _handler_error_result(
634
+ self, error: FunctionCallLifecycleError
635
+ ) -> dict[str, Any]:
636
+ return {
637
+ "error": "FunctionCallHandlerError",
638
+ "stage": error.stage,
639
+ "message": str(error.cause),
640
+ }
399
641
 
400
642
  getAgent = get_agent
401
643
  createAgent = create_agent
@@ -441,17 +683,60 @@ class ToolKitModule:
441
683
  def __init__(self, sdk: AgentOSSDK) -> None:
442
684
  self._sdk = sdk
443
685
 
444
- async def list_tool(self, all: str | None = None) -> list[dict[str, Any]]:
445
- return await self._sdk.toolKit.list_tool(all)
686
+ async def list_tool(self, all: str | None = None) -> list[ToolDto]:
687
+ return await self._sdk._with_app_auth_retry(
688
+ lambda token: self._sdk.toolKit.list_tool(all, bearer_token=token)
689
+ )
690
+
691
+ async def load_tool(self, tool_id: str) -> OpenToolDefinition | None:
692
+ return await self._sdk._with_app_auth_retry(
693
+ lambda token: self._sdk.toolKit.load_tool(tool_id, bearer_token=token)
694
+ )
695
+
696
+ async def call(
697
+ self,
698
+ tool_id: str,
699
+ function_call: Mapping[str, Any],
700
+ ) -> dict[str, Any]:
701
+ return await self._sdk._with_app_auth_retry(
702
+ lambda token: self._sdk.toolKit.call(
703
+ tool_id,
704
+ function_call,
705
+ bearer_token=token,
706
+ )
707
+ )
446
708
 
447
- async def load_tool(self, tool_id: str):
448
- return await self._sdk.toolKit.load_tool(tool_id)
709
+ def stream_call(
710
+ self,
711
+ tool_id: str,
712
+ function_call: Mapping[str, Any],
713
+ ) -> ToolStream:
714
+ return self._stream_call(tool_id, function_call)
715
+
716
+ async def _stream_call(
717
+ self,
718
+ tool_id: str,
719
+ function_call: Mapping[str, Any],
720
+ ) -> AsyncGenerator[ToolStreamEvent, None]:
721
+ stream = await self._sdk._with_app_auth_retry(
722
+ lambda token: self._sdk.toolKit._open_stream_call(
723
+ tool_id,
724
+ function_call,
725
+ bearer_token=token,
726
+ )
727
+ )
728
+ try:
729
+ async for event in stream:
730
+ yield event
731
+ finally:
732
+ await stream.aclose()
449
733
 
450
734
  def subscribe_tool_events(self, daemon_api_key: str, snapshot: bool = True):
451
735
  return self._sdk.toolKit.subscribe_tool_events(daemon_api_key, snapshot)
452
736
 
453
737
  listTool = list_tool
454
738
  loadTool = load_tool
739
+ streamCall = stream_call
455
740
  subscribeToolEvents = subscribe_tool_events
456
741
 
457
742
 
@@ -459,13 +744,24 @@ async def _identity(value: Any) -> Any:
459
744
  return value
460
745
 
461
746
 
747
+ def _event_session_id(payload: Mapping[str, Any], root_session_id: str) -> str:
748
+ candidate = payload.get("sessionId")
749
+ return candidate if isinstance(candidate, str) and candidate else root_session_id
750
+
751
+
462
752
  async def _call_handler(
463
753
  handler: Any, snake_name: str, camel_name: str, *args: Any, **kwargs: Any
464
754
  ) -> Any:
465
755
  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()):
756
+ implementation = getattr(type(handler), snake_name, None)
757
+ defaults = {
758
+ getattr(AgentOSEventHandler, snake_name, None),
759
+ getattr(AgentMessageHandler, snake_name, None),
760
+ }
761
+ if method is None or implementation in defaults:
468
762
  method = getattr(handler, camel_name, None)
763
+ if method is None:
764
+ raise AttributeError(f"Handler does not implement {snake_name} or {camel_name}")
469
765
  return await method(*args, **kwargs)
470
766
 
471
767
 
agentos_sdk/transport.py CHANGED
@@ -1,7 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  from dataclasses import dataclass
4
- from typing import Any, AsyncIterator, Iterable, Mapping
4
+ from typing import Any, AsyncGenerator, Iterable, Mapping
5
5
  from urllib.parse import urljoin
6
6
 
7
7
  import httpx
@@ -11,6 +11,7 @@ import httpx
11
11
  class SseEvent:
12
12
  event: str
13
13
  data: str
14
+ id: str | None = None
14
15
 
15
16
 
16
17
  class ApiError(Exception):
@@ -136,35 +137,54 @@ class ApiClient:
136
137
  return body
137
138
 
138
139
 
139
- async def iter_sse(response: httpx.Response) -> AsyncIterator[SseEvent]:
140
+ async def iter_sse(response: httpx.Response) -> AsyncGenerator[SseEvent, None]:
140
141
  buffer: list[str] = []
141
- async for line in response.aiter_lines():
142
- buffer.append(line)
143
- if line == "":
142
+ try:
143
+ async for line in response.aiter_lines():
144
+ buffer.append(line)
145
+ if line == "":
146
+ for event in parse_sse_lines(buffer):
147
+ yield event
148
+ buffer.clear()
149
+ if buffer:
144
150
  for event in parse_sse_lines(buffer):
145
151
  yield event
146
- buffer.clear()
147
- if buffer:
148
- for event in parse_sse_lines(buffer):
149
- yield event
150
- await response.aclose()
152
+ finally:
153
+ await response.aclose()
154
+
155
+
156
+ def _field_value(line: str, prefix: str) -> str:
157
+ value = line[len(prefix) :]
158
+ return value[1:] if value.startswith(" ") else value
151
159
 
152
160
 
153
161
  def parse_sse_lines(lines: Iterable[str]) -> Iterable[SseEvent]:
154
162
  current_event = ""
163
+ current_id: str | None = None
155
164
  current_data: list[str] = []
156
165
  for raw_line in lines:
157
166
  line = raw_line[:-1] if raw_line.endswith("\r") else raw_line
158
167
  if line.startswith("event:"):
159
- current_event = line[6:].strip()
168
+ current_event = _field_value(line, "event:")
160
169
  elif line.startswith("data:"):
161
- current_data.append(line[5:].strip())
170
+ current_data.append(_field_value(line, "data:"))
171
+ elif line.startswith("id:"):
172
+ current_id = _field_value(line, "id:")
162
173
  elif line == "" and current_data:
163
- yield SseEvent(event=current_event or "message", data="\n".join(current_data))
174
+ yield SseEvent(
175
+ event=current_event or "message",
176
+ data="\n".join(current_data),
177
+ id=current_id,
178
+ )
164
179
  current_event = ""
180
+ current_id = None
165
181
  current_data = []
166
182
  if current_data:
167
- yield SseEvent(event=current_event or "message", data="\n".join(current_data))
183
+ yield SseEvent(
184
+ event=current_event or "message",
185
+ data="\n".join(current_data),
186
+ id=current_id,
187
+ )
168
188
 
169
189
 
170
190
  async def _read_body(response: httpx.Response) -> Any: