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,630 @@
1
+ """HTTP transport: one core, a sync and an async shell, retries, DPoP and safe logging.
2
+
3
+ The two transports differ only in I/O. Everything that decides something is shared and has no
4
+ I/O: ``may_retry`` (the retry policy, a pure function), ``backoff_s``, and ``_Run`` (the state of
5
+ one call: the request to build, the try count, the wait budget and the DPoP nonce).
6
+
7
+ Safety rules that this module enforces:
8
+
9
+ * A request that may have run is repeated only when the policy says it is safe (``may_retry``).
10
+ * A body that cannot be replayed (a one-shot iterator, an unseekable file) is never resent.
11
+ * Redirects are never followed and never retried; they raise ``<area>.unavailable``.
12
+ * With a ``DPoPKey`` set, every request is ``DPoP``-scheme with a fresh proof; the transport never
13
+ falls back to ``Bearer``.
14
+ * A log line holds the method, the path template, the status and the error code. No header, body,
15
+ token, workspace id or URL goes into a log.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import asyncio
21
+ import contextlib
22
+ import logging
23
+ import math
24
+ import random
25
+ import re
26
+ import threading
27
+ import time
28
+ from collections.abc import AsyncIterator, Callable, Iterable, Iterator, Mapping
29
+ from dataclasses import dataclass, field
30
+ from typing import Any
31
+ from urllib.parse import quote
32
+
33
+ import httpx
34
+
35
+ from . import __version__
36
+ from ._contract import ERRORS, OPERATIONS, is_retryable
37
+ from .auth import AsyncTokenCallable, DPoPKey, TokenProvider
38
+ from .errors import AREA_EXTENSION, PlatformError, error_from_response, error_from_transport
39
+
40
+ _log = logging.getLogger("agentic_platform_sdk")
41
+
42
+ DPOP_NONCE_REQUIRED = "gateway.dpop_nonce_required"
43
+ _REFUSED_BEFORE_RUN = frozenset(code for code, info in ERRORS.items() if info.refused_before_run)
44
+ _NEVER_RETRIED_OPERATION = "createChatCompletion" # once it reached the model, it cost tokens
45
+ _SEND_MESSAGE = "SendMessage" # A2A: deduplicated by messageId
46
+ _UPLOAD_OPERATION = "uploadKnowledgeBaseDocument"
47
+
48
+ _DEFAULT_TIMEOUT_S = 30.0
49
+ _AREA_TIMEOUT_S = {"llm": 180.0, "vision": 600.0}
50
+ _UPLOAD_TIMEOUT_S = 300.0
51
+ _BLOCKING_SEND_TIMEOUT_S = 250.0 # the platform's blocking wait cap (240 s) plus slack
52
+ _STREAM_AREA = "agents" # an A2A stream is open as long as the task runs: no read timeout
53
+
54
+ _RESERVED_HEADERS = frozenset({"authorization", "dpop", "x-workspace-id", "idempotency-key"})
55
+ _PATH_PARAM = re.compile(r"\{(\w+)\}")
56
+ _MAX_DOUBLINGS = 60 # keeps ``2 ** attempt`` a small number whatever the attempt count
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class RetryConfig:
61
+ """``tries`` counts every attempt (the first included); ``budget_s`` bounds the total wait."""
62
+
63
+ tries: int = 3
64
+ budget_s: float = 30.0
65
+ base_s: float = 0.5
66
+ cap_s: float = 8.0
67
+
68
+
69
+ @dataclass
70
+ class Call:
71
+ """One request to an operation. ``operation`` is the operationId; the path comes from it."""
72
+
73
+ operation: str
74
+ area: str
75
+ path_params: dict[str, Any] = field(default_factory=dict)
76
+ query: dict[str, Any] | None = None
77
+ json: Any | None = None
78
+ files: Any | None = None
79
+ content: Iterable[bytes] | None = None
80
+ idempotency_key: str | None = None
81
+ # A call known to have been answered with a redirect is never retried.
82
+ redirect: bool = False
83
+ timeout: float | None = None
84
+ # Informational for callers: the method used (request or stream) decides how it is sent.
85
+ stream: bool = False
86
+ jsonrpc_method: str | None = None # for callA2AJsonRpc
87
+ # Extra request headers (``A2A-Version``). The credentials and ``X-Workspace-Id`` always win.
88
+ headers: dict[str, str] | None = None
89
+ # An A2A SendMessage without returnImmediately: the platform holds it up to 240 s.
90
+ blocking: bool = False
91
+
92
+
93
+ # --- the policy ------------------------------------------------------------------------------
94
+
95
+
96
+ def may_retry(
97
+ call: Call, code: str | None, transport_failure: bool, redirect: bool = False
98
+ ) -> bool:
99
+ """Whether a failed attempt of `call` may be repeated.
100
+
101
+ `code` is the platform error code (None when there is none) and `transport_failure` says the
102
+ attempt got no response. A redirect is never retried. The gateway's own refusals (it never ran
103
+ the request) are retried for any call. Otherwise a retryable code or a transport failure is
104
+ retried only when repeating the request is safe: a GET, an operation marked safe-retry, a
105
+ POST/PUT with an Idempotency-Key on an operation that declares the header, or an A2A
106
+ ``SendMessage``. ``createChatCompletion`` is never retried once it could have reached the
107
+ model.
108
+ """
109
+ if redirect or call.redirect:
110
+ return False
111
+ if code in _REFUSED_BEFORE_RUN:
112
+ return True
113
+ if call.operation == _NEVER_RETRIED_OPERATION:
114
+ return False
115
+ if not (transport_failure or (code is not None and is_retryable(code))):
116
+ return False
117
+ operation = OPERATIONS[call.operation]
118
+ return (
119
+ operation.method == "GET"
120
+ or operation.safe_retry
121
+ or (
122
+ operation.method in ("POST", "PUT")
123
+ and bool(call.idempotency_key)
124
+ and operation.idempotency_key
125
+ )
126
+ or call.jsonrpc_method == _SEND_MESSAGE
127
+ )
128
+
129
+
130
+ def _jitter() -> float:
131
+ return random.uniform(0.5, 1.0)
132
+
133
+
134
+ def backoff_s(retry: RetryConfig, attempt: int, retry_after: float | None, jitter: float) -> float:
135
+ """The wait before the next try: ``max(retry_after, min(cap, base * 2**attempt) * jitter)``."""
136
+ exponential = retry.base_s * 2.0 ** min(attempt, _MAX_DOUBLINGS)
137
+ return max(retry_after or 0.0, min(retry.cap_s, exponential) * jitter)
138
+
139
+
140
+ def _sleep(seconds: float) -> None:
141
+ time.sleep(seconds)
142
+
143
+
144
+ async def _asleep(seconds: float) -> None:
145
+ await asyncio.sleep(seconds)
146
+
147
+
148
+ # --- the shared core -------------------------------------------------------------------------
149
+
150
+
151
+ def _is_plain(content: Any) -> bool:
152
+ return isinstance(content, bytes | bytearray | memoryview | str)
153
+
154
+
155
+ def _file_objects(files: Any) -> list[Any]:
156
+ """The file-like objects inside an httpx ``files`` argument (a mapping or a sequence)."""
157
+ if files is None:
158
+ return []
159
+ values = files.values() if isinstance(files, Mapping) else (pair[1] for pair in files)
160
+ found = []
161
+ for value in values:
162
+ if isinstance(value, tuple):
163
+ value = value[1] if len(value) > 1 else value[0]
164
+ if hasattr(value, "read"):
165
+ found.append(value)
166
+ return found
167
+
168
+
169
+ class _Body:
170
+ """Whether the request body can be sent again, and how to rewind it for the next attempt."""
171
+
172
+ def __init__(self, call: Call) -> None:
173
+ self.replayable = True
174
+ self._files: list[tuple[Any, int]] = []
175
+ content = call.content
176
+ if content is not None and not _is_plain(content):
177
+ try:
178
+ one_shot = hasattr(content, "__aiter__") or iter(content) is content
179
+ except TypeError:
180
+ one_shot = True
181
+ if one_shot:
182
+ self.replayable = False
183
+ for obj in _file_objects(call.files):
184
+ try:
185
+ self._files.append((obj, obj.tell()))
186
+ except (AttributeError, OSError, ValueError):
187
+ self.replayable = False
188
+
189
+ def rewind(self) -> None:
190
+ for obj, position in self._files:
191
+ obj.seek(position)
192
+
193
+
194
+ async def _aiter(chunks: Iterable[bytes]) -> AsyncIterator[bytes]:
195
+ for chunk in chunks:
196
+ yield chunk
197
+
198
+
199
+ class _Core:
200
+ """What the two transports share: configuration, URL and header building, the nonce cache."""
201
+
202
+ def __init__(
203
+ self,
204
+ base_url: str,
205
+ token: TokenProvider,
206
+ workspace_id: str | None,
207
+ dpop: DPoPKey | None,
208
+ retry: RetryConfig,
209
+ timeouts: Mapping[str, float] | None,
210
+ user_agent: str,
211
+ ) -> None:
212
+ if not base_url.startswith(("http://", "https://")):
213
+ raise ValueError("base_url must start with http:// or https://")
214
+ self.base_url = base_url.rstrip("/")
215
+ self.token = token
216
+ self.workspace_id = workspace_id
217
+ self.dpop = dpop
218
+ self.retry = retry
219
+ self.timeouts = dict(timeouts or {})
220
+ self.user_agent = user_agent
221
+ # The latest server nonce: the platform counts a refused proof against a failed-auth
222
+ # budget, so a nonce learned once is sent on later proofs as well.
223
+ self.nonce: str | None = None
224
+
225
+ def timeout(self, call: Call, streaming: bool) -> httpx.Timeout:
226
+ """Precedence: the call, the caller's entry for the operation, the operation's own default
227
+ (an upload's 300 s, a blocking A2A send's 250 s, an agents stream without a read
228
+ timeout), the caller's entry for the area, the area default. So an area entry never undoes
229
+ an operation default."""
230
+ if call.timeout is not None:
231
+ return httpx.Timeout(call.timeout)
232
+ configured = self.timeouts.get(call.operation)
233
+ if configured is not None:
234
+ return httpx.Timeout(configured)
235
+ if call.operation == _UPLOAD_OPERATION:
236
+ return httpx.Timeout(_UPLOAD_TIMEOUT_S)
237
+ if call.blocking:
238
+ return httpx.Timeout(_BLOCKING_SEND_TIMEOUT_S)
239
+ if streaming and call.area == _STREAM_AREA:
240
+ return httpx.Timeout(_DEFAULT_TIMEOUT_S, read=None)
241
+ configured = self.timeouts.get(call.area)
242
+ if configured is not None:
243
+ return httpx.Timeout(configured)
244
+ return httpx.Timeout(_AREA_TIMEOUT_S.get(call.area, _DEFAULT_TIMEOUT_S))
245
+
246
+ def learn_nonce(self, headers: httpx.Headers) -> None:
247
+ if self.dpop is not None:
248
+ nonce = headers.get("DPoP-Nonce")
249
+ if nonce:
250
+ self.nonce = nonce
251
+
252
+ def run(self, call: Call) -> _Run:
253
+ return _Run(self, call)
254
+
255
+
256
+ def _fill_path(template: str, params: Mapping[str, Any]) -> str:
257
+ def value(match: re.Match[str]) -> str:
258
+ name = match.group(1)
259
+ if name not in params:
260
+ raise ValueError(f"missing path parameter {name!r}")
261
+ text = str(params[name])
262
+ if text in ("", ".", ".."):
263
+ raise ValueError(f"path parameter {name!r} must be a real identifier")
264
+ return quote(text, safe="")
265
+
266
+ return _PATH_PARAM.sub(value, template)
267
+
268
+
269
+ class _Run:
270
+ """The state of one call across its attempts. No I/O."""
271
+
272
+ def __init__(self, core: _Core, call: Call) -> None:
273
+ operation = OPERATIONS[call.operation]
274
+ self.core = core
275
+ self.call = call
276
+ self.method = operation.method
277
+ self.template = operation.path # what is logged: ids in a URL could be sensitive
278
+ self.url = core.base_url + _fill_path(operation.path, call.path_params)
279
+ self.body = _Body(call)
280
+ self.tries = 0
281
+ self.waited = 0.0
282
+ self._nonce_retried = False
283
+ self._started = False
284
+
285
+ def begin(self) -> None:
286
+ """Call before each attempt: rewinds what the last attempt read."""
287
+ if self._started:
288
+ self.body.rewind()
289
+ self._started = True
290
+
291
+ def request_args(self, token: str, *, streaming: bool, aio: bool) -> dict[str, Any]:
292
+ core, call = self.core, self.call
293
+ headers = {"User-Agent": core.user_agent}
294
+ for name, value in (call.headers or {}).items():
295
+ if name.lower() not in _RESERVED_HEADERS:
296
+ headers[name] = value
297
+ if core.dpop is not None:
298
+ headers["Authorization"] = f"DPoP {token}"
299
+ headers["DPoP"] = core.dpop.proof(self.method, self.url, token, core.nonce)
300
+ else:
301
+ headers["Authorization"] = f"Bearer {token}"
302
+ if core.workspace_id:
303
+ headers["X-Workspace-Id"] = core.workspace_id
304
+ if call.idempotency_key:
305
+ headers["Idempotency-Key"] = call.idempotency_key
306
+ args: dict[str, Any] = {
307
+ "method": self.method,
308
+ "url": self.url,
309
+ "headers": headers,
310
+ "timeout": core.timeout(call, streaming),
311
+ }
312
+ if call.query:
313
+ args["params"] = {k: v for k, v in call.query.items() if v is not None}
314
+ if call.json is not None:
315
+ args["json"] = call.json
316
+ if call.files is not None:
317
+ args["files"] = call.files
318
+ if call.content is not None:
319
+ content = call.content
320
+ args["content"] = (
321
+ _aiter(content)
322
+ if aio and not _is_plain(content) and not hasattr(content, "__aiter__")
323
+ else content
324
+ )
325
+ return args
326
+
327
+ def log(self, status: int | None, code: str | None) -> None:
328
+ _log.info(
329
+ "%s %s -> %s %s",
330
+ self.method,
331
+ self.template,
332
+ "-" if status is None else status,
333
+ code or "-",
334
+ )
335
+
336
+ def judge(self, response: httpx.Response) -> PlatformError | None:
337
+ """None for a 2xx response, else the error for it. A failure response must be read."""
338
+ self.core.learn_nonce(response.headers)
339
+ if response.is_success:
340
+ self.log(response.status_code, None)
341
+ return None
342
+ err = error_from_response(
343
+ response.status_code, response.headers, response.content, self.call.area
344
+ )
345
+ self.log(response.status_code, err.code)
346
+ return err
347
+
348
+ def transport_error(self, exc: httpx.HTTPError) -> PlatformError:
349
+ err = error_from_transport(exc, self.call.area)
350
+ self.log(None, err.code)
351
+ return err
352
+
353
+ def failure(
354
+ self,
355
+ err: PlatformError,
356
+ *,
357
+ transport_failure: bool = False,
358
+ redirect: bool = False,
359
+ nonce: str | None = None,
360
+ ) -> float:
361
+ """Seconds to wait before the next attempt, or raise `err` when there is none."""
362
+ if (
363
+ not transport_failure
364
+ and not redirect
365
+ and not self._nonce_retried
366
+ and self.body.replayable # a body that cannot be sent again is not retried
367
+ and self.core.dpop is not None
368
+ and err.http_status == 401
369
+ and err.code == DPOP_NONCE_REQUIRED
370
+ and nonce
371
+ ):
372
+ # Retried at once with the nonce in the proof; this is not one of the tries.
373
+ self._nonce_retried = True
374
+ self.core.nonce = nonce
375
+ return 0.0
376
+ retry = self.core.retry
377
+ self.tries += 1
378
+ if (
379
+ self.tries >= retry.tries
380
+ or not self.body.replayable
381
+ or not may_retry(self.call, err.code, transport_failure, redirect)
382
+ ):
383
+ raise err
384
+ wait = backoff_s(retry, self.tries - 1, err.retry_after, _jitter())
385
+ # A huge Retry-After (a far-future date) must stop here, never be slept.
386
+ if not math.isfinite(wait) or self.waited + wait > retry.budget_s:
387
+ raise err
388
+ self.waited += wait
389
+ return wait
390
+
391
+
392
+ def _mid_stream_error(call: Call, exc: httpx.HTTPError) -> PlatformError:
393
+ """The error for a transport failure after a stream opened (a reset, a read timeout)."""
394
+ err = error_from_transport(exc, call.area)
395
+ operation = OPERATIONS[call.operation]
396
+ _log.info("%s %s -> - %s", operation.method, operation.path, err.code)
397
+ return err
398
+
399
+
400
+ def _is_redirect(response: httpx.Response) -> bool:
401
+ return 300 <= response.status_code < 400
402
+
403
+
404
+ def _check_provider(token: TokenProvider, *, aio: bool) -> None:
405
+ if not aio and isinstance(token, AsyncTokenCallable):
406
+ raise TypeError("SyncTransport cannot use an AsyncTokenCallable; use AsyncTransport")
407
+
408
+
409
+ _DEFAULT_USER_AGENT = f"agentic-platform-sdk-python/{__version__}"
410
+
411
+
412
+ # --- sync ------------------------------------------------------------------------------------
413
+
414
+
415
+ class SyncTransport:
416
+ """Blocking transport. ``pooled=False`` (the default) opens a client per call, which is safe
417
+ across ``fork`` and threads; ``pooled=True`` shares one client until ``close()``."""
418
+
419
+ def __init__(
420
+ self,
421
+ base_url: str,
422
+ token: TokenProvider,
423
+ workspace_id: str | None,
424
+ dpop: DPoPKey | None = None,
425
+ retry: RetryConfig = RetryConfig(), # noqa: B008 - frozen, so safe to share
426
+ timeouts: Mapping[str, float] | None = None,
427
+ pooled: bool = False,
428
+ http_factory: Callable[[], httpx.Client] | None = None,
429
+ user_agent: str = _DEFAULT_USER_AGENT,
430
+ ) -> None:
431
+ _check_provider(token, aio=False)
432
+ self._core = _Core(base_url, token, workspace_id, dpop, retry, timeouts, user_agent)
433
+ self._pooled = pooled
434
+ self._factory = http_factory or (lambda: httpx.Client(follow_redirects=False))
435
+ self._shared: httpx.Client | None = None
436
+ self._lock = threading.Lock()
437
+
438
+ def _client(self) -> tuple[httpx.Client, bool]:
439
+ """The client to use and whether this call owns (must close) it."""
440
+ if not self._pooled:
441
+ return self._factory(), True
442
+ with self._lock:
443
+ if self._shared is None:
444
+ self._shared = self._factory()
445
+ return self._shared, False
446
+
447
+ def close(self) -> None:
448
+ with self._lock:
449
+ shared, self._shared = self._shared, None
450
+ if shared is not None:
451
+ shared.close()
452
+
453
+ def __enter__(self) -> SyncTransport:
454
+ return self
455
+
456
+ def __exit__(self, *exc_info: object) -> None:
457
+ self.close()
458
+
459
+ def request(self, call: Call) -> httpx.Response:
460
+ """Send `call`; return the 2xx response with its body read. Anything else raises."""
461
+ client, owned = self._client()
462
+ try:
463
+ return self._execute(client, call, streaming=False)
464
+ finally:
465
+ if owned:
466
+ client.close()
467
+
468
+ @contextlib.contextmanager
469
+ def stream(self, call: Call) -> Iterator[httpx.Response]:
470
+ """Send `call`; yield the open 2xx response. Retries apply only until it opens."""
471
+ client, owned = self._client()
472
+ try:
473
+ response = self._execute(client, call, streaming=True)
474
+ try:
475
+ yield response
476
+ except httpx.HTTPError as exc: # the body failed after the stream had opened
477
+ raise _mid_stream_error(call, exc) from exc
478
+ finally:
479
+ response.close()
480
+ finally:
481
+ if owned:
482
+ client.close()
483
+
484
+ def _execute(self, client: httpx.Client, call: Call, *, streaming: bool) -> httpx.Response:
485
+ run = self._core.run(call)
486
+ while True:
487
+ run.begin()
488
+ token = self._core.token.token()
489
+ args = run.request_args(token, streaming=streaming, aio=False)
490
+ response: httpx.Response | None = None
491
+ try:
492
+ response = client.send(
493
+ client.build_request(**args), stream=True, follow_redirects=False
494
+ )
495
+ try:
496
+ if not (streaming and response.is_success):
497
+ response.read()
498
+ response.close()
499
+ except BaseException:
500
+ response.close()
501
+ raise
502
+ except httpx.HTTPError as exc:
503
+ err = run.transport_error(exc)
504
+ wait = run.failure(err, transport_failure=True)
505
+ else:
506
+ failure = run.judge(response)
507
+ if failure is None:
508
+ response.extensions[AREA_EXTENSION] = call.area # for _util.parse
509
+ return response
510
+ wait = run.failure(
511
+ failure,
512
+ redirect=_is_redirect(response),
513
+ nonce=response.headers.get("DPoP-Nonce"),
514
+ )
515
+ if wait:
516
+ _sleep(wait)
517
+
518
+
519
+ # --- async -----------------------------------------------------------------------------------
520
+
521
+
522
+ class AsyncTransport:
523
+ """The async twin of ``SyncTransport``. ``pooled=True`` shares one client until ``aclose()``."""
524
+
525
+ def __init__(
526
+ self,
527
+ base_url: str,
528
+ token: TokenProvider,
529
+ workspace_id: str | None,
530
+ dpop: DPoPKey | None = None,
531
+ retry: RetryConfig = RetryConfig(), # noqa: B008 - frozen, so safe to share
532
+ timeouts: Mapping[str, float] | None = None,
533
+ pooled: bool = False,
534
+ http_factory: Callable[[], httpx.AsyncClient] | None = None,
535
+ user_agent: str = _DEFAULT_USER_AGENT,
536
+ ) -> None:
537
+ self._core = _Core(base_url, token, workspace_id, dpop, retry, timeouts, user_agent)
538
+ self._pooled = pooled
539
+ self._factory = http_factory or (lambda: httpx.AsyncClient(follow_redirects=False))
540
+ self._shared: httpx.AsyncClient | None = None
541
+
542
+ def _client(self) -> tuple[httpx.AsyncClient, bool]:
543
+ if not self._pooled:
544
+ return self._factory(), True
545
+ if self._shared is None: # no await in between: one event loop cannot interleave this
546
+ self._shared = self._factory()
547
+ return self._shared, False
548
+
549
+ async def aclose(self) -> None:
550
+ shared, self._shared = self._shared, None
551
+ if shared is not None:
552
+ await shared.aclose()
553
+
554
+ async def __aenter__(self) -> AsyncTransport:
555
+ return self
556
+
557
+ async def __aexit__(self, *exc_info: object) -> None:
558
+ await self.aclose()
559
+
560
+ async def request(self, call: Call) -> httpx.Response:
561
+ """Send `call`; return the 2xx response with its body read. Anything else raises."""
562
+ client, owned = self._client()
563
+ try:
564
+ return await self._execute(client, call, streaming=False)
565
+ finally:
566
+ if owned:
567
+ await client.aclose()
568
+
569
+ @contextlib.asynccontextmanager
570
+ async def stream(self, call: Call) -> AsyncIterator[httpx.Response]:
571
+ """Send `call`; yield the open 2xx response. Retries apply only until it opens."""
572
+ client, owned = self._client()
573
+ try:
574
+ response = await self._execute(client, call, streaming=True)
575
+ try:
576
+ yield response
577
+ except httpx.HTTPError as exc: # the body failed after the stream had opened
578
+ raise _mid_stream_error(call, exc) from exc
579
+ finally:
580
+ await response.aclose()
581
+ finally:
582
+ if owned:
583
+ await client.aclose()
584
+
585
+ async def _execute(
586
+ self, client: httpx.AsyncClient, call: Call, *, streaming: bool
587
+ ) -> httpx.Response:
588
+ run = self._core.run(call)
589
+ while True:
590
+ run.begin()
591
+ token = await self._core.token.atoken()
592
+ args = run.request_args(token, streaming=streaming, aio=True)
593
+ response: httpx.Response | None = None
594
+ try:
595
+ response = await client.send(
596
+ client.build_request(**args), stream=True, follow_redirects=False
597
+ )
598
+ try:
599
+ if not (streaming and response.is_success):
600
+ await response.aread()
601
+ await response.aclose()
602
+ except BaseException:
603
+ await response.aclose()
604
+ raise
605
+ except httpx.HTTPError as exc:
606
+ err = run.transport_error(exc)
607
+ wait = run.failure(err, transport_failure=True)
608
+ else:
609
+ failure = run.judge(response)
610
+ if failure is None:
611
+ response.extensions[AREA_EXTENSION] = call.area # for _util.parse
612
+ return response
613
+ wait = run.failure(
614
+ failure,
615
+ redirect=_is_redirect(response),
616
+ nonce=response.headers.get("DPoP-Nonce"),
617
+ )
618
+ if wait:
619
+ await _asleep(wait)
620
+
621
+
622
+ __all__ = [
623
+ "DPOP_NONCE_REQUIRED",
624
+ "AsyncTransport",
625
+ "Call",
626
+ "RetryConfig",
627
+ "SyncTransport",
628
+ "backoff_s",
629
+ "may_retry",
630
+ ]