agentic-platform-sdk 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.
Files changed (41) hide show
  1. agentic_platform_sdk/__init__.py +9 -0
  2. agentic_platform_sdk/_a2a.py +133 -0
  3. agentic_platform_sdk/_client.py +152 -0
  4. agentic_platform_sdk/_contract.py +72 -0
  5. agentic_platform_sdk/_generated/__init__.py +0 -0
  6. agentic_platform_sdk/_generated/_base.py +20 -0
  7. agentic_platform_sdk/_generated/models.py +698 -0
  8. agentic_platform_sdk/_paging.py +117 -0
  9. agentic_platform_sdk/_spec/call_areas.json +13 -0
  10. agentic_platform_sdk/_spec/chat-events.schema.json +371 -0
  11. agentic_platform_sdk/_spec/errors.json +2365 -0
  12. agentic_platform_sdk/_spec/operations.json +230 -0
  13. agentic_platform_sdk/_transport.py +630 -0
  14. agentic_platform_sdk/_util.py +133 -0
  15. agentic_platform_sdk/agents.py +793 -0
  16. agentic_platform_sdk/approvals.py +66 -0
  17. agentic_platform_sdk/auth.py +336 -0
  18. agentic_platform_sdk/chat.py +599 -0
  19. agentic_platform_sdk/datasets.py +69 -0
  20. agentic_platform_sdk/errors.py +204 -0
  21. agentic_platform_sdk/kb.py +288 -0
  22. agentic_platform_sdk/llm.py +40 -0
  23. agentic_platform_sdk/me.py +28 -0
  24. agentic_platform_sdk/models.py +91 -0
  25. agentic_platform_sdk/ontology.py +209 -0
  26. agentic_platform_sdk/py.typed +0 -0
  27. agentic_platform_sdk/testing/__init__.py +19 -0
  28. agentic_platform_sdk/testing/conformance.py +803 -0
  29. agentic_platform_sdk/testing/fake.py +902 -0
  30. agentic_platform_sdk/testing/standin.py +165 -0
  31. agentic_platform_sdk/toolchains.py +137 -0
  32. agentic_platform_sdk/tools/__init__.py +70 -0
  33. agentic_platform_sdk/tools/_jcs.py +218 -0
  34. agentic_platform_sdk/tools/asgi.py +228 -0
  35. agentic_platform_sdk/tools/mcp.py +751 -0
  36. agentic_platform_sdk/tools/verify.py +379 -0
  37. agentic_platform_sdk/vision.py +300 -0
  38. agentic_platform_sdk-0.1.0.dist-info/METADATA +226 -0
  39. agentic_platform_sdk-0.1.0.dist-info/RECORD +41 -0
  40. agentic_platform_sdk-0.1.0.dist-info/WHEEL +4 -0
  41. agentic_platform_sdk-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,793 @@
