python-wrap 0.2.1__py3-none-any.whl → 0.4.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 (88) hide show
  1. python_wrap/__init__.py +348 -1
  2. python_wrap/__main__.py +57 -0
  3. python_wrap/_backend.py +133 -0
  4. python_wrap/_buckets.py +162 -0
  5. python_wrap/_core.py +12 -3
  6. python_wrap/_data/agent_guide.md +103 -0
  7. python_wrap/_data/recipes.json +703 -0
  8. python_wrap/_fork.py +113 -0
  9. python_wrap/_integration.py +29 -0
  10. python_wrap/_runtime.py +157 -0
  11. python_wrap/adapters/__init__.py +101 -0
  12. python_wrap/adapters/_frameworks.py +251 -0
  13. python_wrap/adapters/_sdk.py +1978 -0
  14. python_wrap/adapters/anthropic.py +139 -0
  15. python_wrap/adapters/langchain.py +288 -0
  16. python_wrap/adapters/openai.py +169 -0
  17. python_wrap/adapters/openai_agents.py +468 -0
  18. python_wrap/adapters/pydantic_ai.py +459 -0
  19. python_wrap/adaptive.py +605 -0
  20. python_wrap/agents.py +2503 -0
  21. python_wrap/alerts.py +293 -0
  22. python_wrap/async_cache.py +745 -0
  23. python_wrap/batching.py +17 -4
  24. python_wrap/buffering.py +952 -0
  25. python_wrap/bulkhead.py +58 -6
  26. python_wrap/caching.py +425 -56
  27. python_wrap/celery.py +528 -0
  28. python_wrap/chaos.py +519 -0
  29. python_wrap/circuit.py +454 -23
  30. python_wrap/compat.py +267 -0
  31. python_wrap/concurrency.py +82 -1746
  32. python_wrap/config.py +25 -4
  33. python_wrap/coordination.py +638 -0
  34. python_wrap/credentials.py +126 -0
  35. python_wrap/dashboard.py +358 -0
  36. python_wrap/debounce.py +538 -0
  37. python_wrap/django.py +100 -0
  38. python_wrap/doctor.py +599 -0
  39. python_wrap/events.py +145 -4
  40. python_wrap/exporters.py +663 -0
  41. python_wrap/fastapi.py +81 -0
  42. python_wrap/flask.py +61 -0
  43. python_wrap/genai.py +1101 -0
  44. python_wrap/health.py +187 -0
  45. python_wrap/http.py +940 -0
  46. python_wrap/idempotency.py +446 -0
  47. python_wrap/introspect.py +738 -0
  48. python_wrap/lifecycle.py +620 -0
  49. python_wrap/llm.py +2574 -0
  50. python_wrap/llm_cassette.py +948 -0
  51. python_wrap/llm_http_chaos.py +326 -0
  52. python_wrap/llm_shared.py +772 -0
  53. python_wrap/llm_testing.py +990 -0
  54. python_wrap/llm_validate.py +383 -0
  55. python_wrap/local_state.py +395 -0
  56. python_wrap/logs.py +82 -26
  57. python_wrap/mcp.py +490 -0
  58. python_wrap/mcp_guard.py +357 -0
  59. python_wrap/metrics.py +6 -3
  60. python_wrap/migrate.py +1452 -0
  61. python_wrap/observability.py +484 -0
  62. python_wrap/periodic.py +24 -2
  63. python_wrap/policies.py +396 -0
  64. python_wrap/policy.py +14 -0
  65. python_wrap/predicates.py +276 -0
  66. python_wrap/presets.py +378 -0
  67. python_wrap/processing.py +227 -0
  68. python_wrap/propagation.py +62 -0
  69. python_wrap/pytest_plugin.py +85 -0
  70. python_wrap/quotas.py +319 -0
  71. python_wrap/ratelimit.py +560 -0
  72. python_wrap/redaction.py +228 -0
  73. python_wrap/retry.py +448 -70
  74. python_wrap/shared.py +653 -0
  75. python_wrap/singleflight.py +255 -0
  76. python_wrap/slow.py +72 -0
  77. python_wrap/stores.py +168 -0
  78. python_wrap/switches.py +164 -0
  79. python_wrap/testing.py +34 -8
  80. python_wrap/timeouts.py +874 -0
  81. python_wrap/timing.py +239 -17
  82. python_wrap/validation.py +187 -12
  83. python_wrap/web.py +723 -0
  84. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/METADATA +117 -7
  85. python_wrap-0.4.0.dist-info/RECORD +95 -0
  86. python_wrap-0.2.1.dist-info/RECORD +0 -29
  87. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/WHEEL +0 -0
  88. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,1978 @@