1
+ """The ``agents`` area: a small A2A 1.0 client (JSON-RPC over HTTP, with SSE for streaming).
2
+
3
+ Build or buy: this module does **not** use the official ``a2a-sdk`` package. The
4
+ package supports the 1.0 JSON-RPC wire and SSE, but it fails the build-or-buy test where it
5
+ matters here:
6
+
7
+ * It owns its HTTP client and its error model. Every platform call in this SDK goes through one
8
+ transport that adds the credentials (a bearer token, or a ``DPoP`` proof built per request with
9
+ the server nonce), applies one retry policy, maps every failure to ``PlatformError`` and logs
10
+ without headers or bodies. Pushing an ``a2a-sdk`` client through that would mean wrapping its
11
+ httpx client, re-deriving the DPoP proof inside its auth hook, and translating its exceptions
12
+ back: the shared rules would be bypassed or duplicated, not reused.
13
+ * Its models are protobuf messages, so it needs ``protobuf``, ``google-api-core`` and
14
+ ``googleapis-common-protos`` (plus ``json-rpc`` and ``culsans``) at install time. This SDK
15
+ depends on ``httpx``, ``pydantic`` and ``pyjwt`` only, and an app takes the SDK to call a few
16
+ routes, not to carry gRPC-era packages.
17
+ * What the SDK needs from A2A is five methods of the 1.0 wire (``SendMessage``,
18
+ ``SendStreamingMessage``, ``GetTask``, ``ListTasks``, ``CancelTask``) and four SSE event kinds.
19
+ That is about 150 lines, with the platform's own rules (``messageId`` dedupe, ``-32001`` as
20
+ ``NotFound``, ``error.data.code``) built in.
21
+
22
+ The public API is the same either way. The chat-events extension (``TextDelta``, ``ToolCall``,
23
+ ...) is opt-in: ``stream(..., chat_events=True)`` and ``subscribe`` yield the typed events of
24
+ ``agentic_platform_sdk.chat`` and resume a dropped stream; without it a message names no extension
25
+ and an event the SDK does not know comes back as ``Unknown``.
26
+
27
+ Wire facts (platform ``a2a_rpc.py``): every request carries ``A2A-Version: 1.0``, because a
28
+ missing header or ``0.3`` selects the 0.3 method names. A JSON-RPC error comes back as HTTP 200
29
+ with an ``error`` object, so it is not retried; only an HTTP-level failure is, under the transport's
30
+ policy (``SendMessage`` is repeated with the same ``messageId``, which the platform deduplicates).
31
+ A plain stream is never retried once it has opened; a chat-events stream reconnects with
32
+ ``SubscribeToTask`` from its last ``seq`` (see ``chat``). Leaving a ``stream()`` block closes the
33
+ response; it never sends ``CancelTask``, so the task keeps running (call ``cancel`` to stop it).
34
+
35
+ A blocking ``send`` (no ``return_immediately``) waits for the task, and the platform holds it up to
36
+ 240 s, so it has its own default read timeout of 250 s (an operation default, not an area change).
37
+ Precedence: ``send(timeout=)``, then ``timeouts["callA2AJsonRpc"]``, then the 250 s, then
38
+ ``timeouts["agents"]``, then the area's 30 s. A ``return_immediately`` send, ``get_task``, ``tasks``
39
+ and ``cancel`` keep the area default; ``stream`` has no read timeout.
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import asyncio
45
+ import contextlib
46
+ import json
47
+ import time
48
+ import uuid
49
+ from collections.abc import AsyncIterator, Awaitable, Callable, Generator, Iterator
50
+ from typing import Any
51
+
52
+ import httpx
53
+
54
+ from . import chat
55
+ from ._a2a import (
56
+ TERMINAL_STATES,
57
+ ArtifactUpdate,
58
+ Event,
59
+ StatusUpdate,
60
+ Task,
61
+ TaskSnapshot,
62
+ Unknown,
63
+ _event_of,
64
+ _task,
65
+ )
66
+ from ._generated import models as gen
67
+ from ._paging import Page, aiter_cursor, iter_cursor
68
+ from ._transport import AsyncTransport, Call, SyncTransport, _mid_stream_error
69
+ from .errors import NotFound, PlatformError, Unavailable
70
+
71
+ AgentCard = gen.OpenA2AAgentCard
72
+
73
+ _AREA = "agents"
74
+ _VERSION = {"A2A-Version": "1.0"}
75
+ _NOT_FOUND = -32001
76
+ _INTERNAL = -32603
77
+ _DEFAULT_PAGE = 50
78
+ _UNAVAILABLE = "a2a.unavailable"
79
+
80
+
81
+ def _sleep(seconds: float) -> None:
82
+ time.sleep(seconds)
83
+
84
+
85
+ async def _asleep(seconds: float) -> None:
86
+ await asyncio.sleep(seconds)
87
+
88
+
89
+ def _rpc_error(error: Any, http_status: int) -> PlatformError:
90
+ """The ``PlatformError`` for a JSON-RPC ``error`` object. The code is ``error.data.code`` when
91
+ it is a string, else ``a2a.jsonrpc_<abs(error.code)>``; -32001 (task not found) is NotFound."""
92
+ error = error if isinstance(error, dict) else {}
93
+ number = error.get("code")
94
+ if not isinstance(number, int) or isinstance(number, bool):
95
+ number = _INTERNAL
96
+ data = error.get("data")
97
+ data = dict(data) if isinstance(data, dict) else {}
98
+ named = data.get("code")
99
+ code = named if isinstance(named, str) and named else f"a2a.jsonrpc_{abs(number)}"
100
+ data["rpc_code"] = number
101
+ message = error.get("message")
102
+ cls = NotFound if number == _NOT_FOUND else PlatformError
103
+ return cls(
104
+ code,
105
+ http_status=http_status,
106
+ detail=message if isinstance(message, str) else None,
107
+ data=data,
108
+ )
109
+
110
+
111
+ def _unavailable(detail: str) -> Unavailable:
112
+ return Unavailable(_UNAVAILABLE, detail=detail)
113
+
114
+
115
+ def _document(body: bytes) -> dict[str, Any]:
116
+ try:
117
+ document = json.loads(body)
118
+ except ValueError:
119
+ raise _unavailable("the answer is not JSON") from None
120
+ if not isinstance(document, dict):
121
+ raise _unavailable("the answer is not a JSON-RPC response")
122
+ return document
123
+
124
+
125
+ def _result(response: httpx.Response) -> dict[str, Any]:
126
+ """The ``result`` of a JSON-RPC answer (HTTP 2xx), or raise the error it carries."""
127
+ document = _document(response.content)
128
+ if "error" in document:
129
+ raise _rpc_error(document["error"], response.status_code)
130
+ result = document.get("result")
131
+ if not isinstance(result, dict):
132
+ raise _unavailable("the answer has no result")
133
+ return result
134
+
135
+
136
+ def _task_of(result: dict[str, Any]) -> Task:
137
+ """A ``SendMessage`` answers ``{"task": ...}``; ``GetTask`` and ``CancelTask`` the task."""
138
+ inner = result.get("task")
139
+ if isinstance(inner, dict):
140
+ return _task(inner)
141
+ if "id" in result:
142
+ return _task(result)
143
+ raise _unavailable("the answer holds no task")
144
+
145
+
146
+ def _tasks_page(result: dict[str, Any]) -> tuple[list[Task], str | None]:
147
+ tasks = [_task(t) for t in result.get("tasks") or [] if isinstance(t, dict)]
148
+ following = result.get("nextPageToken")
149
+ return tasks, (following if isinstance(following, str) and following else None)
150
+
151
+
152
+ # --- server-sent events ----------------------------------------------------------------------
153
+
154
+
155
+ class _Sse:
156
+ """Collects ``data:`` lines until a blank line ends the event. Other fields and comments are
157
+ ignored, as the A2A stream uses ``data:`` only."""
158
+
159
+ def __init__(self) -> None:
160
+ self._data: list[str] = []
161
+
162
+ def feed(self, line: str) -> str | None:
163
+ """The data of an event when `line` ends one, else None."""
164
+ if line:
165
+ if line.startswith("data:"):
166
+ value = line[5:]
167
+ self._data.append(value[1:] if value.startswith(" ") else value)
168
+ return None
169
+ return self.flush()
170
+
171
+ def flush(self) -> str | None:
172
+ data, self._data = self._data, []
173
+ return "\n".join(data) if data else None
174
+
175
+
176
+ def _frame_result(data: str) -> dict[str, Any] | None:
177
+ """The ``result`` of one SSE ``data`` payload (a JSON-RPC response); None when the payload is
178
+ not one. An error object raises."""
179
+ try:
180
+ document = json.loads(data)
181
+ except ValueError:
182
+ return None
183
+ if not isinstance(document, dict):
184
+ return None
185
+ if "error" in document:
186
+ raise _rpc_error(document["error"], 200)
187
+ result = document.get("result")
188
+ return result if isinstance(result, dict) else None
189
+
190
+
191
+ def _decode(data: str) -> Event:
192
+ """One SSE ``data`` payload as an event; an error object raises."""
193
+ result = _frame_result(data)
194
+ return Unknown("malformed", {"data": data}) if result is None else _event_of(result)
195
+
196
+
197
+ def _is_json(response: httpx.Response) -> bool:
198
+ return response.headers.get("content-type", "").lower().startswith("application/json")
199
+
200
+
201
+ def _sse_data(response: httpx.Response, call: Call) -> Iterator[str]:
202
+ sse = _Sse()
203
+ lines = response.iter_lines()
204
+ while True:
205
+ try:
206
+ line = next(lines)
207
+ except StopIteration:
208
+ break
209
+ except httpx.HTTPError as exc:
210
+ raise _mid_stream_error(call, exc) from exc
211
+ data = sse.feed(line)
212
+ if data is not None:
213
+ yield data
214
+ data = sse.flush()
215
+ if data is not None:
216
+ yield data
217
+
218
+
219
+ async def _asse_data(response: httpx.Response, call: Call) -> AsyncIterator[str]:
220
+ sse = _Sse()
221
+ lines = response.aiter_lines()
222
+ while True:
223
+ try:
224
+ line = await lines.__anext__()
225
+ except StopAsyncIteration:
226
+ break
227
+ except httpx.HTTPError as exc:
228
+ raise _mid_stream_error(call, exc) from exc
229
+ data = sse.feed(line)
230
+ if data is not None:
231
+ yield data
232
+ data = sse.flush()
233
+ if data is not None:
234
+ yield data
235
+
236
+
237
+ def _events(response: httpx.Response, call: Call) -> Iterator[Event]:
238
+ for data in _sse_data(response, call):
239
+ yield _decode(data)
240
+
241
+
242
+ async def _aevents(response: httpx.Response, call: Call) -> AsyncIterator[Event]:
243
+ async for data in _asse_data(response, call):
244
+ yield _decode(data)
245
+
246
+
247
+ # --- requests --------------------------------------------------------------------------------
248
+
249
+
250
+ def _message(text: str, context_id: str | None, message_id: str | None) -> dict[str, Any]:
251
+ message: dict[str, Any] = {
252
+ "messageId": message_id or str(uuid.uuid4()),
253
+ "role": "ROLE_USER",
254
+ "parts": [{"text": text}],
255
+ }
256
+ if context_id:
257
+ message["contextId"] = context_id
258
+ return message
259
+
260
+
261
+ def _send_params(
262
+ text: str, context_id: str | None, message_id: str | None, return_immediately: bool
263
+ ) -> dict[str, Any]:
264
+ params: dict[str, Any] = {"message": _message(text, context_id, message_id)}
265
+ if return_immediately:
266
+ params["configuration"] = {"returnImmediately": True}
267
+ return params
268
+
269
+
270
+ def _rpc(
271
+ agent_id: str,
272
+ method: str,
273
+ params: dict[str, Any],
274
+ *,
275
+ stream: bool = False,
276
+ timeout: float | None = None,
277
+ blocking: bool = False,
278
+ chat_events: bool = False,
279
+ ) -> Call:
280
+ """One JSON-RPC call. Built once, so a retry sends the same request id and ``messageId``.
281
+ `chat_events` names the chat-events extension in ``A2A-Extensions``."""
282
+ return Call(
283
+ operation="callA2AJsonRpc",
284
+ area=_AREA,
285
+ path_params={"agent_id": agent_id},
286
+ json={"jsonrpc": "2.0", "id": str(uuid.uuid4()), "method": method, "params": params},
287
+ jsonrpc_method=method,
288
+ headers={**_VERSION, chat.HEADER: chat.URI} if chat_events else _VERSION,
289
+ stream=stream,
290
+ timeout=timeout,
291
+ blocking=blocking,
292
+ )
293
+
294
+
295
+ def _chat_params(
296
+ text: str, context_id: str | None, message_id: str | None, app_context: Any
297
+ ) -> dict[str, Any]:
298
+ """The params of a chat-events ``SendStreamingMessage``: the message names the extension and
299
+ carries the app context. `app_context` is checked (``ValueError``) before anything is sent."""
300
+ params = _send_params(text, context_id, message_id, False)
301
+ message = params["message"]
302
+ message["extensions"] = [chat.URI]
303
+ if app_context is not None:
304
+ message["metadata"] = {chat.APP_CONTEXT_KEY: chat.check_app_context(app_context)}
305
+ return params
306
+
307
+
308
+ def _subscribe_call(agent_id: str, task_id: str, after_seq: int | None) -> Call:
309
+ """``SubscribeToTask``; with `after_seq` it names the chat-events extension and the position
310
+ after which the frames are wanted."""
311
+ params: dict[str, Any] = {"id": task_id}
312
+ if after_seq is not None:
313
+ params["metadata"] = {chat.AFTER_SEQ_KEY: after_seq}
314
+ return _rpc(agent_id, "SubscribeToTask", params, stream=True, chat_events=after_seq is not None)
315
+
316
+
317
+ def _check_after_seq(after_seq: Any) -> int:
318
+ if isinstance(after_seq, bool) or not isinstance(after_seq, int) or after_seq < 0:
319
+ raise ValueError("after_seq must be an integer of at least 0")
320
+ return after_seq
321
+
322
+
323
+ def _no_app_context(chat_events: bool, app_context: Any) -> None:
324
+ if app_context is not None and not chat_events:
325
+ raise ValueError("app_context is part of the chat-events extension: pass chat_events=True")
326
+
327
+
328
+ def _connection(
329
+ response: httpx.Response, call: Call, run: chat.Run
330
+ ) -> Generator[Any, None, Exception | None]:
331
+ """One connection of a chat stream: its events, then None when it ended in order, or the
332
+ error that cut it (a dropped connection, or the unreadable event log) for the run to judge."""
333
+ try:
334
+ if _is_json(response): # the platform answered in the JSON-RPC body
335
+ response.read()
336
+ yield from run.take(_result(response))
337
+ return None
338
+ for data in _sse_data(response, call):
339
+ frame = _frame_result(data)
340
+ if frame is None:
341
+ yield Unknown("malformed", {"data": data})
342
+ continue
343
+ yield from run.take(frame)
344
+ if run.terminal is not None:
345
+ return None
346
+ except PlatformError as exc:
347
+ if isinstance(exc, Unavailable) or exc.code == chat.EVENTS_UNAVAILABLE:
348
+ return exc
349
+ raise
350
+ return None
351
+
352
+
353
+ def _chat_events(
354
+ transport: SyncTransport,
355
+ agent_id: str,
356
+ run: chat.Run,
357
+ response: httpx.Response,
358
+ call: Call,
359
+ get_task: Callable[[str, str], Task],
360
+ ) -> Iterator[chat.ChatEvent]:
361
+ """The events of a chat stream, across its reconnects (each seq once, in order)."""
362
+ error = yield from _connection(response, call, run)
363
+ while True:
364
+ action, delay = run.after_connection(error)
365
+ if action == chat.END:
366
+ return
367
+ if action == chat.RAISE:
368
+ assert error is not None
369
+ raise error
370
+ if action == chat.SNAPSHOT: # cannot continue: the task is the truth
371
+ yield chat.Done(get_task(agent_id, run.task_id))
372
+ return
373
+ if delay:
374
+ _sleep(delay)
375
+ call = _subscribe_call(agent_id, run.task_id, run.last_seq)
376
+ try:
377
+ with transport.stream(call) as response:
378
+ error = yield from _connection(response, call, run)
379
+ except Unavailable as exc: # the reconnect did not open
380
+ error = exc
381
+
382
+
383
+ class _Outcome:
384
+ """The error that cut an async connection (an async generator cannot return a value)."""
385
+
386
+ error: Exception | None = None
387
+
388
+
389
+ async def _aconnection(
390
+ response: httpx.Response, call: Call, run: chat.Run, outcome: _Outcome
391
+ ) -> AsyncIterator[chat.ChatEvent]:
392
+ """The async twin of ``_connection``: the error that cut the connection is left in `outcome`."""
393
+ outcome.error = None
394
+ try:
395
+ if _is_json(response):
396
+ await response.aread()
397
+ for event in run.take(_result(response)):
398
+ yield event
399
+ return
400
+ async for data in _asse_data(response, call):
401
+ frame = _frame_result(data)
402
+ if frame is None:
403
+ yield Unknown("malformed", {"data": data})
404
+ continue
405
+ for event in run.take(frame):
406
+ yield event
407
+ if run.terminal is not None:
408
+ return
409
+ except PlatformError as exc:
410
+ if isinstance(exc, Unavailable) or exc.code == chat.EVENTS_UNAVAILABLE:
411
+ outcome.error = exc
412
+ return
413
+ raise
414
+
415
+
416
+ async def _achat_events(
417
+ transport: AsyncTransport,
418
+ agent_id: str,
419
+ run: chat.Run,
420
+ response: httpx.Response,
421
+ call: Call,
422
+ get_task: Callable[[str, str], Awaitable[Task]],
423
+ ) -> AsyncIterator[chat.ChatEvent]:
424
+ """The async twin of ``_chat_events``."""
425
+ outcome = _Outcome()
426
+ async for event in _aconnection(response, call, run, outcome):
427
+ yield event
428
+ while True:
429
+ action, delay = run.after_connection(outcome.error)
430
+ if action == chat.END:
431
+ return
432
+ if action == chat.RAISE:
433
+ assert outcome.error is not None
434
+ raise outcome.error
435
+ if action == chat.SNAPSHOT:
436
+ yield chat.Done(await get_task(agent_id, run.task_id))
437
+ return
438
+ if delay:
439
+ await _asleep(delay)
440
+ call = _subscribe_call(agent_id, run.task_id, run.last_seq)
441
+ try:
442
+ async with transport.stream(call) as response:
443
+ async for event in _aconnection(response, call, run, outcome):
444
+ yield event
445
+ except Unavailable as exc: # the reconnect did not open
446
+ outcome.error = exc
447
+
448
+
449
+ def _list_params(
450
+ context_id: str | None, status: str | None, page_size: int, token: str | None
451
+ ) -> dict[str, Any]:
452
+ params: dict[str, Any] = {"pageSize": page_size}
453
+ if context_id:
454
+ params["contextId"] = context_id
455
+ if status:
456
+ params["status"] = status
457
+ if token:
458
+ params["pageToken"] = token
459
+ return params
460
+
461
+
462
+ _LIST_AGENTS = Call(operation="listA2AAgents", area=_AREA)
463
+
464
+
465
+ def _card_call(agent_id: str) -> Call:
466
+ return Call(
467
+ operation="getA2AAgentCard",
468
+ area=_AREA,
469
+ path_params={"agent_id": agent_id},
470
+ headers=_VERSION,
471
+ )
472
+
473
+
474
+ def _card_of(response: httpx.Response) -> dict[str, Any]:
475
+ return _document(response.content)
476
+
477
+
478
+ def _agent_list(response: httpx.Response) -> list[AgentCard]:
479
+ return gen.OpenA2AAgentList.model_validate_json(response.content).items
480
+
481
+
482
+ def _id_params(task_id: str) -> dict[str, Any]:
483
+ return {"id": task_id}
484
+
485
+
486
+ class Agents:
487
+ """A2A agents: the cards, ``send``, ``stream``, ``get_task``, ``tasks`` and ``cancel``."""
488
+
489
+ def __init__(self, transport: SyncTransport) -> None:
490
+ self._t = transport
491
+
492
+ def list(self) -> list[AgentCard]:
493
+ """The published, A2A-enabled agents of the workspace."""
494
+ return _agent_list(self._t.request(_LIST_AGENTS))
495
+
496
+ def card(self, agent_id: str) -> dict[str, Any]:
497
+ """The agent's A2A 1.0 card, as the platform sends it."""
498
+ return _card_of(self._t.request(_card_call(agent_id)))
499
+
500
+ def send(
501
+ self,
502
+ agent_id: str,
503
+ text: str,
504
+ *,
505
+ context_id: str | None = None,
506
+ message_id: str | None = None,
507
+ return_immediately: bool = False,
508
+ timeout: float | None = None,
509
+ ) -> Task:
510
+ """``SendMessage``: file a task and wait for it (unless `return_immediately`).
511
+
512
+ The ``messageId`` is `message_id` or a fresh uuid4, and a retry sends the same one."""
513
+ params = _send_params(text, context_id, message_id, return_immediately)
514
+ call = _rpc(
515
+ agent_id, "SendMessage", params, timeout=timeout, blocking=not return_immediately
516
+ )
517
+ return _task_of(_result(self._t.request(call)))
518
+
519
+ @contextlib.contextmanager
520
+ def stream(
521
+ self,
522
+ agent_id: str,
523
+ text: str,
524
+ *,
525
+ context_id: str | None = None,
526
+ message_id: str | None = None,
527
+ chat_events: bool = False,
528
+ app_context: dict[str, Any] | None = None,
529
+ resume: bool = True,
530
+ ) -> Iterator[Iterator[Event | chat.ChatEvent]]:
531
+ """``SendStreamingMessage``: a block that yields the events as they arrive. Leaving the
532
+ block closes the stream and does not cancel the task.
533
+
534
+ ``chat_events=True`` turns on the chat-events extension: the events are the typed ones of
535
+ ``agentic_platform_sdk.chat`` (``TextDelta``, ``ToolCall``, ``Approval``, ...), ending with
536
+ ``Done``. A stream that drops is resumed from the last ``seq`` it saw (up to
537
+ ``chat.MAX_RESUME_TRIES`` reconnects with no new event between them, then it ends with a
538
+ ``GetTask`` snapshot as ``Done``); ``resume=False`` leaves the drop to the caller.
539
+ `app_context` (a JSON object of at most 4 KB) reaches the app's tools; a larger one is a
540
+ ``ValueError``, before anything is sent."""
541
+ _no_app_context(chat_events, app_context)
542
+ if not chat_events:
543
+ params = _send_params(text, context_id, message_id, False)
544
+ call = _rpc(agent_id, "SendStreamingMessage", params, stream=True)
545
+ with self._t.stream(call) as response:
546
+ if _is_json(response): # the platform refused the request in the JSON-RPC body
547
+ response.read()
548
+ yield iter([_decode_body(response)])
549
+ else:
550
+ yield _events(response, call)
551
+ return
552
+ params = _chat_params(text, context_id, message_id, app_context)
553
+ call = _rpc(agent_id, "SendStreamingMessage", params, stream=True, chat_events=True)
554
+ with self._t.stream(call) as response:
555
+ events = _chat_events(
556
+ self._t, agent_id, chat.Run(resume=resume), response, call, self.get_task
557
+ )
558
+ try:
559
+ yield events
560
+ finally:
561
+ events.close()
562
+
563
+ @contextlib.contextmanager
564
+ def subscribe(
565
+ self,
566
+ agent_id: str,
567
+ task_id: str,
568
+ *,
569
+ after_seq: int = 0,
570
+ chat_events: bool = True,
571
+ resume: bool = True,
572
+ ) -> Iterator[Iterator[Event | chat.ChatEvent]]:
573
+ """``SubscribeToTask``: watch a task that is running (or finished within the platform's
574
+ 15 minute log window). With ``chat_events`` (the default) the stream starts after
575
+ `after_seq`, the last ``seq`` the caller holds, and each later event arrives once; the
576
+ events, reconnects and the end are those of ``stream(..., chat_events=True)``. Without it
577
+ the plain A2A events come back, as ``stream`` gives them."""
578
+ position = _check_after_seq(after_seq)
579
+ if not chat_events:
580
+ call = _subscribe_call(agent_id, task_id, None)
581
+ with self._t.stream(call) as response:
582
+ if _is_json(response):
583
+ response.read()
584
+ yield iter([_decode_body(response)])
585
+ else:
586
+ yield _events(response, call)
587
+ return
588
+ call = _subscribe_call(agent_id, task_id, position)
589
+ with self._t.stream(call) as response:
590
+ run = chat.Run(after_seq=position, resume=resume, task_id=task_id)
591
+ events = _chat_events(self._t, agent_id, run, response, call, self.get_task)
592
+ try:
593
+ yield events
594
+ finally:
595
+ events.close()
596
+
597
+ def get_task(self, agent_id: str, task_id: str) -> Task:
598
+ """``GetTask``."""
599
+ call = _rpc(agent_id, "GetTask", _id_params(task_id))
600
+ return _task_of(_result(self._t.request(call)))
601
+
602
+ get = get_task # an alias
603
+
604
+ def tasks(
605
+ self,
606
+ agent_id: str,
607
+ *,
608
+ context_id: str | None = None,
609
+ status: str | None = None,
610
+ page_size: int = _DEFAULT_PAGE,
611
+ ) -> Iterator[Task]:
612
+ """``ListTasks`` as a lazy iterator: a page is fetched when the one before is used up."""
613
+
614
+ def fetch(token: str | None) -> tuple[list[Task], str | None]:
615
+ params = _list_params(context_id, status, page_size, token)
616
+ return _tasks_page(_result(self._t.request(_rpc(agent_id, "ListTasks", params))))
617
+
618
+ return iter_cursor(fetch)
619
+
620
+ def tasks_page(
621
+ self,
622
+ agent_id: str,
623
+ *,
624
+ context_id: str | None = None,
625
+ status: str | None = None,
626
+ page_token: str | None = None,
627
+ page_size: int = _DEFAULT_PAGE,
628
+ ) -> Page[Task]:
629
+ """One ``ListTasks`` page: its tasks and ``next``, the ``pageToken`` of the following page
630
+ (None at the end). A2A pages by a token and ``pageSize``, not by offset."""
631
+ params = _list_params(context_id, status, page_size, page_token)
632
+ items, following = _tasks_page(
633
+ _result(self._t.request(_rpc(agent_id, "ListTasks", params)))
634
+ )
635
+ return Page(items=items, next=following)
636
+
637
+ def cancel(self, agent_id: str, task_id: str) -> Task:
638
+ call = _rpc(agent_id, "CancelTask", _id_params(task_id))
639
+ return _task_of(_result(self._t.request(call)))
640
+
641
+
642
+ def _decode_body(response: httpx.Response) -> Event:
643
+ """A JSON body answered to a streaming call: an error raises, a result is one event."""
644
+ return _event_of(_result(response))
645
+
646
+
647
+ class AsyncAgents:
648
+ """The async twin of ``Agents``."""
649
+
650
+ def __init__(self, transport: AsyncTransport) -> None:
651
+ self._t = transport
652
+
653
+ async def list(self) -> list[AgentCard]:
654
+ return _agent_list(await self._t.request(_LIST_AGENTS))
655
+
656
+ async def card(self, agent_id: str) -> dict[str, Any]:
657
+ return _card_of(await self._t.request(_card_call(agent_id)))
658
+
659
+ async def send(
660
+ self,
661
+ agent_id: str,
662
+ text: str,
663
+ *,
664
+ context_id: str | None = None,
665
+ message_id: str | None = None,
666
+ return_immediately: bool = False,
667
+ timeout: float | None = None,
668
+ ) -> Task:
669
+ params = _send_params(text, context_id, message_id, return_immediately)
670
+ call = _rpc(
671
+ agent_id, "SendMessage", params, timeout=timeout, blocking=not return_immediately
672
+ )
673
+ return _task_of(_result(await self._t.request(call)))
674
+
675
+ @contextlib.asynccontextmanager
676
+ async def stream(
677
+ self,
678
+ agent_id: str,
679
+ text: str,
680
+ *,
681
+ context_id: str | None = None,
682
+ message_id: str | None = None,
683
+ chat_events: bool = False,
684
+ app_context: dict[str, Any] | None = None,
685
+ resume: bool = True,
686
+ ) -> AsyncIterator[AsyncIterator[Event | chat.ChatEvent]]:
687
+ _no_app_context(chat_events, app_context)
688
+ if not chat_events:
689
+ params = _send_params(text, context_id, message_id, False)
690
+ call = _rpc(agent_id, "SendStreamingMessage", params, stream=True)
691
+ async with self._t.stream(call) as response:
692
+ if _is_json(response):
693
+ await response.aread()
694
+ yield _one(_decode_body(response))
695
+ else:
696
+ yield _aevents(response, call)
697
+ return
698
+ params = _chat_params(text, context_id, message_id, app_context)
699
+ call = _rpc(agent_id, "SendStreamingMessage", params, stream=True, chat_events=True)
700
+ async with self._t.stream(call) as response:
701
+ events = _achat_events(
702
+ self._t, agent_id, chat.Run(resume=resume), response, call, self.get_task
703
+ )
704
+ try:
705
+ yield events
706
+ finally:
707
+ await events.aclose()
708
+
709
+ @contextlib.asynccontextmanager
710
+ async def subscribe(
711
+ self,
712
+ agent_id: str,
713
+ task_id: str,
714
+ *,
715
+ after_seq: int = 0,
716
+ chat_events: bool = True,
717
+ resume: bool = True,
718
+ ) -> AsyncIterator[AsyncIterator[Event | chat.ChatEvent]]:
719
+ position = _check_after_seq(after_seq)
720
+ if not chat_events:
721
+ call = _subscribe_call(agent_id, task_id, None)
722
+ async with self._t.stream(call) as response:
723
+ if _is_json(response):
724
+ await response.aread()
725
+ yield _one(_decode_body(response))
726
+ else:
727
+ yield _aevents(response, call)
728
+ return
729
+ call = _subscribe_call(agent_id, task_id, position)
730
+ async with self._t.stream(call) as response:
731
+ run = chat.Run(after_seq=position, resume=resume, task_id=task_id)
732
+ events = _achat_events(self._t, agent_id, run, response, call, self.get_task)
733
+ try:
734
+ yield events
735
+ finally:
736
+ await events.aclose()
737
+
738
+ async def get_task(self, agent_id: str, task_id: str) -> Task:
739
+ call = _rpc(agent_id, "GetTask", _id_params(task_id))
740
+ return _task_of(_result(await self._t.request(call)))
741
+
742
+ get = get_task # an alias
743
+
744
+ def tasks(
745
+ self,
746
+ agent_id: str,
747
+ *,
748
+ context_id: str | None = None,
749
+ status: str | None = None,
750
+ page_size: int = _DEFAULT_PAGE,
751
+ ) -> AsyncIterator[Task]:
752
+ async def fetch(token: str | None) -> tuple[list[Task], str | None]:
753
+ params = _list_params(context_id, status, page_size, token)
754
+ response = await self._t.request(_rpc(agent_id, "ListTasks", params))
755
+ return _tasks_page(_result(response))
756
+
757
+ return aiter_cursor(fetch)
758
+
759
+ async def tasks_page(
760
+ self,
761
+ agent_id: str,
762
+ *,
763
+ context_id: str | None = None,
764
+ status: str | None = None,
765
+ page_token: str | None = None,
766
+ page_size: int = _DEFAULT_PAGE,
767
+ ) -> Page[Task]:
768
+ params = _list_params(context_id, status, page_size, page_token)
769
+ response = await self._t.request(_rpc(agent_id, "ListTasks", params))
770
+ items, following = _tasks_page(_result(response))
771
+ return Page(items=items, next=following)
772
+
773
+ async def cancel(self, agent_id: str, task_id: str) -> Task:
774
+ call = _rpc(agent_id, "CancelTask", _id_params(task_id))
775
+ return _task_of(_result(await self._t.request(call)))
776
+
777
+
778
+ async def _one(event: Event) -> AsyncIterator[Event]:
779
+ yield event
780
+
781
+
782
+ __all__ = [
783
+ "TERMINAL_STATES",
784
+ "AgentCard",
785
+ "Agents",
786
+ "ArtifactUpdate",
787
+ "AsyncAgents",
788
+ "Event",
789
+ "StatusUpdate",
790
+ "Task",
791
+ "TaskSnapshot",
792
+ "Unknown",
793
+ ]