1
+ """Shared machinery for the provider SDK adapters (`guard_openai`, `guard_anthropic`).
2
+
3
+ Nothing here imports a provider SDK. Clients, responses, stream events and errors are
4
+ read by shape, so the same code works with the real ``openai`` / ``anthropic`` packages,
5
+ with their ``with_raw_response`` wrappers, and with hand-written fakes.
6
+
7
+ - `no_sdk_retries` / `sdk_max_retries`: turn the SDK's own retry loop off so
8
+ python-wrap's is the only one (attempts never multiply across layers).
9
+ - `seed_limiter`: feed ``x-ratelimit-remaining-tokens``,
10
+ ``anthropic-ratelimit-tokens-remaining`` and ``retry-after`` back into a
11
+ `TokenRateLimiter`.
12
+ - `resume_safe` / `ResumableStream` / `StreamInterrupted`: reopen a stream that fails
13
+ before any output, never replay one that already produced text or a tool call.
14
+ - `CacheGuard`: watch prompt-cache hits and flag prefixes that change per request.
15
+ - `GuardedClient`: the proxy both adapters build on.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import contextlib
21
+ import dataclasses
22
+ import functools
23
+ import hashlib
24
+ import inspect
25
+ import json
26
+ import math
27
+ import re
28
+ import threading
29
+ import warnings
30
+ from collections.abc import (
31
+ AsyncGenerator,
32
+ AsyncIterable,
33
+ AsyncIterator,
34
+ Callable,
35
+ Generator,
36
+ Iterable,
37
+ Iterator,
38
+ Mapping,
39
+ Sequence,
40
+ )
41
+ from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast
42
+
43
+ from python_wrap import _core
44
+ from python_wrap.errors import PythonWrapError
45
+ from python_wrap.llm import (
46
+ Budget,
47
+ TokenRateLimiter,
48
+ Usage,
49
+ _field,
50
+ _int,
51
+ _maybe_await,
52
+ _sdk_retries,
53
+ llm_retry,
54
+ llm_retry_after,
55
+ llm_transient,
56
+ read_usage,
57
+ stream_timeout,
58
+ )
59
+
60
+ if TYPE_CHECKING:
61
+ from python_wrap.doctor import Finding, Layer, Report
62
+
63
+ __all__ = [
64
+ "CacheGuard",
65
+ "CacheStats",
66
+ "GuardedClient",
67
+ "PromptCacheWarning",
68
+ "ResumableStream",
69
+ "StreamInterrupted",
70
+ "StreamedToolCall",
71
+ "no_sdk_retries",
72
+ "resume_safe",
73
+ "sdk_max_retries",
74
+ "seed_limiter",
75
+ "stream_transient",
76
+ ]
77
+
78
+ T = TypeVar("T")
79
+ C = TypeVar("C")
80
+
81
+ _LAYER_ATTR = "__python_wrap_layer__"
82
+
83
+
84
+ # ------------------------------------------------------------------- SDK retries
85
+
86
+
87
+ def no_sdk_retries(client: C) -> C:
88
+ """A copy of an SDK client with the SDK's own retries turned off.
89
+
90
+ Both the OpenAI and the Anthropic Python SDKs retry 408/409/429/5xx twice by
91
+ default. Under a python-wrap retry that multiplies: ``llm_retry(max_attempts=4)``
92
+ around a client with ``max_retries=2`` makes up to 4 x 3 = 12 HTTP requests per
93
+ call, and the SDK's waits ignore your `RetryBudget`. This returns
94
+ ``client.with_options(max_retries=0)`` (or ``client.copy(max_retries=0)``): the
95
+ original client is unchanged and shares its connection pool with the copy.
96
+
97
+ Args:
98
+ client: An ``OpenAI`` / ``AsyncOpenAI`` / ``Anthropic`` / ``AsyncAnthropic``
99
+ client, or anything with ``with_options(max_retries=...)``.
100
+
101
+ Returns:
102
+ The client copy.
103
+
104
+ Raises:
105
+ TypeError: If the client has neither ``with_options`` nor ``copy``.
106
+
107
+ Example:
108
+ ```python
109
+ from python_wrap.adapters import no_sdk_retries, sdk_max_retries
110
+
111
+
112
+ class Client: # the shape of an SDK client
113
+ def __init__(self, max_retries: int = 2) -> None:
114
+ self.max_retries = max_retries
115
+
116
+ def with_options(self, *, max_retries: int) -> "Client":
117
+ return Client(max_retries)
118
+
119
+
120
+ client = Client()
121
+ assert sdk_max_retries(no_sdk_retries(client)) == 0
122
+ assert sdk_max_retries(client) == 2 # the original keeps its setting
123
+ ```
124
+ """
125
+ for method in ("with_options", "copy"):
126
+ build = getattr(client, method, None)
127
+ if callable(build):
128
+ return cast(C, build(max_retries=0))
129
+ raise TypeError(
130
+ f"{type(client).__name__} has no with_options()/copy(): build the SDK client "
131
+ "with max_retries=0 yourself"
132
+ )
133
+
134
+
135
+ def sdk_max_retries(client: Any) -> int | None:
136
+ """The ``max_retries`` an SDK client (or a guard around one) is set to, or None."""
137
+ return _sdk_retries(client)
138
+
139
+
140
+ # ------------------------------------------------------------------ rate headers
141
+
142
+ _REMAINING_HEADERS = (
143
+ "x-ratelimit-remaining-tokens",
144
+ "anthropic-ratelimit-tokens-remaining",
145
+ "anthropic-ratelimit-input-tokens-remaining",
146
+ )
147
+
148
+
149
+ def _headers_of(source: Any) -> Any:
150
+ """Response headers of a raw response, an SDK error or its ``.response``."""
151
+ if source is None:
152
+ return None
153
+ headers = getattr(source, "headers", None)
154
+ if headers is None:
155
+ headers = getattr(getattr(source, "response", None), "headers", None)
156
+ return headers
157
+
158
+
159
+ def _header_items(headers: Any) -> list[tuple[str, Any]]:
160
+ if headers is None:
161
+ return []
162
+ try:
163
+ items = headers.items() if hasattr(headers, "items") else headers
164
+ return [(str(key).casefold(), value) for key, value in items]
165
+ except (TypeError, ValueError, AttributeError):
166
+ return []
167
+
168
+
169
+ def remaining_tokens(headers: Any) -> int | None:
170
+ """The smallest token allowance left that the provider's rate-limit headers report."""
171
+ found: list[int] = []
172
+ for key, value in _header_items(headers):
173
+ if key in _REMAINING_HEADERS:
174
+ try:
175
+ number = float(str(value).strip())
176
+ except ValueError:
177
+ continue
178
+ if math.isfinite(number):
179
+ found.append(max(int(number), 0))
180
+ return min(found) if found else None
181
+
182
+
183
+ def seed_limiter(
184
+ limiter: TokenRateLimiter, headers: Any = None, *, retry_after: float | None = None
185
+ ) -> None:
186
+ """Tell a `TokenRateLimiter` what the provider says about its quota.
187
+
188
+ The provider knows about every client sharing your key; the local bucket only about
189
+ this process. After each response the bucket is lowered (never raised) to the
190
+ ``x-ratelimit-remaining-tokens`` (OpenAI) or ``anthropic-ratelimit-tokens-remaining``
191
+ / ``anthropic-ratelimit-input-tokens-remaining`` (Anthropic) value. After a 429 with
192
+ ``retry_after`` seconds the bucket is drained so the next reservation waits at least
193
+ that long.
194
+
195
+ Args:
196
+ limiter: The limiter to adjust.
197
+ headers: Response headers (any mapping or ``(key, value)`` pairs), or None.
198
+ retry_after: Seconds the provider asked to wait, or None.
199
+ """
200
+ remaining = remaining_tokens(headers)
201
+ wait = retry_after if retry_after is not None and math.isfinite(retry_after) else None
202
+ if remaining is None and not wait:
203
+ return
204
+ with limiter._lock:
205
+ limiter._refill()
206
+ if remaining is not None:
207
+ limiter._level = min(limiter._level, float(remaining))
208
+ if wait is not None and wait > 0:
209
+ limiter._level = min(limiter._level, -wait * limiter._rate)
210
+
211
+
212
+ # ------------------------------------------------------------------- stream events
213
+
214
+
215
+ @dataclasses.dataclass(frozen=True)
216
+ class StreamedToolCall:
217
+ """A tool call assembled from stream events.
218
+
219
+ Attributes:
220
+ id: The provider's call id (``call_...`` / ``toolu_...``), when sent.
221
+ name: The tool name, when sent.
222
+ arguments: The raw JSON argument string as streamed (possibly incomplete for a
223
+ pending call).
224
+ index: Its position in the response.
225
+ """
226
+
227
+ id: str | None
228
+ name: str | None
229
+ arguments: str
230
+ index: int
231
+
232
+ @property
233
+ def input(self) -> dict[str, Any]:
234
+ """Parsed arguments, or ``{}`` when they are not (yet) a JSON object."""
235
+ try:
236
+ parsed = json.loads(self.arguments) if self.arguments else {}
237
+ except ValueError:
238
+ return {}
239
+ return parsed if isinstance(parsed, dict) else {}
240
+
241
+
242
+ class StreamInterrupted(PythonWrapError):
243
+ """A stream failed after it had produced output; it is not replayed.
244
+
245
+ Reopening the request would send the caller the same text twice, or ask the model
246
+ for a tool call that may already be executing. The caller decides: show the partial
247
+ text, run the completed tool calls, or start a new turn.
248
+
249
+ Not a transient error: `llm_transient` returns False for it, so an outer
250
+ `llm_retry` does not replay the request either. The original error is
251
+ ``__cause__``.
252
+
253
+ Attributes:
254
+ text: The text streamed before the failure.
255
+ tool_calls: Tool calls whose arguments were complete before the failure.
256
+ pending: Tool calls that had started but not finished (never safe to run).
257
+ attempts: How many times the stream was opened.
258
+ usage: Token usage reported before the failure, if any.
259
+ """
260
+
261
+ def __init__(
262
+ self,
263
+ message: str,
264
+ *,
265
+ text: str,
266
+ tool_calls: tuple[StreamedToolCall, ...],
267
+ pending: tuple[StreamedToolCall, ...],
268
+ attempts: int,
269
+ usage: Usage | None,
270
+ ) -> None:
271
+ super().__init__(message)
272
+ self.text = text
273
+ self.tool_calls = tool_calls
274
+ self.pending = pending
275
+ self.attempts = attempts
276
+ self.usage = usage
277
+
278
+
279
+ # Event types that carry no output: a failure after them is safe to reopen.
280
+ _PRELUDE_TYPES = frozenset(
281
+ {
282
+ "message_start",
283
+ "ping",
284
+ "response.created",
285
+ "response.in_progress",
286
+ "response.queued",
287
+ }
288
+ )
289
+ # Helper events the SDKs synthesise next to the raw delta they repeat.
290
+ _DERIVED_TYPES = frozenset({"text", "input_json", "citation", "thinking", "signature"})
291
+ _USAGE_KEYS = (
292
+ "input_tokens",
293
+ "output_tokens",
294
+ "prompt_tokens",
295
+ "completion_tokens",
296
+ "cache_creation_input_tokens",
297
+ "cache_read_input_tokens",
298
+ )
299
+
300
+
301
+ def _usage_fields(raw: Any) -> dict[str, int]:
302
+ """The token counts of a usage object or mapping, including cached-token details."""
303
+ found: dict[str, int] = {}
304
+ if raw is None:
305
+ return found
306
+ for key in _USAGE_KEYS:
307
+ value = _int(_field(raw, key))
308
+ if value is not None:
309
+ found[key] = max(value, 0)
310
+ for details in ("prompt_tokens_details", "input_tokens_details"):
311
+ cached = _int(_field(_field(raw, details), "cached_tokens"))
312
+ if cached is not None:
313
+ found["cached_tokens"] = max(cached, 0)
314
+ cached = _int(_field(raw, "cached_tokens"))
315
+ if cached is not None:
316
+ found["cached_tokens"] = max(cached, 0)
317
+ return found
318
+
319
+
320
+ @dataclasses.dataclass
321
+ class _Partial:
322
+ id: str | None
323
+ name: str | None
324
+ arguments: str
325
+ index: int
326
+ fallback: str = ""
327
+
328
+ def done(self) -> StreamedToolCall:
329
+ return StreamedToolCall(self.id, self.name, self.arguments or self.fallback, self.index)
330
+
331
+
332
+ class _Tracker:
333
+ """Reads stream events of every supported shape; one per opened stream."""
334
+
335
+ def __init__(self) -> None:
336
+ self.committed = False
337
+ self.text_parts: list[str] = []
338
+ self.open: dict[Any, _Partial] = {}
339
+ self.completed: list[StreamedToolCall] = []
340
+ self.usage: dict[str, int] = {}
341
+ self.model: str | None = None
342
+
343
+ # -- helpers ---------------------------------------------------------------
344
+ def _start(self, key: Any, call_id: Any, name: Any, arguments: Any, index: int) -> None:
345
+ self.open[key] = _Partial(
346
+ call_id if isinstance(call_id, str) else None,
347
+ name if isinstance(name, str) else None,
348
+ arguments if isinstance(arguments, str) else "",
349
+ index,
350
+ )
351
+
352
+ def _finish(self, key: Any) -> None:
353
+ partial = self.open.pop(key, None)
354
+ if partial is not None:
355
+ self.completed.append(partial.done())
356
+
357
+ def finish_all(self) -> None:
358
+ for key in list(self.open):
359
+ self._finish(key)
360
+
361
+ def _model(self, source: Any) -> None:
362
+ model = _field(source, "model")
363
+ if isinstance(model, str) and model:
364
+ self.model = model
365
+
366
+ # -- feeding ---------------------------------------------------------------
367
+ def feed(self, event: Any) -> str:
368
+ """Account for one event; return the text it adds."""
369
+ if isinstance(event, str):
370
+ self.committed = True
371
+ self.text_parts.append(event)
372
+ return event
373
+ if _field(event, "usage_metadata") is not None or _field(event, "type") == "AIMessageChunk":
374
+ return self._langchain(event)
375
+ kind = _field(event, "type")
376
+ if isinstance(kind, str):
377
+ return self._typed(kind, event)
378
+ if _field(event, "choices") is not None or _field(event, "usage") is not None:
379
+ return self._chat(event)
380
+ self.committed = True
381
+ return ""
382
+
383
+ def _typed(self, kind: str, event: Any) -> str:
384
+ if kind not in _PRELUDE_TYPES:
385
+ self.committed = True
386
+ if kind in _DERIVED_TYPES:
387
+ return ""
388
+ if kind == "message_start":
389
+ message = _field(event, "message")
390
+ self._model(message)
391
+ self.usage.update(_usage_fields(_field(message, "usage")))
392
+ elif kind == "content_block_start":
393
+ block = _field(event, "content_block")
394
+ index = _int(_field(event, "index")) or 0
395
+ block_type = _field(block, "type")
396
+ if isinstance(block_type, str) and block_type.endswith("tool_use"):
397
+ self._start(index, _field(block, "id"), _field(block, "name"), "", index)
398
+ given = _field(block, "input")
399
+ if isinstance(given, Mapping) and given:
400
+ self.open[index].fallback = json.dumps(dict(given))
401
+ elif block_type == "text":
402
+ text = _field(block, "text")
403
+ if isinstance(text, str) and text:
404
+ self.text_parts.append(text)
405
+ return text
406
+ elif kind == "content_block_delta":
407
+ delta = _field(event, "delta")
408
+ delta_type = _field(delta, "type")
409
+ index = _int(_field(event, "index")) or 0
410
+ if delta_type == "text_delta":
411
+ text = _field(delta, "text")
412
+ if isinstance(text, str):
413
+ self.text_parts.append(text)
414
+ return text
415
+ elif delta_type == "input_json_delta" and index in self.open:
416
+ piece = _field(delta, "partial_json")
417
+ if isinstance(piece, str):
418
+ self.open[index].arguments += piece
419
+ elif kind == "content_block_stop":
420
+ self._finish(_int(_field(event, "index")) or 0)
421
+ elif kind == "message_delta":
422
+ self.usage.update(_usage_fields(_field(event, "usage")))
423
+ elif kind == "response.output_text.delta":
424
+ text = _field(event, "delta")
425
+ if isinstance(text, str):
426
+ self.text_parts.append(text)
427
+ return text
428
+ elif kind == "response.output_item.added":
429
+ item = _field(event, "item")
430
+ if _field(item, "type") == "function_call":
431
+ index = _int(_field(event, "output_index")) or 0
432
+ call_id = _field(item, "call_id") or _field(item, "id")
433
+ self._start(index, call_id, _field(item, "name"), _field(item, "arguments"), index)
434
+ elif kind == "response.function_call_arguments.delta":
435
+ index = _int(_field(event, "output_index")) or 0
436
+ piece = _field(event, "delta")
437
+ if index in self.open and isinstance(piece, str):
438
+ self.open[index].arguments += piece
439
+ elif kind == "response.function_call_arguments.done":
440
+ index = _int(_field(event, "output_index")) or 0
441
+ arguments = _field(event, "arguments")
442
+ if index in self.open and isinstance(arguments, str):
443
+ self.open[index].arguments = arguments
444
+ elif kind == "response.output_item.done":
445
+ item = _field(event, "item")
446
+ index = _int(_field(event, "output_index")) or 0
447
+ if _field(item, "type") == "function_call":
448
+ if index not in self.open:
449
+ call_id = _field(item, "call_id") or _field(item, "id")
450
+ self._start(index, call_id, _field(item, "name"), "", index)
451
+ arguments = _field(item, "arguments")
452
+ if isinstance(arguments, str) and arguments:
453
+ self.open[index].arguments = arguments
454
+ self._finish(index)
455
+ elif kind in ("response.completed", "response.incomplete"):
456
+ response = _field(event, "response")
457
+ self._model(response)
458
+ self.usage.update(_usage_fields(_field(response, "usage")))
459
+ return ""
460
+
461
+ def _chat(self, chunk: Any) -> str:
462
+ self._model(chunk)
463
+ usage = _field(chunk, "usage")
464
+ if usage is not None:
465
+ self.usage.update(_usage_fields(usage))
466
+ added: list[str] = []
467
+ for choice in _field(chunk, "choices") or ():
468
+ delta = _field(choice, "delta")
469
+ content = _field(delta, "content")
470
+ if isinstance(content, str) and content:
471
+ self.committed = True
472
+ self.text_parts.append(content)
473
+ added.append(content)
474
+ for call in _field(delta, "tool_calls") or ():
475
+ self.committed = True
476
+ index = _int(_field(call, "index")) or 0
477
+ function = _field(call, "function")
478
+ if index not in self.open:
479
+ for earlier in [key for key in self.open if key != index]:
480
+ self._finish(earlier) # OpenAI streams parallel calls one by one
481
+ self._start(
482
+ index,
483
+ _field(call, "id"),
484
+ _field(function, "name"),
485
+ _field(function, "arguments"),
486
+ index,
487
+ )
488
+ else:
489
+ piece = _field(function, "arguments")
490
+ if isinstance(piece, str):
491
+ self.open[index].arguments += piece
492
+ if _field(choice, "finish_reason") is not None:
493
+ self.finish_all()
494
+ return "".join(added)
495
+
496
+ def _langchain(self, chunk: Any) -> str:
497
+ """A LangChain ``AIMessageChunk``: text in ``content``, usage on the last chunk."""
498
+ usage = _field(chunk, "usage_metadata")
499
+ if usage is not None:
500
+ self.usage.update(_usage_fields(usage))
501
+ meta = _field(chunk, "response_metadata")
502
+ name = _field(meta, "model_name") or _field(meta, "model")
503
+ if isinstance(name, str) and name:
504
+ self.model = name
505
+ content = _field(chunk, "content")
506
+ if _field(chunk, "tool_call_chunks"):
507
+ self.committed = True
508
+ if isinstance(content, str) and content:
509
+ self.committed = True
510
+ self.text_parts.append(content)
511
+ return content
512
+ return ""
513
+
514
+ # -- results ---------------------------------------------------------------
515
+ @property
516
+ def text(self) -> str:
517
+ return "".join(self.text_parts)
518
+
519
+ def usage_object(self) -> Usage | None:
520
+ if not self.usage:
521
+ return None
522
+ return read_usage({"usage": dict(self.usage), "model": self.model})
523
+
524
+
525
+ # ------------------------------------------------------------------- resume_safe
526
+
527
+ #: Transport errors raised while a stream body is read (httpx and look-alikes).
528
+ _STREAM_ERROR_NAMES = frozenset(
529
+ {
530
+ "TransportError",
531
+ "NetworkError",
532
+ "ReadError",
533
+ "ReadTimeout",
534
+ "RemoteProtocolError",
535
+ "IncompleteRead",
536
+ "ChunkedEncodingError",
537
+ }
538
+ )
539
+
540
+
541
+ def _guard_sync(source: Any, limits: Mapping[str, float | None], name: str) -> Iterable[Any]:
542
+ """`stream_timeout` forced onto the sync protocol (SDK streams offer both)."""
543
+ from python_wrap.llm import _Limits, _SyncStream
544
+
545
+ return _SyncStream(source, _Limits(**limits), None, name)
546
+
547
+
548
+ def _guard_async(source: Any, limits: Mapping[str, float | None], name: str) -> AsyncIterable[Any]:
549
+ from python_wrap.llm import _AsyncStream, _Limits
550
+
551
+ return _AsyncStream(source, _Limits(**limits), None, name)
552
+
553
+
554
+ def stream_transient(exc: BaseException) -> bool:
555
+ """`llm_transient`, plus the ways a stream fails after its HTTP 200.
556
+
557
+ Also accepts transport errors raised while reading the body (``ReadError``,
558
+ ``RemoteProtocolError``... by class name) and error events sent inside the stream
559
+ whose body is typed ``overloaded_error`` / ``rate_limit_error`` / ``api_error``
560
+ (the SDKs raise those with the stream's 200 status).
561
+ """
562
+ from python_wrap.llm import _body_codes, _is_refusal
563
+
564
+ if llm_transient(exc):
565
+ return True
566
+ if isinstance(exc, StreamInterrupted) or _is_refusal(exc):
567
+ return False
568
+ if any(klass.__name__ in _STREAM_ERROR_NAMES for klass in type(exc).__mro__):
569
+ return True
570
+ return bool(_body_codes(exc) & {"overloaded_error", "rate_limit_error", "api_error"})
571
+
572
+
573
+ _Finish = Callable[["ResumableStream[Any]", "BaseException | None"], Any]
574
+
575
+
576
+ class _Text:
577
+ """``stream.text_stream``: only the text pieces, sync or async."""
578
+
579
+ def __init__(self, owner: ResumableStream[Any]) -> None:
580
+ self._owner = owner
581
+
582
+ def __iter__(self) -> Iterator[str]:
583
+ for _event in self._owner:
584
+ piece = self._owner._last_text
585
+ if piece:
586
+ yield piece
587
+
588
+ async def __aiter__(self) -> AsyncIterator[str]:
589
+ async for _event in self._owner:
590
+ piece = self._owner._last_text
591
+ if piece:
592
+ yield piece
593
+
594
+
595
+ class ResumableStream(Generic[T]):
596
+ """A streamed LLM response that reopens itself only while that is safe.
597
+
598
+ Build it with `resume_safe`. Iterate it with ``for`` (sync streams) or ``async for``
599
+ (async streams); it yields the provider's own events unchanged. Events that carry
600
+ no output yet (``message_start``, ``response.created``, a role-only chat chunk) are
601
+ held back, so when the stream fails before any output it is closed and reopened
602
+ and the caller never sees a duplicate. Once output has been yielded (a text delta,
603
+ a content block, a tool-call delta) a failure raises `StreamInterrupted` with what
604
+ was received.
605
+
606
+ Attributes:
607
+ attempts: How many times the stream was opened.
608
+ name: Used in events and errors.
609
+ """
610
+
611
+ def __init__(
612
+ self,
613
+ factory: Callable[[], Any],
614
+ *,
615
+ max_attempts: int = 3,
616
+ retry_if: Callable[[BaseException], bool] | None = None,
617
+ delay: float = 0.5,
618
+ max_delay: float = 8.0,
619
+ first_token: float | None = None,
620
+ chunk_gap: float | None = None,
621
+ total: float | None = None,
622
+ on_finish: _Finish | None = None,
623
+ name: str = "stream",
624
+ ) -> None:
625
+ if isinstance(max_attempts, bool) or not isinstance(max_attempts, int):
626
+ raise ValueError(f"max_attempts must be an integer, got {max_attempts!r}")
627
+ if max_attempts < 1:
628
+ raise ValueError(f"max_attempts must be >= 1, got {max_attempts!r}")
629
+ for label, value in (("delay", delay), ("max_delay", max_delay)):
630
+ if not math.isfinite(value) or value < 0:
631
+ raise ValueError(f"{label} must be >= 0, got {value!r}")
632
+ self._factory = factory
633
+ self.max_attempts = max_attempts
634
+ self._retry_if = retry_if if retry_if is not None else stream_transient
635
+ self._delay, self._max_delay = delay, max_delay
636
+ self._limits: dict[str, float | None] | None = None
637
+ if first_token is not None or chunk_gap is not None or total is not None:
638
+ stream_timeout([], first_token=first_token, chunk_gap=chunk_gap, total=total)
639
+ self._limits = {"first_token": first_token, "chunk_gap": chunk_gap, "total": total}
640
+ self._on_finish = on_finish
641
+ self.name = name
642
+ self.attempts = 0
643
+ self._tracker = _Tracker()
644
+ self._committed = False
645
+ self._started = False
646
+ self._finished = False
647
+ self._current: Any = None
648
+ self._wrapped: Any = None
649
+ self._exit: Callable[..., Any] | None = None
650
+ self._last_text = ""
651
+ self._gen: Generator[T, None, None] | None = None
652
+ self._agen: AsyncGenerator[T, None] | None = None
653
+
654
+ # -- what was received -----------------------------------------------------
655
+ @property
656
+ def text(self) -> str:
657
+ """The text received so far."""
658
+ return self._tracker.text
659
+
660
+ @property
661
+ def tool_calls(self) -> tuple[StreamedToolCall, ...]:
662
+ """Tool calls whose arguments are complete."""
663
+ return tuple(self._tracker.completed)
664
+
665
+ @property
666
+ def pending_tool_calls(self) -> tuple[StreamedToolCall, ...]:
667
+ """Tool calls that have started but not finished."""
668
+ return tuple(partial.done() for partial in self._tracker.open.values())
669
+
670
+ @property
671
+ def usage(self) -> Usage | None:
672
+ """Token usage the stream reported (needs the provider to send it)."""
673
+ return self._tracker.usage_object()
674
+
675
+ @property
676
+ def model(self) -> str | None:
677
+ """The model the stream reported, if any."""
678
+ return self._tracker.model
679
+
680
+ @property
681
+ def usage_fields(self) -> Mapping[str, int]:
682
+ """Raw usage counts, including cache reads and writes when reported."""
683
+ return dict(self._tracker.usage)
684
+
685
+ @property
686
+ def committed(self) -> bool:
687
+ """True once output has been handed to the caller (reopening is then unsafe)."""
688
+ return self._committed
689
+
690
+ @property
691
+ def text_stream(self) -> _Text:
692
+ """Iterate only the text pieces (``for`` or ``async for``)."""
693
+ return _Text(self)
694
+
695
+ def __getattr__(self, name: str) -> Any:
696
+ if name.startswith("_"):
697
+ raise AttributeError(name)
698
+ current = self.__dict__.get("_current")
699
+ if current is None:
700
+ raise AttributeError(f"{type(self).__name__} has no attribute {name!r} (yet)")
701
+ return getattr(current, name)
702
+
703
+ # -- shared steps ----------------------------------------------------------
704
+ def _wait(self, exc: BaseException) -> float:
705
+ hint = llm_retry_after(exc)
706
+ if hint is not None:
707
+ return min(hint, self._max_delay)
708
+ backoff: float = self._delay * 2.0 ** (self.attempts - 1)
709
+ return min(backoff, self._max_delay)
710
+
711
+ def _interrupted(self, exc: BaseException) -> StreamInterrupted:
712
+ tracker = self._tracker
713
+ _core.emit(
714
+ "llm.stream_interrupted",
715
+ self.name,
716
+ chars=len(tracker.text),
717
+ tool_calls=len(tracker.completed),
718
+ exception=exc,
719
+ )
720
+ return StreamInterrupted(
721
+ f"stream {self.name!r} failed after output started "
722
+ f"({len(tracker.text)} chars, {len(tracker.completed)} complete tool calls, "
723
+ f"{len(tracker.open)} pending); not replayed: {type(exc).__name__}",
724
+ text=tracker.text,
725
+ tool_calls=tuple(tracker.completed),
726
+ pending=self.pending_tool_calls,
727
+ attempts=self.attempts,
728
+ usage=tracker.usage_object(),
729
+ )
730
+
731
+ def _gives_up(self, exc: BaseException) -> bool:
732
+ return self.attempts >= self.max_attempts or not self._retry_if(exc)
733
+
734
+ def _resumed(self, exc: BaseException, wait: float) -> None:
735
+ _core.emit(
736
+ "llm.stream_resumed", self.name, attempt=self.attempts, exception=exc, delay=wait
737
+ )
738
+
739
+ def _finish(self, error: BaseException | None) -> None:
740
+ if self._finished:
741
+ return
742
+ self._finished = True
743
+ if error is None:
744
+ self._tracker.finish_all()
745
+ if self._on_finish is not None:
746
+ try:
747
+ self._on_finish(self, error)
748
+ except Exception:
749
+ _core.get_logger().exception("python_wrap resume_safe finish hook failed")
750
+
751
+ def _start(self) -> None:
752
+ if self._started:
753
+ raise RuntimeError(f"stream {self.name!r} can be iterated only once")
754
+ self._started = True
755
+
756
+ def _accept(
757
+ self, tracker: _Tracker, event: Any, buffer: list[tuple[Any, str]]
758
+ ) -> list[tuple[Any, str]]:
759
+ """Feed ``event``; return ``(event, text)`` pairs to hand out now (none while held)."""
760
+ item = (event, tracker.feed(event))
761
+ if self._committed:
762
+ return [item]
763
+ if tracker.committed:
764
+ self._committed = True
765
+ self._tracker = tracker
766
+ released = [*buffer, item]
767
+ buffer.clear()
768
+ return released
769
+ buffer.append(item)
770
+ return []
771
+
772
+ # -- sync ------------------------------------------------------------------
773
+ def _open(self) -> Iterable[Any]:
774
+ made = self._factory()
775
+ if inspect.isawaitable(made):
776
+ close = getattr(made, "close", None)
777
+ if callable(close):
778
+ close()
779
+ raise TypeError(f"stream {self.name!r} is async: iterate it with `async for`")
780
+ self._exit = None
781
+ if not isinstance(made, Iterable) and hasattr(made, "__enter__"):
782
+ self._exit = made.__exit__
783
+ made = made.__enter__()
784
+ self._current = made
785
+ self._wrapped = _guard_sync(made, self._limits, self.name) if self._limits else made
786
+ return cast("Iterable[Any]", self._wrapped)
787
+
788
+ def _close(self) -> None:
789
+ wrapped, current, leave = self._wrapped, self._current, self._exit
790
+ self._wrapped = self._exit = None
791
+ if leave is not None:
792
+ with contextlib.suppress(Exception):
793
+ leave(None, None, None)
794
+ for target in (wrapped, current):
795
+ if target is None or (leave is not None and target is current):
796
+ continue
797
+ close = getattr(target, "close", None)
798
+ if callable(close):
799
+ with contextlib.suppress(Exception):
800
+ result = close()
801
+ if inspect.isawaitable(result):
802
+ cast(Any, result).close()
803
+
804
+ def __iter__(self) -> Iterator[T]:
805
+ self._start()
806
+ self._gen = self._run()
807
+ return self._gen
808
+
809
+ def _hand_out(self, items: list[tuple[Any, str]]) -> Iterator[T]:
810
+ for event, text in items:
811
+ self._last_text = text
812
+ yield cast(T, event)
813
+
814
+ def _run(self) -> Generator[T, None, None]:
815
+ error: BaseException | None = None
816
+ try:
817
+ while True:
818
+ self.attempts += 1
819
+ tracker = _Tracker()
820
+ buffer: list[tuple[Any, str]] = []
821
+ try:
822
+ for event in self._open():
823
+ yield from self._hand_out(self._accept(tracker, event, buffer))
824
+ except Exception as exc:
825
+ self._close()
826
+ if self._committed:
827
+ raise self._interrupted(exc) from exc
828
+ if self._gives_up(exc):
829
+ self._tracker = tracker
830
+ raise
831
+ wait = self._wait(exc)
832
+ self._resumed(exc, wait)
833
+ _core.sleep(wait)
834
+ continue
835
+ if not self._committed:
836
+ self._tracker = tracker
837
+ yield from self._hand_out(buffer)
838
+ self._close()
839
+ return
840
+ except BaseException as exc:
841
+ error = exc
842
+ raise
843
+ finally:
844
+ self._close()
845
+ self._finish(error)
846
+
847
+ # -- async -----------------------------------------------------------------
848
+ async def _aopen(self) -> AsyncIterable[Any]:
849
+ made = self._factory()
850
+ if inspect.isawaitable(made):
851
+ made = await made
852
+ self._exit = None
853
+ if not isinstance(made, AsyncIterable) and hasattr(made, "__aenter__"):
854
+ self._exit = made.__aexit__
855
+ made = await made.__aenter__()
856
+ if not isinstance(made, AsyncIterable):
857
+ raise TypeError(f"stream {self.name!r} is sync: iterate it with `for`")
858
+ self._current = made
859
+ self._wrapped = _guard_async(made, self._limits, self.name) if self._limits else made
860
+ return cast("AsyncIterable[Any]", self._wrapped)
861
+
862
+ async def _aclose(self) -> None:
863
+ wrapped, current, leave = self._wrapped, self._current, self._exit
864
+ self._wrapped = self._exit = None
865
+ if leave is not None:
866
+ with contextlib.suppress(Exception):
867
+ await _maybe_await(leave(None, None, None))
868
+ for target in (wrapped, current):
869
+ if target is None or (leave is not None and target is current):
870
+ continue
871
+ for method in ("aclose", "close"):
872
+ close = getattr(target, method, None)
873
+ if callable(close):
874
+ with contextlib.suppress(Exception):
875
+ await _maybe_await(close())
876
+ break
877
+
878
+ def __aiter__(self) -> AsyncIterator[T]:
879
+ self._start()
880
+ self._agen = self._arun()
881
+ return self._agen
882
+
883
+ async def _arun(self) -> AsyncGenerator[T, None]:
884
+ error: BaseException | None = None
885
+ try:
886
+ while True:
887
+ self.attempts += 1
888
+ tracker = _Tracker()
889
+ buffer: list[tuple[Any, str]] = []
890
+ try:
891
+ async for event in await self._aopen():
892
+ for item, text in self._accept(tracker, event, buffer):
893
+ self._last_text = text
894
+ yield cast(T, item)
895
+ except Exception as exc:
896
+ await self._aclose()
897
+ if self._committed:
898
+ raise self._interrupted(exc) from exc
899
+ if self._gives_up(exc):
900
+ self._tracker = tracker
901
+ raise
902
+ wait = self._wait(exc)
903
+ self._resumed(exc, wait)
904
+ await _core.async_sleep(wait)
905
+ continue
906
+ if not self._committed:
907
+ self._tracker = tracker
908
+ for item, text in buffer:
909
+ self._last_text = text
910
+ yield cast(T, item)
911
+ await self._aclose()
912
+ return
913
+ except BaseException as exc:
914
+ error = exc
915
+ raise
916
+ finally:
917
+ await self._aclose()
918
+ self._finish(error)
919
+
920
+ # -- context managers ------------------------------------------------------
921
+ def close(self) -> None:
922
+ """Stop reading and close the underlying stream (sync)."""
923
+ gen = self.__dict__.get("_gen")
924
+ if gen is not None:
925
+ gen.close()
926
+ self._close()
927
+ self._finish(None)
928
+
929
+ async def aclose(self) -> None:
930
+ """Stop reading and close the underlying stream (async)."""
931
+ agen = self.__dict__.get("_agen")
932
+ if agen is not None:
933
+ await agen.aclose()
934
+ await self._aclose()
935
+ self._finish(None)
936
+
937
+ def __enter__(self) -> ResumableStream[T]:
938
+ return self
939
+
940
+ def __exit__(self, *exc: object) -> None:
941
+ self.close()
942
+
943
+ async def __aenter__(self) -> ResumableStream[T]:
944
+ return self
945
+
946
+ async def __aexit__(self, *exc: object) -> None:
947
+ await self.aclose()
948
+
949
+ def __repr__(self) -> str:
950
+ return (
951
+ f"ResumableStream({self.name!r}, attempts={self.attempts}, committed={self._committed})"
952
+ )
953
+
954
+
955
+ def resume_safe(
956
+ source: Callable[..., Any] | None = None,
957
+ /,
958
+ *,
959
+ max_attempts: int = 3,
960
+ retry_if: Callable[[BaseException], bool] | None = None,
961
+ delay: float = 0.5,
962
+ max_delay: float = 8.0,
963
+ first_token: float | None = None,
964
+ chunk_gap: float | None = None,
965
+ total: float | None = None,
966
+ name: str | None = None,
967
+ ) -> Any:
968
+ """Reopen a failed LLM stream only when no output has been handed out yet.
969
+
970
+ Retrying a stream is not like retrying a call. A failure before the first output
971
+ (connection reset, 529 on open, a stall before the first token) is safe to retry:
972
+ the stream is closed, the wait doubles from ``delay`` (or follows ``Retry-After``)
973
+ and it is opened again, invisibly to the caller. A failure after text or a tool
974
+ call was yielded is not: replaying would duplicate the text, or start a tool call
975
+ the caller may already be acting on. Then `StreamInterrupted` is raised, carrying
976
+ the partial text, the tool calls that completed and the ones still pending.
977
+
978
+ Events are read by shape: OpenAI chat-completion chunks (``choices[].delta``),
979
+ OpenAI Responses events (``response.output_text.delta``,
980
+ ``response.function_call_arguments.delta``, ``response.output_item.done``...),
981
+ Anthropic message events (``content_block_start``, ``content_block_delta``,
982
+ ``content_block_stop``...), python-wrap's `FakeStream` chunks and plain strings.
983
+
984
+ Two forms:
985
+
986
+ - ``resume_safe(lambda: client.chat.completions.create(..., stream=True))``: a
987
+ zero-argument factory that opens the stream (sync, async, or returning a context
988
+ manager such as Anthropic's ``messages.stream(...)``).
989
+ - ``@resume_safe(...)`` on a function returning a stream; each call returns a
990
+ `ResumableStream` that calls the function again to reopen.
991
+
992
+ Args:
993
+ source: The factory, or None for the decorator form.
994
+ max_attempts: Total opens, including the first.
995
+ retry_if: Which errors before output are worth reopening for;
996
+ `stream_transient` by default (`llm_transient`, which accepts
997
+ `StreamTimeout`, plus transport errors and in-stream overloaded errors).
998
+ delay: First wait between opens, doubled each time.
999
+ max_delay: Longest wait, also the cap on ``Retry-After`` hints.
1000
+ first_token: Stall limit for the first event of each open (`stream_timeout`).
1001
+ chunk_gap: Stall limit between events.
1002
+ total: Limit for one open, start to end.
1003
+ name: Used in events and errors.
1004
+
1005
+ Returns:
1006
+ A `ResumableStream`, or a decorator.
1007
+
1008
+ Example:
1009
+ ```python
1010
+ from python_wrap.adapters import StreamInterrupted, resume_safe
1011
+ from python_wrap.llm_testing import FakeStream
1012
+ from python_wrap.testing import fake_clock
1013
+
1014
+
1015
+ class Reset(ConnectionError):
1016
+ pass
1017
+
1018
+
1019
+ opened = []
1020
+
1021
+
1022
+ def open_stream() -> FakeStream:
1023
+ opened.append(1)
1024
+ if len(opened) == 1: # the first open fails before any output: reopened
1025
+ return FakeStream(["Hel", "lo"], error=Reset, error_after=0)
1026
+ return FakeStream(["Hel", "lo"], error=Reset, error_after=1) # fails mid-way
1027
+
1028
+ stream = resume_safe(open_stream)
1029
+ received = []
1030
+ with fake_clock():
1031
+ try:
1032
+ for chunk in stream:
1033
+ received.append(chunk.text)
1034
+ except StreamInterrupted as exc:
1035
+ assert exc.text == "Hel" and exc.attempts == 2
1036
+ assert received == ["Hel"] and len(opened) == 2
1037
+ ```
1038
+ """
1039
+ options: dict[str, Any] = {
1040
+ "max_attempts": max_attempts,
1041
+ "retry_if": retry_if,
1042
+ "delay": delay,
1043
+ "max_delay": max_delay,
1044
+ "first_token": first_token,
1045
+ "chunk_gap": chunk_gap,
1046
+ "total": total,
1047
+ }
1048
+ if source is not None:
1049
+ label = name or _core.qualname(source)
1050
+ return ResumableStream(source, name=label, **options)
1051
+ ResumableStream(lambda: (), **options) # validate now, not on the first call
1052
+ limited = first_token is not None or chunk_gap is not None or total is not None
1053
+ settings = {
1054
+ "llm": "resume_safe",
1055
+ "max_attempts": max_attempts,
1056
+ "first_token": first_token,
1057
+ "chunk_gap": chunk_gap,
1058
+ "total": total,
1059
+ "seconds": total,
1060
+ }
1061
+
1062
+ def decorate(func: Callable[..., Any]) -> Callable[..., Any]:
1063
+ label = name or _core.qualname(func)
1064
+
1065
+ @functools.wraps(func)
1066
+ def wrapper(*args: Any, **kwargs: Any) -> ResumableStream[Any]:
1067
+ return ResumableStream(lambda: func(*args, **kwargs), name=label, **options)
1068
+
1069
+ setattr(wrapper, _LAYER_ATTR, ("timeout" if limited else "guard", settings))
1070
+ return wrapper
1071
+
1072
+ setattr(decorate, _LAYER_ATTR, ("timeout" if limited else "guard", settings))
1073
+ return decorate
1074
+
1075
+
1076
+ # ------------------------------------------------------------------- CacheGuard
1077
+
1078
+
1079
+ class PromptCacheWarning(UserWarning):
1080
+ """Prompt caching looks ineffective (`CacheGuard`)."""
1081
+
1082
+
1083
+ @dataclasses.dataclass(frozen=True)
1084
+ class CacheStats:
1085
+ """What a `CacheGuard` has seen.
1086
+
1087
+ Attributes:
1088
+ calls: Responses observed.
1089
+ eligible_calls: Those with a prompt long enough to be cached.
1090
+ prompt_tokens: Prompt tokens of the eligible calls (cached or not).
1091
+ cache_read_tokens: Tokens served from the cache.
1092
+ cache_write_tokens: Tokens written to the cache (Anthropic ``cache_creation``).
1093
+ """
1094
+
1095
+ calls: int = 0
1096
+ eligible_calls: int = 0
1097
+ prompt_tokens: int = 0
1098
+ cache_read_tokens: int = 0
1099
+ cache_write_tokens: int = 0
1100
+
1101
+ @property
1102
+ def hit_rate(self) -> float:
1103
+ """Share of eligible prompt tokens read from the cache (0.0 to 1.0)."""
1104
+ return self.cache_read_tokens / self.prompt_tokens if self.prompt_tokens else 0.0
1105
+
1106
+
1107
+ _VOLATILE = (
1108
+ ("uuid", re.compile(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", re.I)),
1109
+ ("timestamp", re.compile(r"\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}")),
1110
+ ("time of day", re.compile(r"\b\d{1,2}:\d{2}:\d{2}\b")),
1111
+ ("unix timestamp", re.compile(r"\b1\d{9}(?:\d{3})?\b")),
1112
+ ("random id", re.compile(r"\b[0-9a-f]{24,}\b", re.I)),
1113
+ )
1114
+
1115
+
1116
+ def _texts(value: Any, depth: int = 0) -> Iterator[str]:
1117
+ if depth > 6:
1118
+ return
1119
+ if isinstance(value, str):
1120
+ yield value
1121
+ elif isinstance(value, Mapping):
1122
+ for key in ("text", "content", "description", "name", "instructions"):
1123
+ if key in value:
1124
+ yield from _texts(value[key], depth + 1)
1125
+ if "input_schema" in value or "parameters" in value or "function" in value:
1126
+ for key in ("input_schema", "parameters", "function"):
1127
+ if key in value:
1128
+ yield json.dumps(value[key], sort_keys=True, default=str)
1129
+ elif isinstance(value, (list, tuple)):
1130
+ for item in value:
1131
+ yield from _texts(item, depth + 1)
1132
+ else:
1133
+ text = getattr(value, "text", None)
1134
+ if isinstance(text, str):
1135
+ yield text
1136
+
1137
+
1138
+ def prompt_prefix(request: Mapping[str, Any]) -> str:
1139
+ """The stable part of a request a prompt cache keys on: tools, system, instructions.
1140
+
1141
+ Covers Anthropic ``system=`` (string or blocks) and ``tools=``, OpenAI ``tools=``,
1142
+ ``instructions=`` and the leading ``system``/``developer`` messages.
1143
+ """
1144
+ parts: list[str] = []
1145
+ parts += _texts(request.get("tools"))
1146
+ parts += _texts(request.get("system"))
1147
+ parts += _texts(request.get("instructions"))
1148
+ for message in request.get("messages") or ():
1149
+ role = _field(message, "role")
1150
+ if role not in ("system", "developer"):
1151
+ break
1152
+ parts += _texts(_field(message, "content"))
1153
+ leading = request.get("input")
1154
+ if isinstance(leading, (list, tuple)):
1155
+ for message in leading:
1156
+ if _field(message, "role") not in ("system", "developer"):
1157
+ break
1158
+ parts += _texts(_field(message, "content"))
1159
+ return "\n".join(parts)
1160
+
1161
+
1162
+ def volatile_kinds(text: str) -> tuple[str, ...]:
1163
+ """Kinds of per-request values (``"timestamp"``, ``"uuid"``...) found in ``text``."""
1164
+ return tuple(kind for kind, pattern in _VOLATILE if pattern.search(text))
1165
+
1166
+
1167
+ def _has_cache_control(value: Any, depth: int = 0) -> bool:
1168
+ if depth > 6:
1169
+ return False
1170
+ if isinstance(value, Mapping):
1171
+ if "cache_control" in value:
1172
+ return True
1173
+ return any(_has_cache_control(item, depth + 1) for item in value.values())
1174
+ if isinstance(value, (list, tuple)):
1175
+ return any(_has_cache_control(item, depth + 1) for item in value)
1176
+ return False
1177
+
1178
+
1179
+ def _cache_numbers(response: Any) -> tuple[int, int, int, bool] | None:
1180
+ """``(prompt_tokens, cache_read, cache_write, anthropic_style)`` from a response."""
1181
+ raw = _field(response, "usage")
1182
+ if raw is None:
1183
+ raw = response
1184
+ fields = _usage_fields(raw)
1185
+ anthropic = any(
1186
+ key in fields or _has_attr(raw, key)
1187
+ for key in ("cache_creation_input_tokens", "cache_read_input_tokens")
1188
+ )
1189
+ if anthropic:
1190
+ read = fields.get("cache_read_input_tokens", 0)
1191
+ write = fields.get("cache_creation_input_tokens", 0)
1192
+ return fields.get("input_tokens", 0) + read + write, read, write, True
1193
+ prompt = fields.get("prompt_tokens", fields.get("input_tokens"))
1194
+ if prompt is None:
1195
+ return None
1196
+ return prompt, min(fields.get("cached_tokens", 0), prompt), 0, False
1197
+
1198
+
1199
+ def _has_attr(raw: Any, name: str) -> bool:
1200
+ if isinstance(raw, Mapping):
1201
+ return name in raw
1202
+ return raw is not None and hasattr(raw, name)
1203
+
1204
+
1205
+ class CacheGuard:
1206
+ """Watch prompt-cache effectiveness and flag prompts that defeat the cache.
1207
+
1208
+ Prompt caching (Anthropic ``cache_control`` breakpoints, OpenAI's automatic prefix
1209
+ cache) only pays when the prefix (tools, system prompt, leading messages) is byte
1210
+ for byte the same on every call. A timestamp or a request id in the system prompt
1211
+ silently turns every call into a cache miss at full price.
1212
+
1213
+ `observe` each response (the guarded clients do it for you) with its request. The
1214
+ guard adds up cache reads and writes from the usage
1215
+ (``cache_read_input_tokens`` / ``cache_creation_input_tokens`` or
1216
+ ``prompt_tokens_details.cached_tokens``) and, once ``min_calls`` calls with a
1217
+ cacheable prompt have a hit rate at or below ``min_hit_rate``, warns once
1218
+ (`PromptCacheWarning` and an ``llm.prompt_cache_cold`` event) with the likely
1219
+ reasons. A prefix containing a timestamp, UUID or long random id is reported once
1220
+ as soon as it is seen (``llm.prompt_cache_volatile``). Only hashes and the kind of
1221
+ value are kept, never prompt text.
1222
+
1223
+ Args:
1224
+ min_calls: Eligible calls before the hit rate is judged.
1225
+ min_hit_rate: Hit rate at or below which the cache counts as cold.
1226
+ min_prompt_tokens: Prompts shorter than this are not cacheable (1024 tokens on
1227
+ most models) and are not counted.
1228
+ name: Used in warnings and events.
1229
+ warn: Also call `warnings.warn` (events are always emitted).
1230
+
1231
+ Example:
1232
+ ```python
1233
+ import warnings
1234
+
1235
+ from python_wrap.adapters import CacheGuard, PromptCacheWarning
1236
+
1237
+ guard = CacheGuard(min_calls=3, min_prompt_tokens=100)
1238
+ request = {"system": "You are a helpful assistant.", "messages": []}
1239
+ usage = {"usage": {"input_tokens": 2000, "output_tokens": 10,
1240
+ "cache_read_input_tokens": 0, "cache_creation_input_tokens": 0}}
1241
+ with warnings.catch_warnings(record=True) as caught:
1242
+ warnings.simplefilter("always")
1243
+ for _ in range(3):
1244
+ guard.observe(usage, request)
1245
+ assert guard.stats().hit_rate == 0.0
1246
+ assert [w.category for w in caught] == [PromptCacheWarning]
1247
+ assert "cache_control" in str(caught[0].message)
1248
+ ```
1249
+ """
1250
+
1251
+ def __init__(
1252
+ self,
1253
+ *,
1254
+ min_calls: int = 5,
1255
+ min_hit_rate: float = 0.05,
1256
+ min_prompt_tokens: int = 1024,
1257
+ name: str = "prompt-cache",
1258
+ warn: bool = True,
1259
+ ) -> None:
1260
+ if isinstance(min_calls, bool) or not isinstance(min_calls, int) or min_calls < 1:
1261
+ raise ValueError(f"min_calls must be an integer >= 1, got {min_calls!r}")
1262
+ if not 0 <= min_hit_rate < 1:
1263
+ raise ValueError(f"min_hit_rate must be in [0, 1), got {min_hit_rate!r}")
1264
+ if min_prompt_tokens < 0:
1265
+ raise ValueError(f"min_prompt_tokens must be >= 0, got {min_prompt_tokens!r}")
1266
+ self.min_calls, self.min_hit_rate = min_calls, min_hit_rate
1267
+ self.min_prompt_tokens, self.name, self.warn = min_prompt_tokens, name, warn
1268
+ self._lock = threading.Lock()
1269
+ self.reset()
1270
+
1271
+ def reset(self) -> None:
1272
+ """Forget everything seen and re-arm the warnings."""
1273
+ with self._lock:
1274
+ self._stats = CacheStats()
1275
+ self._prefixes: set[str] = set()
1276
+ self._with_prefix = 0
1277
+ self._volatile: set[str] = set()
1278
+ self._marked = False
1279
+ self._anthropic = False
1280
+ self._cold_warned = False
1281
+ self._volatile_warned = False
1282
+
1283
+ def stats(self) -> CacheStats:
1284
+ """Totals so far."""
1285
+ with self._lock:
1286
+ return self._stats
1287
+
1288
+ @property
1289
+ def volatile(self) -> tuple[str, ...]:
1290
+ """Kinds of per-request values seen in a prefix so far."""
1291
+ with self._lock:
1292
+ return tuple(sorted(self._volatile))
1293
+
1294
+ def check_prefix(self, request: Mapping[str, Any]) -> tuple[str, ...]:
1295
+ """Kinds of per-request values in the request's cacheable prefix (no recording)."""
1296
+ return volatile_kinds(prompt_prefix(request))
1297
+
1298
+ def _reasons(self) -> tuple[str, ...]:
1299
+ reasons: list[str] = []
1300
+ if self._volatile:
1301
+ kinds = ", ".join(sorted(self._volatile))
1302
+ reasons.append(f"the prompt prefix contains values that change per call ({kinds})")
1303
+ if self._with_prefix >= 2 and len(self._prefixes) == self._with_prefix:
1304
+ reasons.append("the prompt prefix (tools, system prompt) differed on every call")
1305
+ if self._anthropic and not self._marked:
1306
+ reasons.append(
1307
+ "no cache_control breakpoint in the requests "
1308
+ "(Anthropic caches only marked prefixes)"
1309
+ )
1310
+ return tuple(reasons)
1311
+
1312
+ def observe(self, response: Any, request: Mapping[str, Any] | None = None) -> CacheStats:
1313
+ """Record one response (and the request that produced it).
1314
+
1315
+ Args:
1316
+ response: A response with ``usage``, a usage object or a usage mapping.
1317
+ request: The request keyword arguments, to inspect the prefix.
1318
+
1319
+ Returns:
1320
+ The updated totals.
1321
+ """
1322
+ numbers = _cache_numbers(response)
1323
+ volatile: tuple[str, ...] = ()
1324
+ prefix_hash: str | None = None
1325
+ marked = False
1326
+ if request is not None:
1327
+ prefix = prompt_prefix(request)
1328
+ if prefix:
1329
+ volatile = volatile_kinds(prefix)
1330
+ prefix_hash = hashlib.sha256(prefix.encode()).hexdigest()
1331
+ marked = _has_cache_control(request) or "cache_control" in request
1332
+ fire_volatile: tuple[str, ...] | None = None
1333
+ fire_cold: tuple[float, int, tuple[str, ...]] | None = None
1334
+ with self._lock:
1335
+ stats = self._stats
1336
+ calls = stats.calls + 1
1337
+ eligible, prompt, read, write = (
1338
+ stats.eligible_calls,
1339
+ stats.prompt_tokens,
1340
+ stats.cache_read_tokens,
1341
+ stats.cache_write_tokens,
1342
+ )
1343
+ if numbers is not None and numbers[0] >= self.min_prompt_tokens:
1344
+ eligible += 1
1345
+ prompt += numbers[0]
1346
+ read += numbers[1]
1347
+ write += numbers[2]
1348
+ self._anthropic = self._anthropic or numbers[3]
1349
+ if prefix_hash is not None:
1350
+ self._prefixes.add(prefix_hash)
1351
+ self._with_prefix += 1
1352
+ self._marked = self._marked or marked
1353
+ self._stats = CacheStats(calls, eligible, prompt, read, write)
1354
+ if volatile and not self._volatile.issuperset(volatile):
1355
+ self._volatile.update(volatile)
1356
+ if not self._volatile_warned:
1357
+ self._volatile_warned = True
1358
+ fire_volatile = volatile
1359
+ stats = self._stats
1360
+ if (
1361
+ not self._cold_warned
1362
+ and stats.eligible_calls >= self.min_calls
1363
+ and stats.hit_rate <= self.min_hit_rate
1364
+ ):
1365
+ self._cold_warned = True
1366
+ fire_cold = (stats.hit_rate, stats.eligible_calls, self._reasons())
1367
+ if fire_volatile is not None:
1368
+ _core.emit("llm.prompt_cache_volatile", self.name, kinds=fire_volatile)
1369
+ self._warn(
1370
+ f"{self.name}: the cached prompt prefix contains {', '.join(fire_volatile)}; "
1371
+ "a value that changes per call makes every call a cache miss. Move it after "
1372
+ "the cached prefix (into the last user message)."
1373
+ )
1374
+ if fire_cold is not None:
1375
+ rate, count, reasons = fire_cold
1376
+ _core.emit(
1377
+ "llm.prompt_cache_cold", self.name, calls=count, hit_rate=rate, reasons=reasons
1378
+ )
1379
+ why = "; ".join(reasons) if reasons else "the prefix may be shorter than the minimum"
1380
+ self._warn(
1381
+ f"{self.name}: prompt-cache hit rate is {rate:.0%} over {count} cacheable "
1382
+ f"calls. Likely: {why}."
1383
+ )
1384
+ return stats
1385
+
1386
+ def _warn(self, message: str) -> None:
1387
+ if self.warn:
1388
+ warnings.warn(message, PromptCacheWarning, stacklevel=4)
1389
+
1390
+ def __repr__(self) -> str:
1391
+ stats = self.stats()
1392
+ return f"CacheGuard({self.name!r}, calls={stats.calls}, hit_rate={stats.hit_rate:.2f})"
1393
+
1394
+
1395
+ # ------------------------------------------------------------------ the proxy
1396
+
1397
+
1398
+ def _is_async_client(client: Any) -> bool:
1399
+ return type(client).__name__.startswith("Async")
1400
+
1401
+
1402
+ class _Endpoint:
1403
+ """One guarded SDK resource (``chat.completions``, ``responses``, ``messages``)."""
1404
+
1405
+ def __init__(self, guard: GuardedClient, path: tuple[str, ...], kind: str) -> None:
1406
+ self._guard = guard
1407
+ self._path = path
1408
+ self._kind = kind
1409
+ self._label = f"{guard.system}.{'.'.join(path)}"
1410
+ create: Any
1411
+ if guard.is_async:
1412
+ self._call = guard._compose(self._label, self._ainvoke)
1413
+
1414
+ async def acreate(*args: Any, **kwargs: Any) -> Any:
1415
+ if kwargs.get("stream"):
1416
+ return await self._astream(args, kwargs)
1417
+ return await self._call(*args, **kwargs)
1418
+
1419
+ create = acreate
1420
+ else:
1421
+ self._call = guard._compose(self._label, self._invoke)
1422
+
1423
+ def screate(*args: Any, **kwargs: Any) -> Any:
1424
+ if kwargs.get("stream"):
1425
+ return self._stream(args, kwargs)
1426
+ return self._call(*args, **kwargs)
1427
+
1428
+ create = screate
1429
+ create.__wrapped__ = self._call # so doctor() sees the layers
1430
+ create.__qualname__ = create.__name__ = f"{self._label}.create"
1431
+ self.create = create
1432
+ if kind == "messages":
1433
+ self.stream = self._stream_manager
1434
+
1435
+ def _target(self, client: Any | None = None) -> Any:
1436
+ target = self._guard.client if client is None else client
1437
+ for part in self._path:
1438
+ target = getattr(target, part)
1439
+ return target
1440
+
1441
+ def __getattr__(self, name: str) -> Any:
1442
+ if name.startswith("_"):
1443
+ raise AttributeError(name)
1444
+ return getattr(self._target(self._guard.raw), name)
1445
+
1446
+ # -- the HTTP call, reading headers when the SDK exposes them ---------------
1447
+ def _raw_target(self) -> tuple[Any, Any]:
1448
+ target = self._target()
1449
+ raw = getattr(target, "with_raw_response", None) if self._guard.read_headers else None
1450
+ return target, raw
1451
+
1452
+ def _send(self, args: tuple[Any, ...], kwargs: Mapping[str, Any]) -> tuple[Any, Any]:
1453
+ target, raw = self._raw_target()
1454
+ if raw is not None:
1455
+ response = raw.create(*args, **kwargs)
1456
+ return response.parse(), _headers_of(response)
1457
+ return target.create(*args, **kwargs), None
1458
+
1459
+ async def _asend(self, args: tuple[Any, ...], kwargs: Mapping[str, Any]) -> tuple[Any, Any]:
1460
+ target, raw = self._raw_target()
1461
+ if raw is not None:
1462
+ response = await _maybe_await(raw.create(*args, **kwargs))
1463
+ return await _maybe_await(response.parse()), _headers_of(response)
1464
+ return await _maybe_await(target.create(*args, **kwargs)), None
1465
+
1466
+ # -- one attempt of a plain call --------------------------------------------
1467
+ def _invoke(self, *args: Any, **kwargs: Any) -> Any:
1468
+ guard = self._guard
1469
+ cost = guard._reserve(args, kwargs, self._label)
1470
+ try:
1471
+ result, headers = self._send(args, kwargs)
1472
+ except BaseException as exc:
1473
+ guard._failed(cost, exc, kwargs)
1474
+ raise
1475
+ guard._settled(cost, result, headers, kwargs)
1476
+ return result
1477
+
1478
+ async def _ainvoke(self, *args: Any, **kwargs: Any) -> Any:
1479
+ guard = self._guard
1480
+ cost = await guard._areserve(args, kwargs, self._label)
1481
+ try:
1482
+ result, headers = await self._asend(args, kwargs)
1483
+ except BaseException as exc:
1484
+ guard._failed(cost, exc, kwargs)
1485
+ raise
1486
+ guard._settled(cost, result, headers, kwargs)
1487
+ return result
1488
+
1489
+ # -- streams: one admission, reopened by ResumableStream ---------------------
1490
+ def _stream_kwargs(self, kwargs: dict[str, Any]) -> dict[str, Any]:
1491
+ kwargs = dict(kwargs)
1492
+ if self._kind == "chat" and "stream_options" not in kwargs:
1493
+ kwargs["stream_options"] = {"include_usage": True}
1494
+ return kwargs
1495
+
1496
+ def _open(self, args: tuple[Any, ...], kwargs: Mapping[str, Any]) -> Any:
1497
+ try:
1498
+ stream, headers = self._send(args, kwargs)
1499
+ except BaseException as exc:
1500
+ self._guard._seed_error(exc, kwargs)
1501
+ raise
1502
+ self._guard._seed(headers, kwargs)
1503
+ return stream
1504
+
1505
+ async def _aopen(self, args: tuple[Any, ...], kwargs: Mapping[str, Any]) -> Any:
1506
+ try:
1507
+ stream, headers = await self._asend(args, kwargs)
1508
+ except BaseException as exc:
1509
+ self._guard._seed_error(exc, kwargs)
1510
+ raise
1511
+ self._guard._seed(headers, kwargs)
1512
+ return stream
1513
+
1514
+ def _stream(self, args: tuple[Any, ...], kwargs: dict[str, Any]) -> ResumableStream[Any]:
1515
+ guard = self._guard
1516
+ kwargs = self._stream_kwargs(kwargs)
1517
+ admission = guard._admit(args, kwargs, self._label)
1518
+ return guard._resumable(self._label, lambda: self._open(args, kwargs), admission, kwargs)
1519
+
1520
+ async def _astream(self, args: tuple[Any, ...], kwargs: dict[str, Any]) -> ResumableStream[Any]:
1521
+ guard = self._guard
1522
+ kwargs = self._stream_kwargs(kwargs)
1523
+ admission = await guard._aadmit(args, kwargs, self._label)
1524
+ return guard._resumable(self._label, lambda: self._aopen(args, kwargs), admission, kwargs)
1525
+
1526
+ def _stream_manager(self, *args: Any, **kwargs: Any) -> _StreamManager:
1527
+ """``messages.stream(...)``: a context manager yielding a `ResumableStream`."""
1528
+ return _StreamManager(self, args, kwargs)
1529
+
1530
+
1531
+ class _Namespace:
1532
+ """A guarded attribute group (``guarded.chat``): named children, the rest passed on."""
1533
+
1534
+ def __init__(self, guard: GuardedClient, path: tuple[str, ...], **children: Any) -> None:
1535
+ self._guard, self._path = guard, path
1536
+ for name, child in children.items():
1537
+ setattr(self, name, child)
1538
+
1539
+ def __getattr__(self, name: str) -> Any:
1540
+ if name.startswith("_"):
1541
+ raise AttributeError(name)
1542
+ target = self._guard.raw
1543
+ for part in self._path:
1544
+ target = getattr(target, part)
1545
+ return getattr(target, name)
1546
+
1547
+
1548
+ class _StreamManager:
1549
+ """``with guarded.messages.stream(...) as stream:`` (or ``async with``)."""
1550
+
1551
+ def __init__(self, endpoint: _Endpoint, args: tuple[Any, ...], kwargs: dict[str, Any]) -> None:
1552
+ self._endpoint = endpoint
1553
+ self._args, self._kwargs = args, kwargs
1554
+ self._stream: ResumableStream[Any] | None = None
1555
+
1556
+ def _open(self) -> Any:
1557
+ endpoint, args, kwargs = self._endpoint, self._args, self._kwargs
1558
+ return endpoint._target().stream(*args, **kwargs)
1559
+
1560
+ def __enter__(self) -> ResumableStream[Any]:
1561
+ guard, label = self._endpoint._guard, self._endpoint._label
1562
+ scope = guard._admit(self._args, self._kwargs, label)
1563
+ self._stream = guard._resumable(label, self._open, scope, self._kwargs)
1564
+ return self._stream
1565
+
1566
+ def __exit__(self, *exc: object) -> None:
1567
+ if self._stream is not None:
1568
+ self._stream.close()
1569
+
1570
+ async def __aenter__(self) -> ResumableStream[Any]:
1571
+ guard, label = self._endpoint._guard, self._endpoint._label
1572
+ scope = await guard._aadmit(self._args, self._kwargs, label)
1573
+ self._stream = guard._resumable(label, self._open, scope, self._kwargs)
1574
+ return self._stream
1575
+
1576
+ async def __aexit__(self, *exc: object) -> None:
1577
+ if self._stream is not None:
1578
+ await self._stream.aclose()
1579
+
1580
+
1581
+ class _Runner:
1582
+ """Per-step accounting around an SDK tool runner (sync or async)."""
1583
+
1584
+ def __init__(self, guard: GuardedClient, runner: Any, kwargs: dict[str, Any], label: str):
1585
+ self._guard, self._runner, self._kwargs, self._label = guard, runner, kwargs, label
1586
+ self.steps = 0
1587
+
1588
+ def __getattr__(self, name: str) -> Any:
1589
+ if name.startswith("_"):
1590
+ raise AttributeError(name)
1591
+ return getattr(self._runner, name)
1592
+
1593
+ def __iter__(self) -> Iterator[Any]:
1594
+ guard, iterator = self._guard, iter(self._runner)
1595
+ while True:
1596
+ scope = guard._admit((), self._kwargs, self._label)
1597
+ try:
1598
+ message = next(iterator)
1599
+ except StopIteration:
1600
+ guard._release(scope)
1601
+ return
1602
+ except BaseException as exc:
1603
+ guard._release(scope, exc)
1604
+ raise
1605
+ self.steps += 1
1606
+ guard._account(scope, message, self._kwargs)
1607
+ yield message
1608
+
1609
+ async def __aiter__(self) -> AsyncIterator[Any]:
1610
+ guard, iterator = self._guard, self._runner.__aiter__()
1611
+ while True:
1612
+ scope = await guard._aadmit((), self._kwargs, self._label)
1613
+ try:
1614
+ message = await iterator.__anext__()
1615
+ except StopAsyncIteration:
1616
+ guard._release(scope)
1617
+ return
1618
+ except BaseException as exc:
1619
+ guard._release(scope, exc)
1620
+ raise
1621
+ self.steps += 1
1622
+ guard._account(scope, message, self._kwargs)
1623
+ yield message
1624
+
1625
+ def until_done(self) -> Any:
1626
+ """Run every step (accounted) and return the last message."""
1627
+ if self._guard.is_async:
1628
+ return self._auntil_done()
1629
+ last = None
1630
+ for message in self:
1631
+ last = message
1632
+ return last
1633
+
1634
+ async def _auntil_done(self) -> Any:
1635
+ last = None
1636
+ async for message in self:
1637
+ last = message
1638
+ return last
1639
+
1640
+
1641
+ _MAX_LIMITER_KEYS = 256 # distinct limiter_key values; later ones share the base limiter
1642
+
1643
+
1644
+ @dataclasses.dataclass
1645
+ class _Admission:
1646
+ """What `GuardedClient._admit` reserved for one streamed call or runner step."""
1647
+
1648
+ scope: str | None
1649
+ cost: int
1650
+ request: Mapping[str, Any] | None = None
1651
+
1652
+
1653
+ class GuardedClient:
1654
+ """The proxy `guard_openai` and `guard_anthropic` return.
1655
+
1656
+ Guarded resources run each call through, outermost first: tracing
1657
+ (`traced_llm`, when ``trace`` is set), the `Budget` (checked before, charged with
1658
+ the response's usage after), the retry loop (`llm_retry` with
1659
+ ``owns_retries=True``), your per-attempt ``policy`` (a timeout, a breaker), and the
1660
+ `TokenRateLimiter` (reserve an estimate, settle with the real usage, then lower the
1661
+ bucket to the provider's ``*-remaining-tokens`` header; a 429's ``retry-after``
1662
+ drains it). Streams (``stream=True``) become `ResumableStream` objects whose usage
1663
+ is charged when they end. Every other attribute is the original client's,
1664
+ unguarded.
1665
+
1666
+ Attributes:
1667
+ raw: The client you passed (its SDK retries untouched).
1668
+ client: The client calls go through (``max_retries=0`` when python-wrap owns
1669
+ retries).
1670
+ system: ``"openai"`` or ``"anthropic"``.
1671
+ is_async: Whether the client is async.
1672
+ """
1673
+
1674
+ def __init__(
1675
+ self,
1676
+ client: Any,
1677
+ *,
1678
+ system: str,
1679
+ budget: Budget | None = None,
1680
+ limiter: TokenRateLimiter | None = None,
1681
+ policy: Callable[[Callable[..., Any]], Callable[..., Any]] | None = None,
1682
+ attempts: int = 4,
1683
+ retry: Mapping[str, Any] | None = None,
1684
+ owns_retries: bool = True,
1685
+ trace: bool | Mapping[str, Any] = False,
1686
+ cache_guard: CacheGuard | None = None,
1687
+ read_headers: bool = True,
1688
+ first_token: float | None = None,
1689
+ chunk_gap: float | None = None,
1690
+ total: float | None = None,
1691
+ is_async: bool | None = None,
1692
+ limiter_key: Callable[[Mapping[str, Any]], str] | None = None,
1693
+ ) -> None:
1694
+ if limiter_key is not None and getattr(limiter, "_store", None) is not None:
1695
+ # shortcut: per-key windows are in-process only; upgrade when a shared token
1696
+ # window can be cloned under a new name.
1697
+ raise ValueError("limiter_key needs an in-process TokenRateLimiter (no store=)")
1698
+ if isinstance(attempts, bool) or not isinstance(attempts, int) or attempts < 1:
1699
+ raise ValueError(f"attempts must be an integer >= 1, got {attempts!r}")
1700
+ if retry is not None and ("max_attempts" in retry or "owns_retries" in retry):
1701
+ raise ValueError("pass attempts= and owns_retries= directly, not inside retry=")
1702
+ self.raw = client
1703
+ self.client = client
1704
+ if owns_retries:
1705
+ try:
1706
+ self.client = no_sdk_retries(client)
1707
+ except TypeError:
1708
+ if sdk_max_retries(client): # it retries and cannot be told not to
1709
+ raise
1710
+ # a client without its own retry loop (a fake, a thin wrapper): use as is
1711
+ self.system = system
1712
+ self.budget, self.limiter, self.policy = budget, limiter, policy
1713
+ self.limiter_key = limiter_key
1714
+ self._limiters: dict[str, TokenRateLimiter] = {}
1715
+ self.attempts = attempts if owns_retries else 1
1716
+ self.owns_retries = owns_retries
1717
+ self._retry_options = dict(retry or {})
1718
+ self.trace: dict[str, Any] | None = None
1719
+ if isinstance(trace, Mapping):
1720
+ self.trace = dict(trace)
1721
+ elif trace:
1722
+ self.trace = {}
1723
+ self.cache_guard = cache_guard
1724
+ self.read_headers = read_headers
1725
+ self._limits = {"first_token": first_token, "chunk_gap": chunk_gap, "total": total}
1726
+ if any(value is not None for value in self._limits.values()):
1727
+ stream_timeout([], **self._limits) # validates
1728
+ self.is_async = _is_async_client(client) if is_async is None else is_async
1729
+
1730
+ # -- composition -------------------------------------------------------------
1731
+ def _compose(self, label: str, attempt: Callable[..., Any]) -> Callable[..., Any]:
1732
+ if self.is_async:
1733
+
1734
+ async def one(*args: Any, **kwargs: Any) -> Any:
1735
+ return await attempt(*args, **kwargs)
1736
+
1737
+ call: Callable[..., Any] = one
1738
+ else:
1739
+
1740
+ def sync_one(*args: Any, **kwargs: Any) -> Any:
1741
+ return attempt(*args, **kwargs)
1742
+
1743
+ call = sync_one
1744
+ call.__name__ = call.__qualname__ = label
1745
+ if self.policy is not None:
1746
+ call = self.policy(call)
1747
+ if self.owns_retries and self.attempts > 1:
1748
+ call = llm_retry(
1749
+ max_attempts=self.attempts,
1750
+ owns_retries=True,
1751
+ client=self.client,
1752
+ **self._retry_options,
1753
+ )(call)
1754
+ if self.budget is not None:
1755
+ call = self.budget(call)
1756
+ if self.trace is not None:
1757
+ from python_wrap.genai import traced_llm
1758
+
1759
+ call = traced_llm(**{"system": self.system, **self.trace})(call)
1760
+ return call
1761
+
1762
+ # -- limiter and budget steps ------------------------------------------------
1763
+ def _estimate(self, args: tuple[Any, ...], kwargs: Mapping[str, Any]) -> int:
1764
+ limiter = self.limiter
1765
+ if limiter is None or _core.overrides.disable_rate_limits:
1766
+ return 0
1767
+ return max(0, int(limiter._estimate(*args, **kwargs)))
1768
+
1769
+ def _reserve(self, args: tuple[Any, ...], kwargs: Mapping[str, Any], label: str) -> int:
1770
+ cost = self._estimate(args, kwargs)
1771
+ limiter = self._limiting(kwargs)
1772
+ if limiter is not None:
1773
+ limiter.acquire(cost, label=label)
1774
+ return cost
1775
+
1776
+ async def _areserve(self, args: tuple[Any, ...], kwargs: Mapping[str, Any], label: str) -> int:
1777
+ cost = self._estimate(args, kwargs)
1778
+ limiter = self._limiting(kwargs)
1779
+ if limiter is not None:
1780
+ await limiter.aacquire(cost, label=label)
1781
+ return cost
1782
+
1783
+ def _limiting(self, request: Mapping[str, Any] | None = None) -> TokenRateLimiter | None:
1784
+ """The limiter for this request: one window per ``limiter_key`` value, if set."""
1785
+ limiter = self.limiter
1786
+ if limiter is None or _core.overrides.disable_rate_limits:
1787
+ return None
1788
+ if self.limiter_key is None or request is None:
1789
+ return limiter
1790
+ key = str(self.limiter_key(request))
1791
+ found = self._limiters.get(key)
1792
+ if found is None and len(self._limiters) >= _MAX_LIMITER_KEYS:
1793
+ return limiter # keys may come from requests: never grow without bound
1794
+ if found is None:
1795
+ found = self._limiters.setdefault(
1796
+ key,
1797
+ TokenRateLimiter(
1798
+ limiter.tokens_per_minute,
1799
+ estimate=limiter._estimate,
1800
+ usage=limiter.usage,
1801
+ block=limiter.block,
1802
+ max_wait=limiter.max_wait,
1803
+ name=f"{limiter.name}:{key}",
1804
+ ),
1805
+ )
1806
+ return found
1807
+
1808
+ def _seed(self, headers: Any, request: Mapping[str, Any] | None = None) -> None:
1809
+ limiter = self._limiting(request)
1810
+ if limiter is not None:
1811
+ seed_limiter(limiter, headers)
1812
+
1813
+ def _seed_error(self, exc: BaseException, request: Mapping[str, Any] | None = None) -> None:
1814
+ limiter = self._limiting(request)
1815
+ if limiter is None:
1816
+ return
1817
+ status = _int(_field(exc, "status_code")) or _int(
1818
+ _field(getattr(exc, "response", None), "status_code")
1819
+ )
1820
+ hint = llm_retry_after(exc) if status == 429 else None
1821
+ seed_limiter(limiter, _headers_of(exc), retry_after=hint)
1822
+
1823
+ def _failed(
1824
+ self, cost: int, exc: BaseException, request: Mapping[str, Any] | None = None
1825
+ ) -> None:
1826
+ limiter = self._limiting(request)
1827
+ if limiter is not None:
1828
+ limiter.settle(cost, 0)
1829
+ self._seed_error(exc, request)
1830
+
1831
+ def _settled(self, cost: int, result: Any, headers: Any, kwargs: Mapping[str, Any]) -> None:
1832
+ limiter = self._limiting(kwargs)
1833
+ if limiter is not None:
1834
+ usage = read_usage(result)
1835
+ limiter.settle(cost, cost if usage is None else usage.total_tokens)
1836
+ seed_limiter(limiter, headers)
1837
+ if self.cache_guard is not None:
1838
+ self.cache_guard.observe(result, kwargs)
1839
+
1840
+ def _scope(self, args: tuple[Any, ...], kwargs: Mapping[str, Any], label: str) -> str | None:
1841
+ budget = self.budget
1842
+ if budget is None:
1843
+ return None
1844
+ from python_wrap.llm import _MISSING
1845
+
1846
+ scope = budget._scope_key(args, dict(kwargs), _MISSING)
1847
+ budget._check(scope, label)
1848
+ return scope
1849
+
1850
+ def _admit(self, args: tuple[Any, ...], kwargs: Mapping[str, Any], label: str) -> _Admission:
1851
+ scope = self._scope(args, kwargs, label)
1852
+ return _Admission(scope, self._reserve(args, kwargs, label), kwargs)
1853
+
1854
+ async def _aadmit(
1855
+ self, args: tuple[Any, ...], kwargs: Mapping[str, Any], label: str
1856
+ ) -> _Admission:
1857
+ scope = self._scope(args, kwargs, label)
1858
+ return _Admission(scope, await self._areserve(args, kwargs, label), kwargs)
1859
+
1860
+ def _release(self, admission: _Admission, error: BaseException | None = None) -> None:
1861
+ """Refund a reservation whose call produced nothing."""
1862
+ if error is not None:
1863
+ self._failed(admission.cost, error, admission.request)
1864
+ else:
1865
+ limiter = self._limiting(admission.request)
1866
+ if limiter is not None:
1867
+ limiter.settle(admission.cost, 0)
1868
+
1869
+ def _account(self, admission: _Admission, response: Any, request: Mapping[str, Any]) -> None:
1870
+ """Charge a finished call or step: budget, limiter, cache guard."""
1871
+ usage = read_usage(response)
1872
+ if self.budget is not None and admission.scope is not None:
1873
+ self.budget._add(admission.scope, usage)
1874
+ limiter = self._limiting(admission.request)
1875
+ if limiter is not None:
1876
+ limiter.settle(admission.cost, admission.cost if usage is None else usage.total_tokens)
1877
+ if self.cache_guard is not None:
1878
+ self.cache_guard.observe(response, request)
1879
+
1880
+ def _resumable(
1881
+ self,
1882
+ label: str,
1883
+ factory: Callable[[], Any],
1884
+ admission: _Admission,
1885
+ request: Mapping[str, Any],
1886
+ ) -> ResumableStream[Any]:
1887
+ def finish(stream: ResumableStream[Any], error: BaseException | None) -> None:
1888
+ fields = stream.usage_fields
1889
+ if fields:
1890
+ self._account(admission, {"usage": dict(fields), "model": stream.model}, request)
1891
+ elif not stream.committed: # nothing was produced: refund the reservation
1892
+ self._release(admission)
1893
+ # output without reported usage: the estimate stands
1894
+
1895
+ options = self._retry_options
1896
+ extra = options.get("retry_if")
1897
+
1898
+ def worth_reopening(exc: BaseException) -> bool:
1899
+ return stream_transient(exc) and (extra is None or bool(extra(exc)))
1900
+
1901
+ return ResumableStream(
1902
+ factory,
1903
+ max_attempts=self.attempts,
1904
+ retry_if=worth_reopening,
1905
+ delay=options.get("delay", 0.5),
1906
+ max_delay=options.get("max_delay", 8.0),
1907
+ first_token=self._limits["first_token"],
1908
+ chunk_gap=self._limits["chunk_gap"],
1909
+ total=self._limits["total"],
1910
+ on_finish=finish,
1911
+ name=label,
1912
+ )
1913
+
1914
+ # -- diagnostics -------------------------------------------------------------
1915
+ def doctor(self) -> Report:
1916
+ """Lint the per-call stack of this guard (`python_wrap.doctor.doctor`)."""
1917
+ from python_wrap.doctor import doctor
1918
+
1919
+ return doctor(self._primary().create)
1920
+
1921
+ def _primary(self) -> _Endpoint:
1922
+ raise NotImplementedError
1923
+
1924
+ def __getattr__(self, name: str) -> Any:
1925
+ if name.startswith("_"):
1926
+ raise AttributeError(name)
1927
+ return getattr(self.raw, name)
1928
+
1929
+ def __repr__(self) -> str:
1930
+ return (
1931
+ f"{type(self).__name__}({type(self.raw).__name__}, attempts={self.attempts}, "
1932
+ f"budget={self.budget!r}, limiter={self.limiter!r})"
1933
+ )
1934
+
1935
+
1936
+ # -------------------------------------------------------------------- doctor
1937
+
1938
+
1939
+ def doctor_findings(layers: Sequence[Layer]) -> list[Finding]:
1940
+ """PW018-PW019: SDK retries under a python-wrap retry; retried streams."""
1941
+ from python_wrap.doctor import Finding
1942
+
1943
+ found: list[Finding] = []
1944
+ for layer in layers:
1945
+ sdk = layer.settings.get("sdk_retries")
1946
+ if layer.role == "retry" and isinstance(sdk, int) and sdk > 0:
1947
+ attempts = layer.settings.get("max_attempts")
1948
+ total = (
1949
+ f"{attempts} x {sdk + 1} = {attempts * (sdk + 1)}"
1950
+ if isinstance(attempts, int)
1951
+ else f"{sdk + 1}x"
1952
+ )
1953
+ found.append(
1954
+ Finding(
1955
+ "PW018",
1956
+ "warning",
1957
+ f"python-wrap retries an SDK client that still retries by itself "
1958
+ f"(max_retries={sdk}): up to {total} HTTP requests per call, and the "
1959
+ "SDK's waits ignore the RetryBudget. Pass no_sdk_retries(client) (or "
1960
+ "use guard_openai/guard_anthropic, which do it).",
1961
+ )
1962
+ )
1963
+ kinds = [layer.settings.get("llm") for layer in layers]
1964
+ if (
1965
+ any(layer.role == "retry" for layer in layers)
1966
+ and "stream_timeout" in kinds
1967
+ and "resume_safe" not in kinds
1968
+ ):
1969
+ found.append(
1970
+ Finding(
1971
+ "PW019",
1972
+ "warning",
1973
+ "a retry wraps a streamed LLM call without resume_safe: the retry only "
1974
+ "covers opening the stream, and replaying it after output started repeats "
1975
+ "text and half-done tool calls. Use resume_safe(...) for the stream.",
1976
+ )
1977
+ )
1978
+ return found