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
python_wrap/llm.py ADDED
@@ -0,0 +1,2574 @@
1
+ """Wrappers for LLM calls: classified retries, spend budgets, token rate limits,
2
+ model fallback chains, streaming timeouts and a response cache.
3
+
4
+ Provider SDKs are never imported. Responses are duck-typed: token usage is read from
5
+ ``response.usage.input_tokens`` / ``output_tokens`` (Anthropic style),
6
+ ``response.usage.prompt_tokens`` / ``completion_tokens`` (OpenAI style), the same keys
7
+ on a dict, or a ``usage=`` callable you supply. Errors are classified by ``status_code``
8
+ (on the exception or its ``.response``), by class name and by the error body, so the
9
+ same code works with any client library, or with your own HTTP calls.
10
+
11
+ The pieces:
12
+
13
+ - `llm_transient` / `llm_retry`: retry 408/409/429/529/5xx, overloaded, timeout and
14
+ connection errors (honouring ``Retry-After`` and ``retry-after-ms``), never other 4xx
15
+ or content-policy refusals. ``python_wrap.presets.llm_client`` bundles it with a
16
+ timeout and a circuit breaker.
17
+ - `Budget` / `budget`: token and dollar limits per total, per key (user, tenant), per
18
+ explicit run or per call chain, with an optional shared backend.
19
+ - `token_rate_limit`: a tokens-per-minute bucket that reserves an estimate before the
20
+ call and reconciles it with the real usage afterwards.
21
+ - `fallback_models`: try models in order, each behind its own circuit breaker, with an
22
+ optional last-good cached answer; emits ``llm.fallback_served``.
23
+ - `stream_timeout`: ``first_token=``, ``chunk_gap=`` and ``total=`` limits for sync and
24
+ async streams; raises `StreamTimeout`.
25
+ - `llm_cache`: an exact-match response cache keyed on the request, with a pluggable
26
+ store and an optional ``similarity=`` embedding hook for semantic matches.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import asyncio
32
+ import contextlib
33
+ import contextvars
34
+ import dataclasses
35
+ import functools
36
+ import hashlib
37
+ import inspect
38
+ import json
39
+ import math
40
+ import queue
41
+ import threading
42
+ import time
43
+ import uuid
44
+ import weakref
45
+ from collections import OrderedDict
46
+ from collections.abc import (
47
+ AsyncIterable,
48
+ AsyncIterator,
49
+ Awaitable,
50
+ Callable,
51
+ Hashable,
52
+ Iterable,
53
+ Iterator,
54
+ Mapping,
55
+ Sequence,
56
+ )
57
+ from types import MappingProxyType, TracebackType
58
+ from typing import TYPE_CHECKING, Any, Literal, ParamSpec, Protocol, TypeVar, cast, overload
59
+
60
+ from python_wrap import _core, _fork
61
+ from python_wrap._runtime import digest
62
+ from python_wrap.circuit import CircuitBreaker
63
+ from python_wrap.errors import CircuitOpenError, PythonWrapError, RateLimitExceeded, TimeoutExpired
64
+ from python_wrap.retry import RetryBudget, retry, retry_after_header
65
+
66
+ if TYPE_CHECKING:
67
+ from python_wrap.doctor import Finding, Layer
68
+
69
+ __all__ = [
70
+ "Budget",
71
+ "BudgetBackend",
72
+ "BudgetExceeded",
73
+ "RedisBudgetBackend",
74
+ "Spend",
75
+ "StreamTimeout",
76
+ "TokenRateLimiter",
77
+ "Usage",
78
+ "budget",
79
+ "estimate_tokens",
80
+ "fallback_models",
81
+ "llm_cache",
82
+ "llm_retry",
83
+ "llm_retry_after",
84
+ "llm_transient",
85
+ "read_usage",
86
+ "stream_timeout",
87
+ "token_rate_limit",
88
+ ]
89
+
90
+ P = ParamSpec("P")
91
+ R = TypeVar("R")
92
+ T = TypeVar("T")
93
+
94
+ _LAYER_ATTR = "__python_wrap_layer__"
95
+ _Decorator = Callable[[Callable[P, R]], Callable[P, R]]
96
+ ExceptionTypes = type[BaseException] | tuple[type[BaseException], ...]
97
+
98
+
99
+ # ----------------------------------------------------------------------- exceptions
100
+
101
+
102
+ class BudgetExceeded(PythonWrapError):
103
+ """A token or dollar `Budget` is used up, so the call was not made.
104
+
105
+ Attributes:
106
+ budget: The budget name.
107
+ scope: The scope that ran out (``"total"``, ``"key"``, ``"run"``, ``"chain"``).
108
+ tokens: Tokens spent in that scope so far.
109
+ usd: Dollars spent in that scope so far.
110
+ limit_tokens: The token limit, or None.
111
+ limit_usd: The dollar limit, or None.
112
+ """
113
+
114
+ def __init__(
115
+ self,
116
+ message: str,
117
+ *,
118
+ budget: str,
119
+ scope: str,
120
+ tokens: int,
121
+ usd: float,
122
+ limit_tokens: int | None,
123
+ limit_usd: float | None,
124
+ ) -> None:
125
+ super().__init__(message)
126
+ self.budget = budget
127
+ self.scope = scope
128
+ self.tokens = tokens
129
+ self.usd = usd
130
+ self.limit_tokens = limit_tokens
131
+ self.limit_usd = limit_usd
132
+
133
+
134
+ class StreamTimeout(TimeoutExpired):
135
+ """A stream produced no chunk in time.
136
+
137
+ Attributes:
138
+ limit: Which limit tripped: ``"first_token"``, ``"chunk_gap"`` or ``"total"``.
139
+ seconds: That limit's value.
140
+ """
141
+
142
+ def __init__(self, message: str, *, seconds: float, limit: str) -> None:
143
+ super().__init__(message, seconds=seconds)
144
+ self.limit = limit
145
+
146
+
147
+ # ------------------------------------------------------------ error classification
148
+
149
+ #: Class names (anywhere in the MRO) of transient errors in common LLM SDKs.
150
+ _TRANSIENT_NAMES = frozenset(
151
+ {
152
+ "RateLimitError",
153
+ "APITimeoutError",
154
+ "APIConnectionError",
155
+ "InternalServerError",
156
+ "OverloadedError",
157
+ "ServiceUnavailableError",
158
+ "ServiceUnavailable",
159
+ "TooManyRequests",
160
+ "ResourceExhausted",
161
+ "DeadlineExceeded",
162
+ }
163
+ )
164
+ #: Error-body ``type``/``code`` values that mean "try again later".
165
+ _TRANSIENT_CODES = frozenset(
166
+ {"overloaded_error", "rate_limit_error", "rate_limit_exceeded", "server_error", "timeout"}
167
+ )
168
+ #: Error-body ``type``/``code`` values that mean "the provider refused the content".
169
+ _REFUSAL_CODES = frozenset(
170
+ {
171
+ "content_filter",
172
+ "content_policy_violation",
173
+ "content_policy",
174
+ "refusal",
175
+ "safety",
176
+ "responsible_ai_policy_violation",
177
+ }
178
+ )
179
+ _REFUSAL_HINTS = ("contentfilter", "contentpolicy", "refusal", "safety", "moderation")
180
+
181
+
182
+ def _field(obj: Any, name: str) -> Any:
183
+ """Read ``name`` from a mapping key or an attribute."""
184
+ if obj is None:
185
+ return None
186
+ if isinstance(obj, Mapping):
187
+ return obj.get(name)
188
+ return getattr(obj, name, None)
189
+
190
+
191
+ def _int(value: Any) -> int | None:
192
+ if isinstance(value, bool) or not isinstance(value, int):
193
+ return None
194
+ return value
195
+
196
+
197
+ def _status(exc: BaseException) -> int | None:
198
+ for source in (exc, getattr(exc, "response", None)):
199
+ for name in ("status_code", "status", "http_status"):
200
+ found = _int(_field(source, name))
201
+ if found is not None and 100 <= found <= 599:
202
+ return found
203
+ return None
204
+
205
+
206
+ def _body_codes(exc: BaseException) -> set[str]:
207
+ codes: set[str] = set()
208
+ for name in ("code", "type"):
209
+ value = getattr(exc, name, None)
210
+ if isinstance(value, str):
211
+ codes.add(value.casefold())
212
+ body = getattr(exc, "body", None)
213
+ for part in (body, _field(body, "error")):
214
+ if isinstance(part, Mapping):
215
+ for name in ("type", "code"):
216
+ value = part.get(name)
217
+ if isinstance(value, str):
218
+ codes.add(value.casefold())
219
+ return codes
220
+
221
+
222
+ def _is_refusal(exc: BaseException) -> bool:
223
+ names = [klass.__name__.casefold() for klass in type(exc).__mro__]
224
+ if any(hint in name for name in names for hint in _REFUSAL_HINTS):
225
+ return True
226
+ return bool(_body_codes(exc) & _REFUSAL_CODES)
227
+
228
+
229
+ def llm_transient(exc: BaseException) -> bool:
230
+ """True when an LLM call that raised ``exc`` is worth retrying.
231
+
232
+ Retried: HTTP 408, 409, 429, 529 and every 5xx (read from ``status_code`` or
233
+ ``status`` on the exception or its ``.response``); bodies typed
234
+ ``overloaded_error`` / ``rate_limit_error``; SDK classes named like
235
+ ``RateLimitError``, ``APITimeoutError``, ``APIConnectionError``,
236
+ ``InternalServerError``; and any ``ConnectionError`` or ``TimeoutError``.
237
+
238
+ Never retried: every other 4xx (bad request, auth, not found), content-policy or
239
+ refusal errors (class names containing ``ContentFilter``, ``Refusal``, ``Safety``...
240
+ or a ``content_filter`` / ``content_policy_violation`` code), `CircuitOpenError` and
241
+ `BudgetExceeded`.
242
+
243
+ Args:
244
+ exc: The exception an LLM call raised.
245
+
246
+ Returns:
247
+ Whether a retry (or a fallback to another model) may help.
248
+
249
+ Example:
250
+ ```python
251
+ from python_wrap.llm import llm_transient
252
+
253
+ class APIStatusError(Exception):
254
+ def __init__(self, status_code: int) -> None:
255
+ self.status_code = status_code
256
+
257
+ assert llm_transient(APIStatusError(529))
258
+ assert not llm_transient(APIStatusError(400))
259
+ ```
260
+ """
261
+ if isinstance(exc, (CircuitOpenError, BudgetExceeded)):
262
+ return False
263
+ if _is_refusal(exc):
264
+ return False
265
+ status = _status(exc)
266
+ if status is not None:
267
+ return status in (408, 409, 429, 529) or status >= 500
268
+ if _body_codes(exc) & _TRANSIENT_CODES:
269
+ return True
270
+ if any(klass.__name__ in _TRANSIENT_NAMES for klass in type(exc).__mro__):
271
+ return True
272
+ return isinstance(exc, (ConnectionError, TimeoutError))
273
+
274
+
275
+ def llm_retry_after(exc: Any) -> float | None:
276
+ """The wait an LLM provider asked for, for ``retry(delay_from=...)``.
277
+
278
+ Reads a ``retry-after-ms`` header (milliseconds, sent by some providers) first, then
279
+ everything `retry_after_header` understands (``retry_after`` attribute,
280
+ ``Retry-After`` in seconds or as an HTTP date, on the error or ``.response``).
281
+
282
+ Args:
283
+ exc: An exception (or response-like object).
284
+
285
+ Returns:
286
+ Seconds to wait, or None when the provider gave no hint.
287
+ """
288
+ try:
289
+ headers = getattr(exc, "headers", None)
290
+ if headers is None:
291
+ headers = getattr(getattr(exc, "response", None), "headers", None)
292
+ if headers is not None:
293
+ items = headers.items() if hasattr(headers, "items") else headers
294
+ for key, value in items:
295
+ if str(key).casefold() == "retry-after-ms":
296
+ millis = float(value)
297
+ if math.isfinite(millis):
298
+ return max(millis / 1000, 0.0)
299
+ except (TypeError, ValueError, AttributeError):
300
+ pass
301
+ return retry_after_header(exc)
302
+
303
+
304
+ def llm_retry(
305
+ *,
306
+ max_attempts: int = 4,
307
+ delay: float = 1.0,
308
+ max_delay: float = 60.0,
309
+ jitter: float = 0.5,
310
+ max_time: float | None = None,
311
+ budget: RetryBudget | None = None,
312
+ retry_if: Callable[[BaseException], bool] | None = None,
313
+ owns_retries: bool = False,
314
+ client: Any = None,
315
+ ) -> _Decorator[..., Any]:
316
+ """A `retry` configured for LLM APIs.
317
+
318
+ Retries what `llm_transient` accepts (rate limits, overloaded, 5xx, timeouts and
319
+ connection errors) and nothing else, so a bad request or a content-policy refusal
320
+ fails at once instead of being paid for four times. The wait doubles from
321
+ ``delay`` up to ``max_delay`` with up to ``jitter`` random seconds, unless the
322
+ provider sent ``Retry-After`` / ``retry-after-ms``: that wait is used exactly (still
323
+ capped by ``max_delay``). Retries draw on a `RetryBudget` (20 % of calls plus 5/s by
324
+ default) so an outage does not multiply your traffic.
325
+
326
+ Args:
327
+ max_attempts: Total attempts, including the first.
328
+ delay: First backoff wait in seconds.
329
+ max_delay: Longest single wait, also the cap on server hints.
330
+ jitter: Random extra seconds added to each backoff wait.
331
+ max_time: Total time budget for all attempts (None: no limit).
332
+ budget: A shared `RetryBudget`; a new one (ratio 0.2, 5/s) otherwise.
333
+ retry_if: Extra predicate; an error is retried only if it is transient **and**
334
+ this returns True.
335
+ owns_retries: Make this the only retry loop for the call. Any ``llm_retry``
336
+ running inside it (in a helper, or in a guarded SDK client from
337
+ `python_wrap.adapters`) makes a single attempt, and when this decorator
338
+ itself runs inside another ``llm_retry`` it makes a single attempt, so
339
+ attempts never multiply across layers (4 x 3 = 12). Turn the SDK's own
340
+ retries off as well (`python_wrap.adapters.no_sdk_retries`).
341
+ client: The SDK client the function calls. Only its ``max_retries`` setting is
342
+ read, so ``doctor`` can warn (PW018) while the SDK still retries underneath.
343
+
344
+ Returns:
345
+ A decorator for sync or async functions.
346
+
347
+ Example:
348
+ ```python
349
+ from python_wrap.llm import llm_retry
350
+ from python_wrap.testing import fake_clock
351
+
352
+ class Overloaded(Exception):
353
+ status_code = 529
354
+
355
+ calls = []
356
+
357
+ @llm_retry(max_attempts=3)
358
+ def complete(prompt: str) -> str:
359
+ calls.append(prompt)
360
+ if len(calls) < 3:
361
+ raise Overloaded
362
+ return "done"
363
+
364
+ with fake_clock():
365
+ assert complete("hi") == "done"
366
+ assert len(calls) == 3
367
+ ```
368
+ """
369
+ extra = retry_if
370
+
371
+ def transient(exc: BaseException) -> bool:
372
+ return llm_transient(exc) and (extra is None or bool(extra(exc)))
373
+
374
+ inner = retry(
375
+ max_attempts=max_attempts,
376
+ delay=delay,
377
+ backoff=2,
378
+ max_delay=max_delay,
379
+ jitter=jitter,
380
+ max_time=max_time,
381
+ on=Exception,
382
+ retry_if=transient,
383
+ delay_from=llm_retry_after,
384
+ budget=budget if budget is not None else RetryBudget(ratio=0.2, min_per_second=5),
385
+ )
386
+ settings = {**getattr(inner, _LAYER_ATTR)[1], "llm": "retry", "owns_retries": owns_retries}
387
+ sdk_retries = _sdk_retries(client) if client is not None else None
388
+ if sdk_retries is not None:
389
+ settings["sdk_retries"] = sdk_retries
390
+ mark = "owner" if owns_retries else "loop"
391
+
392
+ def single(state: str | None) -> bool:
393
+ # Inside an owner every llm_retry makes one attempt; so does an owner inside a loop.
394
+ return state == "owner" or (owns_retries and state is not None)
395
+
396
+ def decorate(func: Callable[P, R]) -> Callable[P, R]:
397
+ looped: Callable[..., Any] = inner(func)
398
+ wrapper: Any
399
+ if _core.is_async(func):
400
+ afunc = cast("Callable[..., Awaitable[Any]]", func)
401
+
402
+ @functools.wraps(func)
403
+ async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
404
+ state = _active_retry_scope()
405
+ if single(state):
406
+ return await afunc(*args, **kwargs)
407
+ token = _RETRY_SCOPE.set((state if state == "owner" else mark, _retry_identity()))
408
+ try:
409
+ return await looped(*args, **kwargs)
410
+ finally:
411
+ _RETRY_SCOPE.reset(token)
412
+
413
+ wrapper = async_wrapper
414
+ else:
415
+
416
+ @functools.wraps(func)
417
+ def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
418
+ state = _active_retry_scope()
419
+ if single(state):
420
+ return func(*args, **kwargs)
421
+ token = _RETRY_SCOPE.set((state if state == "owner" else mark, _retry_identity()))
422
+ try:
423
+ return looped(*args, **kwargs)
424
+ finally:
425
+ _RETRY_SCOPE.reset(token)
426
+
427
+ wrapper = sync_wrapper
428
+ stats = getattr(looped, "__retry_stats__", None)
429
+ if stats is not None:
430
+ wrapper.__retry_stats__ = stats
431
+ setattr(wrapper, _LAYER_ATTR, ("retry", settings))
432
+ return cast("Callable[P, R]", wrapper)
433
+
434
+ setattr(decorate, _LAYER_ATTR, ("retry", settings))
435
+ return decorate
436
+
437
+
438
+ #: Current retry scope and its task/thread identity. The scope is ignored when a copied
439
+ #: context runs under a different identity.
440
+ _RETRY_SCOPE: contextvars.ContextVar[tuple[str, weakref.ReferenceType[object]] | None] = (
441
+ contextvars.ContextVar("python_wrap_llm_retry_scope", default=None)
442
+ )
443
+
444
+
445
+ def _retry_owner() -> object:
446
+ """Identify the task or thread that owns an LLM retry scope.
447
+
448
+ Context variables can be explicitly copied into a new thread, and free-threaded
449
+ Python may inherit them by default. A copied scope must not suppress retries in an
450
+ independent execution owner. Return the object itself only transiently; the stored
451
+ scope keeps a weak reference so a long-lived copied context cannot retain a task.
452
+ """
453
+ try:
454
+ task = asyncio.current_task()
455
+ except RuntimeError:
456
+ task = None
457
+ if task is not None:
458
+ return task
459
+ return threading.current_thread()
460
+
461
+
462
+ def _retry_identity() -> weakref.ReferenceType[object]:
463
+ return weakref.ref(_retry_owner())
464
+
465
+
466
+ def _active_retry_scope() -> str | None:
467
+ scope = _RETRY_SCOPE.get()
468
+ if scope is None or scope[1]() is not _retry_owner():
469
+ return None
470
+ return scope[0]
471
+
472
+
473
+ def _sdk_retries(client: Any) -> int | None:
474
+ """The ``max_retries`` an SDK client (or a guard around one) is set to, or None."""
475
+ for source in (client, getattr(client, "_client", None)):
476
+ value = _int(getattr(source, "max_retries", None))
477
+ if value is not None:
478
+ return max(value, 0)
479
+ return None
480
+
481
+
482
+ # --------------------------------------------------- breakers counting transients only
483
+
484
+
485
+ class _NotCounted(Exception):
486
+ """Carries an error past a breaker without counting it as a failure."""
487
+
488
+ def __init__(self, error: Exception) -> None:
489
+ super().__init__(repr(error))
490
+ self.error = error
491
+
492
+
493
+ def _llm_breaker(**options: Any) -> CircuitBreaker:
494
+ return CircuitBreaker(on=Exception, exclude=_NotCounted, **options)
495
+
496
+
497
+ def _through_breaker(
498
+ breaker: CircuitBreaker, func: Callable[..., Any], counts: Callable[[BaseException], bool]
499
+ ) -> Callable[..., Any]:
500
+ """Call ``func`` through ``breaker``; only errors ``counts`` accepts open it."""
501
+ if _core.is_async(func):
502
+
503
+ async def ainner(*args: Any, **kwargs: Any) -> Any:
504
+ try:
505
+ return await func(*args, **kwargs)
506
+ except Exception as exc:
507
+ if counts(exc):
508
+ raise
509
+ raise _NotCounted(exc) from None
510
+
511
+ @functools.wraps(func)
512
+ async def async_call(*args: Any, **kwargs: Any) -> Any:
513
+ try:
514
+ return await breaker.call(ainner, *args, **kwargs)
515
+ except _NotCounted as carrier:
516
+ error = carrier.error
517
+ raise error
518
+
519
+ setattr(async_call, _LAYER_ATTR, ("breaker", breaker))
520
+ return async_call
521
+
522
+ def inner(*args: Any, **kwargs: Any) -> Any:
523
+ try:
524
+ return func(*args, **kwargs)
525
+ except Exception as exc:
526
+ if counts(exc):
527
+ raise
528
+ raise _NotCounted(exc) from None
529
+
530
+ @functools.wraps(func)
531
+ def call(*args: Any, **kwargs: Any) -> Any:
532
+ try:
533
+ return breaker.call(inner, *args, **kwargs)
534
+ except _NotCounted as carrier:
535
+ error = carrier.error
536
+ raise error
537
+
538
+ setattr(call, _LAYER_ATTR, ("breaker", breaker))
539
+ return call
540
+
541
+
542
+ class _BreakerLayer:
543
+ """A policy ``breaker=`` layer whose breaker counts only `llm_transient` errors."""
544
+
545
+ def __init__(self, breaker: CircuitBreaker) -> None:
546
+ self.breaker = breaker
547
+ setattr(self, _LAYER_ATTR, ("breaker", breaker))
548
+
549
+ def __call__(self, func: Callable[P, R]) -> Callable[P, R]:
550
+ return cast("Callable[P, R]", _through_breaker(self.breaker, func, llm_transient))
551
+
552
+
553
+ # ----------------------------------------------------------------------------- usage
554
+
555
+
556
+ @dataclasses.dataclass(frozen=True)
557
+ class Usage:
558
+ """Tokens one LLM call used.
559
+
560
+ Attributes:
561
+ input_tokens: Prompt tokens (including cache reads and writes, when reported).
562
+ output_tokens: Completion tokens.
563
+ model: The model that served the call, when the response names it.
564
+ """
565
+
566
+ input_tokens: int = 0
567
+ output_tokens: int = 0
568
+ model: str | None = None
569
+
570
+ @property
571
+ def total_tokens(self) -> int:
572
+ """Input plus output tokens."""
573
+ return self.input_tokens + self.output_tokens
574
+
575
+
576
+ def _count(raw: Any, *names: str) -> int | None:
577
+ for name in names:
578
+ value = _int(_field(raw, name))
579
+ if value is not None:
580
+ return max(value, 0)
581
+ return None
582
+
583
+
584
+ def read_usage(response: Any) -> Usage | None:
585
+ """Read token usage from a provider response without importing its SDK.
586
+
587
+ Understands ``response.usage`` with ``input_tokens`` / ``output_tokens``
588
+ (Anthropic style, plus ``cache_creation_input_tokens`` and
589
+ ``cache_read_input_tokens``, added to the input count) or ``prompt_tokens`` /
590
+ ``completion_tokens`` (OpenAI style), as attributes or dict keys, and a
591
+ ``model`` field next to it. A `Usage` is returned as is.
592
+
593
+ Args:
594
+ response: A response object or dict.
595
+
596
+ Returns:
597
+ The `Usage`, or None when the response reports none.
598
+
599
+ Example:
600
+ ```python
601
+ from python_wrap.llm import read_usage
602
+
603
+ usage = read_usage({"model": "m-1", "usage": {"prompt_tokens": 12, "completion_tokens": 3}})
604
+ assert usage is not None and usage.total_tokens == 15 and usage.model == "m-1"
605
+ ```
606
+ """
607
+ if isinstance(response, Usage):
608
+ return response
609
+ raw = _field(response, "usage")
610
+ if raw is None:
611
+ raw = _field(response, "usage_metadata") # LangChain AIMessage
612
+ if raw is None:
613
+ return None
614
+ meta = _field(response, "response_metadata")
615
+ model = _field(meta, "model_name") or _field(meta, "model")
616
+ inputs, outputs = _count(raw, "input_tokens"), _count(raw, "output_tokens")
617
+ if inputs is None and outputs is None:
618
+ return None
619
+ # LangChain's input_tokens already include cache reads.
620
+ return Usage(inputs or 0, outputs or 0, model if isinstance(model, str) and model else None)
621
+ inputs = _count(raw, "input_tokens", "prompt_tokens")
622
+ outputs = _count(raw, "output_tokens", "completion_tokens")
623
+ if inputs is None and outputs is None:
624
+ return None
625
+ cached = (_count(raw, "cache_creation_input_tokens") or 0) + (
626
+ _count(raw, "cache_read_input_tokens") or 0
627
+ )
628
+ model = _field(response, "model")
629
+ return Usage(
630
+ (inputs or 0) + cached, outputs or 0, model if isinstance(model, str) and model else None
631
+ )
632
+
633
+
634
+ UsageReader = Callable[[Any], Any]
635
+
636
+
637
+ def _coerce_usage(value: Any) -> Usage | None:
638
+ if value is None or isinstance(value, Usage):
639
+ return value
640
+ if isinstance(value, tuple) and len(value) == 2:
641
+ return Usage(max(int(value[0]), 0), max(int(value[1]), 0))
642
+ if isinstance(value, Mapping) and "usage" not in value:
643
+ return read_usage({"usage": value, "model": value.get("model")})
644
+ return read_usage(value)
645
+
646
+
647
+ def _usage_of(result: Any, reader: UsageReader | None) -> Usage | None:
648
+ return _coerce_usage(reader(result)) if reader is not None else read_usage(result)
649
+
650
+
651
+ Prices = Mapping[str, tuple[float, float]]
652
+
653
+
654
+ def _price(prices: Prices, model: str | None) -> tuple[float, float] | None:
655
+ if model is not None:
656
+ if model in prices:
657
+ return prices[model]
658
+ matches = [name for name in prices if name != "*" and model.startswith(name)]
659
+ if matches:
660
+ return prices[max(matches, key=len)]
661
+ return prices.get("*")
662
+
663
+
664
+ def _cost(usage: Usage, prices: Prices | None, default_model: str | None) -> float:
665
+ if not prices:
666
+ return 0.0
667
+ model = usage.model or default_model
668
+ price = _price(prices, model)
669
+ if price is None:
670
+ raise LookupError(
671
+ f"no price for model {model!r}: add it (or a '*' default) to prices=, "
672
+ "otherwise its calls would not count against the dollar budget"
673
+ )
674
+ return (usage.input_tokens * price[0] + usage.output_tokens * price[1]) / 1_000_000
675
+
676
+
677
+ # ---------------------------------------------------------------------------- budget
678
+
679
+
680
+ @dataclasses.dataclass(frozen=True)
681
+ class Spend:
682
+ """Tokens and dollars spent in one budget scope."""
683
+
684
+ tokens: int = 0
685
+ usd: float = 0.0
686
+
687
+
688
+ class BudgetBackend(Protocol):
689
+ """Where a `Budget` keeps its counters; implement it to share them between processes.
690
+
691
+ Keys are strings. ``add`` must be atomic and return the new totals; ``ttl`` (seconds
692
+ or None) bounds how long a counter needs to live (budgets with ``period=`` pass it).
693
+ """
694
+
695
+ def add(self, key: str, tokens: int, usd: float, ttl: float | None, /) -> tuple[int, float]:
696
+ """Add to a counter and return its new ``(tokens, usd)``."""
697
+
698
+ def get(self, key: str, /) -> tuple[int, float]:
699
+ """Return the counter's ``(tokens, usd)``; ``(0, 0.0)`` when unknown."""
700
+
701
+ def delete(self, key: str, /) -> None:
702
+ """Forget a counter."""
703
+
704
+
705
+ class _LocalBackend:
706
+ """Thread-safe in-process counters, with expiry for windowed budgets."""
707
+
708
+ def __init__(self) -> None:
709
+ self._data: dict[str, tuple[int, float, float | None]] = {}
710
+ self._lock = _fork.ForkSafeLock()
711
+ self._adds = 0
712
+
713
+ def _live(self, key: str, now: float) -> tuple[int, float]:
714
+ entry = self._data.get(key)
715
+ if entry is None or (entry[2] is not None and now >= entry[2]):
716
+ return 0, 0.0
717
+ return entry[0], entry[1]
718
+
719
+ def add(self, key: str, tokens: int, usd: float, ttl: float | None) -> tuple[int, float]:
720
+ now = _core.wall_time()
721
+ with self._lock:
722
+ used_tokens, used_usd = self._live(key, now)
723
+ old = self._data.get(key)
724
+ expires = old[2] if old is not None and (old[2] is None or now < old[2]) else None
725
+ if expires is None and ttl is not None:
726
+ expires = now + ttl
727
+ self._data[key] = (used_tokens + tokens, used_usd + usd, expires)
728
+ self._adds += 1
729
+ if self._adds % 256 == 0:
730
+ for name in [k for k, v in self._data.items() if v[2] is not None and now >= v[2]]:
731
+ del self._data[name]
732
+ return used_tokens + tokens, used_usd + usd
733
+
734
+ def get(self, key: str) -> tuple[int, float]:
735
+ with self._lock:
736
+ return self._live(key, _core.wall_time())
737
+
738
+ def delete(self, key: str) -> None:
739
+ with self._lock:
740
+ self._data.pop(key, None)
741
+
742
+
743
+ _REDIS_ADD = """
744
+ local t=redis.call('HINCRBY',KEYS[1],'tokens',ARGV[1])
745
+ local u=redis.call('HINCRBYFLOAT',KEYS[1],'usd',ARGV[2])
746
+ if tonumber(ARGV[3])>0 and redis.call('PTTL',KEYS[1])<0 then
747
+ redis.call('PEXPIRE',KEYS[1],ARGV[3]) end
748
+ return {t, tostring(u)}
749
+ """
750
+
751
+
752
+ class RedisBudgetBackend:
753
+ """A `BudgetBackend` on Redis, so every worker process shares one budget.
754
+
755
+ Takes any synchronous ``redis.Redis``-compatible client (``eval``, ``hmget``,
756
+ ``delete``); redis is never imported. Each counter is one hash updated by a Lua
757
+ script, so concurrent adds never lose spend. Async budgets run each round trip in a
758
+ worker thread.
759
+
760
+ Args:
761
+ client: The Redis client.
762
+ prefix: Namespace for the keys.
763
+ """
764
+
765
+ def __init__(self, client: Any, prefix: str = "python-wrap:budget") -> None:
766
+ if not prefix:
767
+ raise ValueError("RedisBudgetBackend needs a nonempty prefix")
768
+ self.client, self.prefix = client, prefix
769
+
770
+ def _key(self, key: str) -> str:
771
+ return f"{self.prefix}:{key}"
772
+
773
+ def add(self, key: str, tokens: int, usd: float, ttl: float | None) -> tuple[int, float]:
774
+ millis = 0 if ttl is None else max(1, math.ceil(ttl * 1000))
775
+ result = self.client.eval(_REDIS_ADD, 1, self._key(key), tokens, repr(usd), millis)
776
+ return int(result[0]), float(result[1])
777
+
778
+ def get(self, key: str) -> tuple[int, float]:
779
+ tokens, usd = self.client.hmget(self._key(key), "tokens", "usd")
780
+ return int(tokens or 0), float(usd or 0.0)
781
+
782
+ def delete(self, key: str) -> None:
783
+ self.client.delete(self._key(key))
784
+
785
+
786
+ Scope = Literal["total", "key", "run", "chain"]
787
+ _SCOPES = ("total", "key", "run", "chain")
788
+ _NO_RUNS: Mapping[str, str] = MappingProxyType({})
789
+ _RUNS: contextvars.ContextVar[Mapping[str, str]] = contextvars.ContextVar(
790
+ "python_wrap_llm_runs",
791
+ default=_NO_RUNS,
792
+ )
793
+
794
+
795
+ class _RunScope:
796
+ """``with budget.run():`` / ``async with budget.run():`` opens a fresh run."""
797
+
798
+ def __init__(self, owner: Budget) -> None:
799
+ self._owner = owner
800
+ self._token: contextvars.Token[Mapping[str, str]] | None = None
801
+ self._run = ""
802
+
803
+ def __enter__(self) -> _RunScope:
804
+ self._token, self._run = self._owner._open_run()
805
+ return self
806
+
807
+ def __exit__(
808
+ self,
809
+ exc_type: type[BaseException] | None,
810
+ exc: BaseException | None,
811
+ tb: TracebackType | None,
812
+ ) -> None:
813
+ if self._token is not None:
814
+ self._owner._close_run(self._token, self._run)
815
+ self._token = None
816
+
817
+ async def __aenter__(self) -> _RunScope:
818
+ return self.__enter__()
819
+
820
+ async def __aexit__(
821
+ self,
822
+ exc_type: type[BaseException] | None,
823
+ exc: BaseException | None,
824
+ tb: TracebackType | None,
825
+ ) -> None:
826
+ self.__exit__(exc_type, exc, tb)
827
+
828
+ @property
829
+ def spent(self) -> Spend:
830
+ """What this run has spent so far."""
831
+ return self._owner._read(self._owner._qualify(f"run:{self._run}"))
832
+
833
+
834
+ class Budget:
835
+ """A token and/or dollar limit for LLM calls; use it as a decorator.
836
+
837
+ Before each call the scope's counter is checked: if it is already at or over a
838
+ limit the call is not made and `BudgetExceeded` is raised. After a successful call
839
+ the response's usage (see `read_usage`) is added, priced with ``prices``. The call
840
+ that crosses a limit still returns its (already paid for) result; the next call is
841
+ refused. Errors spend nothing.
842
+
843
+ Scopes (``per=``):
844
+
845
+ - ``"total"``: one counter for the budget's lifetime (or each ``period``).
846
+ - ``"key"``: one counter per ``key(*args, **kwargs)``, for example per user.
847
+ - ``"run"``: one counter per ``with budget.run():`` block (sync or async; context
848
+ variables carry it into tasks and `hedge`/`run_in_thread` threads). Calling outside
849
+ a run raises `RuntimeError`.
850
+ - ``"chain"``: like ``"run"``, but the outermost decorated call opens the run, so an
851
+ agent loop decorated with the same budget caps everything it calls.
852
+
853
+ For streamed responses, call `record` with the final usage yourself.
854
+
855
+ Args:
856
+ tokens: Token limit (input plus output), or None.
857
+ usd: Dollar limit, or None (then ``prices`` is optional).
858
+ per: The scope, see above.
859
+ key: For ``per="key"``: function of the call arguments returning the key.
860
+ period: Reset the counters every ``period`` seconds (windows aligned to the wall
861
+ clock, e.g. ``86400`` for a daily budget); None never resets.
862
+ prices: ``{"model": (usd_per_million_input, usd_per_million_output)}``. The
863
+ longest key the model name starts with wins, ``"*"`` is the default. With a
864
+ ``usd`` limit, a model without a price raises `LookupError` after the call.
865
+ model: The model to price responses that do not name one.
866
+ usage: ``usage(response)`` returning a `Usage`, ``(input, output)`` or a usage
867
+ mapping, for responses `read_usage` does not understand.
868
+ name: Used in errors, events and backend keys.
869
+ backend: A `BudgetBackend` (e.g. `RedisBudgetBackend`) to share counters
870
+ between processes; in-process counters otherwise.
871
+
872
+ Raises:
873
+ ValueError: For a missing or out-of-range limit, unknown scope, or a ``per="key"``
874
+ budget without ``key=``.
875
+
876
+ Example:
877
+ ```python
878
+ from python_wrap.llm import Budget, BudgetExceeded
879
+
880
+ spend = Budget(usd=0.01, prices={"m-1": (1.0, 4.0)})
881
+
882
+ @spend
883
+ def complete(prompt: str) -> dict[str, object]:
884
+ return {"model": "m-1", "usage": {"input_tokens": 2000, "output_tokens": 1000}}
885
+
886
+ complete("one") # $0.006
887
+ complete("two") # $0.012: crosses the limit, result still returned
888
+ try:
889
+ complete("three")
890
+ except BudgetExceeded as exc:
891
+ assert exc.scope == "total"
892
+ assert spend.spent().tokens == 6000
893
+ ```
894
+ """
895
+
896
+ def __reduce__(self) -> Any:
897
+ _core.refuse_pickle(self)
898
+
899
+ def __init__(
900
+ self,
901
+ *,
902
+ tokens: int | None = None,
903
+ usd: float | None = None,
904
+ per: Scope = "total",
905
+ key: Callable[..., Hashable] | None = None,
906
+ period: float | None = None,
907
+ prices: Prices | None = None,
908
+ model: str | None = None,
909
+ usage: UsageReader | None = None,
910
+ name: str = "budget",
911
+ backend: BudgetBackend | None = None,
912
+ ) -> None:
913
+ if tokens is None and usd is None:
914
+ raise ValueError("a Budget needs tokens= or usd= (or both)")
915
+ if tokens is not None and (isinstance(tokens, bool) or not isinstance(tokens, int)):
916
+ raise ValueError(f"tokens must be an integer, got {tokens!r}")
917
+ if tokens is not None and tokens < 1:
918
+ raise ValueError(f"tokens must be >= 1, got {tokens!r}")
919
+ if usd is not None and (not math.isfinite(usd) or usd <= 0):
920
+ raise ValueError(f"usd must be a positive number, got {usd!r}")
921
+ if per not in _SCOPES:
922
+ raise ValueError(f"per must be one of {', '.join(_SCOPES)}; got {per!r}")
923
+ if per == "key" and key is None:
924
+ raise ValueError('per="key" needs key=, a function of the call arguments')
925
+ if period is not None and (not math.isfinite(period) or period <= 0):
926
+ raise ValueError(f"period must be positive, got {period!r}")
927
+ if usd is not None and not prices:
928
+ raise ValueError("a usd= limit needs prices= to turn tokens into dollars")
929
+ if not name:
930
+ raise ValueError("name must not be empty")
931
+ self.tokens, self.usd, self.per, self.key = tokens, usd, per, key
932
+ self.period, self.prices, self.model, self.usage = period, prices, model, usage
933
+ self.name = name
934
+ self.backend: BudgetBackend = backend if backend is not None else _LocalBackend()
935
+ self._shared = backend is not None
936
+ self._id = uuid.uuid4().hex
937
+ setattr(self, _LAYER_ATTR, ("budget", self._settings()))
938
+
939
+ def _settings(self) -> dict[str, Any]:
940
+ return {
941
+ "llm": "budget",
942
+ "name": self.name,
943
+ "tokens": self.tokens,
944
+ "usd": self.usd,
945
+ "per": self.per,
946
+ "shared": self._shared,
947
+ }
948
+
949
+ # -- scopes ------------------------------------------------------------------
950
+ def _qualify(self, base: str) -> str:
951
+ if self.period is not None:
952
+ base += f":w{int(_core.wall_time() // self.period)}"
953
+ return f"{self.name}:{base}"
954
+
955
+ def _scope_key(self, args: tuple[Any, ...], kwargs: dict[str, Any], key: Any) -> str:
956
+ if self.per == "total":
957
+ return self._qualify("total")
958
+ if self.per == "key":
959
+ if key is _MISSING:
960
+ assert self.key is not None
961
+ key = self.key(*args, **kwargs)
962
+ return self._qualify(f"key:{digest(key)}")
963
+ run = _RUNS.get().get(self._id)
964
+ if run is None:
965
+ raise RuntimeError(
966
+ f"budget {self.name!r} is per={self.per!r} but no run is active: "
967
+ "wrap the work in `with budget.run():`"
968
+ )
969
+ return self._qualify(f"run:{run}")
970
+
971
+ def _open_run(self) -> tuple[contextvars.Token[Mapping[str, str]], str]:
972
+ run = uuid.uuid4().hex
973
+ return _RUNS.set({**_RUNS.get(), self._id: run}), run
974
+
975
+ def _close_run(self, token: contextvars.Token[Mapping[str, str]], run: str) -> None:
976
+ _RUNS.reset(token)
977
+ self.backend.delete(self._qualify(f"run:{run}"))
978
+
979
+ def run(self) -> _RunScope:
980
+ """Open a new run scope: ``with budget.run():`` or ``async with budget.run():``.
981
+
982
+ Every decorated call inside shares one fresh counter, deleted when the block
983
+ exits. ``.spent`` on the returned object reports the run's spend.
984
+ """
985
+ return _RunScope(self)
986
+
987
+ # -- accounting --------------------------------------------------------------
988
+ def _read(self, scope: str) -> Spend:
989
+ tokens, usd = self.backend.get(scope)
990
+ return Spend(tokens, usd)
991
+
992
+ def _over(self, spend: Spend) -> bool:
993
+ return (self.tokens is not None and spend.tokens >= self.tokens) or (
994
+ self.usd is not None and spend.usd >= self.usd
995
+ )
996
+
997
+ def _refuse(self, function: str, spend: Spend) -> BudgetExceeded:
998
+ _core.emit(
999
+ "llm.budget_exceeded",
1000
+ function,
1001
+ budget=self.name,
1002
+ scope=self.per,
1003
+ tokens=spend.tokens,
1004
+ usd=spend.usd,
1005
+ )
1006
+ limits = []
1007
+ if self.tokens is not None:
1008
+ limits.append(f"{spend.tokens}/{self.tokens} tokens")
1009
+ if self.usd is not None:
1010
+ limits.append(f"${spend.usd:.4f}/${self.usd:g}")
1011
+ return BudgetExceeded(
1012
+ f"budget {self.name!r} ({self.per}) is used up: {', '.join(limits)}",
1013
+ budget=self.name,
1014
+ scope=self.per,
1015
+ tokens=spend.tokens,
1016
+ usd=spend.usd,
1017
+ limit_tokens=self.tokens,
1018
+ limit_usd=self.usd,
1019
+ )
1020
+
1021
+ def _check(self, scope: str, function: str) -> None:
1022
+ spend = self._read(scope)
1023
+ if self._over(spend):
1024
+ raise self._refuse(function, spend)
1025
+
1026
+ def _add(self, scope: str, usage: Usage | None) -> Spend:
1027
+ if usage is None:
1028
+ return self._read(scope)
1029
+ usd = _cost(usage, self.prices, self.model) if self.usd is not None or self.prices else 0.0
1030
+ tokens, total_usd = self.backend.add(scope, usage.total_tokens, usd, self.period)
1031
+ return Spend(tokens, total_usd)
1032
+
1033
+ def record(self, response: Any, *, key: Any = None) -> Spend:
1034
+ """Add a response's (or a `Usage`'s) tokens to the current scope by hand.
1035
+
1036
+ Use it for streamed responses, whose usage arrives with the last chunk.
1037
+
1038
+ Args:
1039
+ response: A response, a usage mapping, a `Usage` or ``(input, output)``.
1040
+ key: The key, for ``per="key"`` budgets.
1041
+
1042
+ Returns:
1043
+ The scope's spend after adding.
1044
+
1045
+ Raises:
1046
+ RuntimeError: For a run/chain budget outside a run.
1047
+ ValueError: For a ``per="key"`` budget without ``key=``.
1048
+ """
1049
+ if self.per == "key" and key is None:
1050
+ raise ValueError('record() on a per="key" budget needs key=')
1051
+ usage = _usage_of(response, self.usage) if self.usage else _coerce_usage(response)
1052
+ return self._add(self._scope_key((), {}, key if self.per == "key" else _MISSING), usage)
1053
+
1054
+ def spent(self, *, key: Any = None) -> Spend:
1055
+ """Spend in the current scope (for ``per="key"``, of ``key``)."""
1056
+ if self.per == "key" and key is None:
1057
+ raise ValueError('spent() on a per="key" budget needs key=')
1058
+ return self._read(self._scope_key((), {}, key if self.per == "key" else _MISSING))
1059
+
1060
+ def exhausted(self, *, key: Any = None) -> bool:
1061
+ """True when the next call in the current scope would be refused."""
1062
+ return self._over(self.spent(key=key))
1063
+
1064
+ def reset(self, *, key: Any = None) -> None:
1065
+ """Forget the current scope's spend (for ``per="key"``, of ``key``)."""
1066
+ if self.per == "key" and key is None:
1067
+ raise ValueError('reset() on a per="key" budget needs key=')
1068
+ self.backend.delete(self._scope_key((), {}, key if self.per == "key" else _MISSING))
1069
+
1070
+ # -- decorator ---------------------------------------------------------------
1071
+ def __call__(self, func: Callable[P, R]) -> Callable[P, R]:
1072
+ """Decorate a function making LLM calls (sync or async)."""
1073
+ label = _core.qualname(func)
1074
+ chain = self.per == "chain"
1075
+ shared = self._shared
1076
+
1077
+ if _core.is_async(func):
1078
+ afunc = cast("Callable[..., Awaitable[Any]]", func)
1079
+
1080
+ async def offload(call: Callable[..., T], *args: Any) -> T:
1081
+ return await asyncio.to_thread(call, *args) if shared else call(*args)
1082
+
1083
+ @functools.wraps(func)
1084
+ async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
1085
+ opened = self._open_run() if chain and self._id not in _RUNS.get() else None
1086
+ try:
1087
+ scope = self._scope_key(args, kwargs, _MISSING)
1088
+ await offload(self._check, scope, label)
1089
+ result = await afunc(*args, **kwargs)
1090
+ await offload(self._add, scope, _usage_of(result, self.usage))
1091
+ return result
1092
+ finally:
1093
+ if opened is not None:
1094
+ await offload(self._close_run, *opened)
1095
+
1096
+ setattr(async_wrapper, _LAYER_ATTR, ("budget", self._settings()))
1097
+ return cast("Callable[P, R]", async_wrapper)
1098
+
1099
+ @functools.wraps(func)
1100
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
1101
+ opened = self._open_run() if chain and self._id not in _RUNS.get() else None
1102
+ try:
1103
+ scope = self._scope_key(args, kwargs, _MISSING)
1104
+ self._check(scope, label)
1105
+ result = func(*args, **kwargs)
1106
+ self._add(scope, _usage_of(result, self.usage))
1107
+ return result
1108
+ finally:
1109
+ if opened is not None:
1110
+ self._close_run(*opened)
1111
+
1112
+ setattr(wrapper, _LAYER_ATTR, ("budget", self._settings()))
1113
+ return wrapper
1114
+
1115
+ def __repr__(self) -> str:
1116
+ limits = [f"tokens={self.tokens}"] if self.tokens is not None else []
1117
+ limits += [f"usd={self.usd:g}"] if self.usd is not None else []
1118
+ return f"Budget({self.name!r}, {', '.join(limits)}, per={self.per!r})"
1119
+
1120
+
1121
+ _MISSING: Any = object()
1122
+
1123
+
1124
+ def budget(
1125
+ *,
1126
+ tokens: int | None = None,
1127
+ usd: float | None = None,
1128
+ per: Scope = "total",
1129
+ key: Callable[..., Hashable] | None = None,
1130
+ period: float | None = None,
1131
+ prices: Prices | None = None,
1132
+ model: str | None = None,
1133
+ usage: UsageReader | None = None,
1134
+ name: str = "budget",
1135
+ backend: BudgetBackend | None = None,
1136
+ ) -> Budget:
1137
+ """Build a `Budget`; ``@budget(tokens=50_000, per="key", key=...)`` decorates directly.
1138
+
1139
+ Keep the returned object when you want to inspect or reset it (``spend =
1140
+ budget(...)``, then ``@spend``). See `Budget` for every argument.
1141
+
1142
+ Example:
1143
+ ```python
1144
+ from python_wrap.llm import BudgetExceeded, budget
1145
+
1146
+ @budget(tokens=100, per="key", key=lambda user, prompt: user)
1147
+ def ask(user: str, prompt: str) -> dict[str, object]:
1148
+ return {"usage": {"input_tokens": 60, "output_tokens": 40}}
1149
+
1150
+ ask("ann", "hi")
1151
+ ask("bob", "hi") # bob has his own allowance
1152
+ try:
1153
+ ask("ann", "again")
1154
+ except BudgetExceeded:
1155
+ pass
1156
+ else:
1157
+ raise AssertionError("ann is over budget")
1158
+ ```
1159
+ """
1160
+ return Budget(
1161
+ tokens=tokens,
1162
+ usd=usd,
1163
+ per=per,
1164
+ key=key,
1165
+ period=period,
1166
+ prices=prices,
1167
+ model=model,
1168
+ usage=usage,
1169
+ name=name,
1170
+ backend=backend,
1171
+ )
1172
+
1173
+
1174
+ # ------------------------------------------------------------------ token rate limit
1175
+
1176
+
1177
+ def _text_len(value: Any) -> int:
1178
+ if isinstance(value, str):
1179
+ return len(value)
1180
+ if isinstance(value, Mapping):
1181
+ return sum(_text_len(value.get(name)) for name in ("content", "text"))
1182
+ if isinstance(value, (list, tuple)):
1183
+ return sum(_text_len(item) for item in value)
1184
+ content = getattr(value, "content", None)
1185
+ return _text_len(content) if content is not None else 0
1186
+
1187
+
1188
+ def estimate_tokens(*args: Any, **kwargs: Any) -> int:
1189
+ """A dependency-free token estimate for a request: about four characters per token.
1190
+
1191
+ Counts the text in ``messages``, ``prompt``, ``input`` and ``system`` keyword
1192
+ arguments and positional strings, plus the requested output allowance
1193
+ (``max_tokens``, ``max_output_tokens`` or ``max_completion_tokens``). Pass your own
1194
+ ``estimate=`` (a real tokenizer) to `token_rate_limit` when precision matters.
1195
+
1196
+ Returns:
1197
+ The estimated total tokens (at least 1).
1198
+ """
1199
+ chars = sum(_text_len(kwargs.get(name)) for name in ("messages", "prompt", "input", "system"))
1200
+ chars += sum(_text_len(arg) for arg in args if isinstance(arg, (str, list, tuple)))
1201
+ output = 0
1202
+ for name in ("max_tokens", "max_output_tokens", "max_completion_tokens"):
1203
+ value = _int(kwargs.get(name))
1204
+ if value is not None:
1205
+ output = max(value, 0)
1206
+ break
1207
+ return max(1, math.ceil(chars / 4) + output)
1208
+
1209
+
1210
+ class TokenRateLimiter:
1211
+ """A tokens-per-minute limit for LLM calls; build it with `token_rate_limit`.
1212
+
1213
+ A token bucket holding up to ``tokens_per_minute`` tokens, refilled continuously.
1214
+ Each call reserves its estimate before it starts; when the call returns, the
1215
+ reservation is replaced by the real usage (refunding or charging the difference),
1216
+ and a failed call is refunded. A request larger than the whole bucket is admitted
1217
+ when the bucket is full. Reads time through ``python_wrap._core``, so
1218
+ `python_wrap.testing.fake_clock` controls it; ``disable_rate_limits()`` bypasses it.
1219
+
1220
+ Attributes:
1221
+ tokens_per_minute: The limit.
1222
+ name: Used in events and errors.
1223
+ """
1224
+
1225
+ def __reduce__(self) -> Any:
1226
+ _core.refuse_pickle(self)
1227
+
1228
+ def __init__(
1229
+ self,
1230
+ tokens_per_minute: int,
1231
+ *,
1232
+ estimate: Callable[..., int] | int | None = None,
1233
+ usage: UsageReader | None = None,
1234
+ block: bool = True,
1235
+ max_wait: float | None = None,
1236
+ name: str = "tokens",
1237
+ store: Any = None,
1238
+ ) -> None:
1239
+ if (
1240
+ isinstance(tokens_per_minute, bool)
1241
+ or not isinstance(tokens_per_minute, int)
1242
+ or tokens_per_minute < 1
1243
+ ):
1244
+ raise ValueError(
1245
+ f"tokens_per_minute must be an integer >= 1, got {tokens_per_minute!r}"
1246
+ )
1247
+ if max_wait is not None and (not math.isfinite(max_wait) or max_wait < 0):
1248
+ raise ValueError(f"max_wait must be >= 0, got {max_wait!r}")
1249
+ if isinstance(estimate, int) and (isinstance(estimate, bool) or estimate < 0):
1250
+ raise ValueError(f"estimate must be >= 0, got {estimate!r}")
1251
+ self.tokens_per_minute = tokens_per_minute
1252
+ self.name = name
1253
+ self.block, self.max_wait, self.usage = block, max_wait, usage
1254
+ fixed = estimate if isinstance(estimate, int) else None
1255
+ self._estimate: Callable[..., int] = (
1256
+ (lambda *a, **k: fixed)
1257
+ if fixed is not None
1258
+ else (estimate if callable(estimate) else estimate_tokens)
1259
+ )
1260
+ self._capacity = float(tokens_per_minute)
1261
+ self._rate = tokens_per_minute / 60.0
1262
+ self._level = self._capacity
1263
+ self._stamp: float | None = None
1264
+ self._blocked = 0.0 # monotonic time until which a provider asked us to stop
1265
+ self._store = store
1266
+ self._lock = _fork.ForkSafeLock()
1267
+ setattr(
1268
+ self,
1269
+ _LAYER_ATTR,
1270
+ (
1271
+ "limiter",
1272
+ {
1273
+ "llm": "token_limit",
1274
+ "name": name,
1275
+ "tokens_per_minute": tokens_per_minute,
1276
+ "shared": store is not None,
1277
+ },
1278
+ ),
1279
+ )
1280
+
1281
+ def _refill(self) -> None:
1282
+ now = _core.monotonic()
1283
+ if self._stamp is not None:
1284
+ elapsed = max(now - self._stamp, 0.0) # a clock swapped in tests may step back
1285
+ self._level = min(self._capacity, self._level + elapsed * self._rate)
1286
+ self._stamp = now
1287
+
1288
+ @property
1289
+ def available(self) -> float:
1290
+ """Tokens that could be reserved right now (negative while in debt)."""
1291
+ if self._store is not None:
1292
+ return float(self._store.level(self._capacity, self._rate))
1293
+ with self._lock:
1294
+ self._refill()
1295
+ return self._level
1296
+
1297
+ def try_reserve(self, tokens: int) -> float:
1298
+ """Reserve ``tokens`` if possible: 0.0 when reserved, else seconds to wait."""
1299
+ if self._store is not None:
1300
+ return float(self._store.reserve(tokens, self._capacity, self._rate))
1301
+ with self._lock:
1302
+ self._refill()
1303
+ if self._blocked > _core.monotonic():
1304
+ return self._blocked - _core.monotonic()
1305
+ need = min(float(tokens), self._capacity)
1306
+ if self._level + 1e-6 >= need: # waiting exactly retry_after admits (float slack)
1307
+ self._level -= tokens
1308
+ return 0.0
1309
+ return (need - self._level) / self._rate
1310
+
1311
+ def _force(self, tokens: int) -> None:
1312
+ if self._store is not None:
1313
+ self._store.force(tokens, self._capacity, self._rate)
1314
+ return
1315
+ with self._lock:
1316
+ self._refill()
1317
+ self._level -= tokens
1318
+
1319
+ def settle(self, reserved: int, actual: int) -> None:
1320
+ """Replace a reservation of ``reserved`` tokens by the ``actual`` usage."""
1321
+ if self._store is not None:
1322
+ self._store.settle(reserved, actual, self._capacity, self._rate)
1323
+ return
1324
+ with self._lock:
1325
+ self._refill()
1326
+ self._level = min(self._capacity, self._level + reserved - actual)
1327
+
1328
+ def _refused(self, wait: float, label: str) -> RateLimitExceeded:
1329
+ _core.emit("rate_limit.rejected", self.name, retry_after=wait)
1330
+ return RateLimitExceeded(
1331
+ f"token rate limit {self.name!r} ({self.tokens_per_minute}/min) exceeded for {label}",
1332
+ retry_after=wait,
1333
+ )
1334
+
1335
+ def _waits(self, waited: float, wait: float) -> bool:
1336
+ return self.block and (self.max_wait is None or waited + wait <= self.max_wait)
1337
+
1338
+ def acquire(self, tokens: int, *, label: str = "call") -> None:
1339
+ """Reserve ``tokens``, waiting (``block=True``) or raising `RateLimitExceeded`."""
1340
+ waited = 0.0
1341
+ while not _core.overrides.disable_rate_limits:
1342
+ wait = self.try_reserve(tokens)
1343
+ if wait <= 0:
1344
+ break
1345
+ if not self._waits(waited, wait):
1346
+ raise self._refused(wait, label)
1347
+ if _core.overrides.no_sleep:
1348
+ self._force(tokens)
1349
+ break
1350
+ _core.sleep(wait)
1351
+ waited += wait
1352
+ _core.emit("rate_limit.waited", self.name, seconds=wait)
1353
+
1354
+ async def aacquire(self, tokens: int, *, label: str = "call") -> None:
1355
+ """Async `acquire`: waits with ``asyncio`` instead of blocking the thread."""
1356
+ waited = 0.0
1357
+ while not _core.overrides.disable_rate_limits:
1358
+ wait = await self._areserve(tokens)
1359
+ if wait <= 0:
1360
+ break
1361
+ if not self._waits(waited, wait):
1362
+ raise self._refused(wait, label)
1363
+ if _core.overrides.no_sleep:
1364
+ await self._aforce(tokens)
1365
+ await asyncio.sleep(0)
1366
+ break
1367
+ await _core.async_sleep(wait)
1368
+ waited += wait
1369
+ _core.emit("rate_limit.waited", self.name, seconds=wait)
1370
+
1371
+ async def _areserve(self, tokens: int) -> float:
1372
+ store = self._store
1373
+ if store is None:
1374
+ return self.try_reserve(tokens)
1375
+ if hasattr(store, "areserve"):
1376
+ return float(await store.areserve(tokens, self._capacity, self._rate))
1377
+ return await asyncio.to_thread(self.try_reserve, tokens)
1378
+
1379
+ async def _aforce(self, tokens: int) -> None:
1380
+ store = self._store
1381
+ if store is not None and hasattr(store, "aforce"):
1382
+ await store.aforce(tokens, self._capacity, self._rate)
1383
+ elif store is not None:
1384
+ await asyncio.to_thread(self._force, tokens)
1385
+ else:
1386
+ self._force(tokens)
1387
+
1388
+ async def _asettle(self, reserved: int, actual: int) -> None:
1389
+ store = self._store
1390
+ if store is not None and hasattr(store, "asettle"):
1391
+ await store.asettle(reserved, actual, self._capacity, self._rate)
1392
+ elif store is not None:
1393
+ await asyncio.to_thread(self.settle, reserved, actual)
1394
+ else:
1395
+ self.settle(reserved, actual)
1396
+
1397
+ def observe_headers(self, headers: Any) -> Any:
1398
+ """Update the bucket from a provider's rate-limit headers (sync).
1399
+
1400
+ The provider's ``remaining`` token count lowers the bucket (never raises it), and
1401
+ ``Retry-After`` (or the reset time when nothing remains) blocks further requests
1402
+ until then. With a shared ``store=`` the block applies to every worker. See
1403
+ `python_wrap.llm_shared.parse_rate_limit_headers` for the headers understood.
1404
+
1405
+ Returns:
1406
+ The parsed `python_wrap.llm_shared.RateLimitHint`.
1407
+ """
1408
+ from python_wrap.llm_shared import parse_rate_limit_headers
1409
+
1410
+ if self._store is not None:
1411
+ return self._store.observe_headers(headers, capacity=self._capacity, rate=self._rate)
1412
+ hint = parse_rate_limit_headers(headers)
1413
+ block = hint.block_seconds
1414
+ with self._lock:
1415
+ self._refill()
1416
+ if hint.remaining_tokens is not None:
1417
+ self._level = min(self._level, hint.remaining_tokens)
1418
+ if block is not None and block > 0:
1419
+ self._blocked = max(self._blocked, _core.monotonic() + block)
1420
+ return hint
1421
+
1422
+ async def aobserve_headers(self, headers: Any) -> Any:
1423
+ """Async `observe_headers`; shared stores are updated without blocking the loop."""
1424
+ store = self._store
1425
+ if store is not None and hasattr(store, "aobserve_headers"):
1426
+ return await store.aobserve_headers(headers, capacity=self._capacity, rate=self._rate)
1427
+ return await asyncio.to_thread(self.observe_headers, headers)
1428
+
1429
+ @staticmethod
1430
+ def _error_headers(exc: BaseException) -> Any:
1431
+ headers = _field(exc, "headers")
1432
+ if headers is None:
1433
+ headers = _field(_field(exc, "response"), "headers")
1434
+ return headers
1435
+
1436
+ def _learn(self, exc: BaseException) -> None:
1437
+ """Feed an error's response headers (a 429's, usually) to `observe_headers`."""
1438
+ headers = self._error_headers(exc)
1439
+ if headers is not None:
1440
+ with contextlib.suppress(Exception): # a broken store must not mask the real error
1441
+ self.observe_headers(headers)
1442
+
1443
+ async def _alearn(self, exc: BaseException) -> None:
1444
+ headers = self._error_headers(exc)
1445
+ if headers is not None:
1446
+ with contextlib.suppress(Exception):
1447
+ await self.aobserve_headers(headers)
1448
+
1449
+ def _actual(self, result: Any, reserved: int) -> int:
1450
+ usage = _usage_of(result, self.usage)
1451
+ return reserved if usage is None else usage.total_tokens
1452
+
1453
+ def __call__(self, func: Callable[P, R]) -> Callable[P, R]:
1454
+ """Decorate a sync or async function making LLM calls."""
1455
+ label = _core.qualname(func)
1456
+
1457
+ if _core.is_async(func):
1458
+ afunc = cast("Callable[..., Awaitable[Any]]", func)
1459
+
1460
+ @functools.wraps(func)
1461
+ async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
1462
+ if _core.overrides.disable_rate_limits:
1463
+ return await afunc(*args, **kwargs)
1464
+ cost = max(0, int(self._estimate(*args, **kwargs)))
1465
+ await self.aacquire(cost, label=label)
1466
+ try:
1467
+ result = await afunc(*args, **kwargs)
1468
+ except BaseException as exc:
1469
+ await self._asettle(cost, 0)
1470
+ await self._alearn(exc)
1471
+ raise
1472
+ await self._asettle(cost, self._actual(result, cost))
1473
+ return result
1474
+
1475
+ setattr(async_wrapper, _LAYER_ATTR, getattr(self, _LAYER_ATTR))
1476
+ return cast("Callable[P, R]", async_wrapper)
1477
+
1478
+ @functools.wraps(func)
1479
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
1480
+ if _core.overrides.disable_rate_limits:
1481
+ return func(*args, **kwargs)
1482
+ cost = max(0, int(self._estimate(*args, **kwargs)))
1483
+ self.acquire(cost, label=label)
1484
+ try:
1485
+ result = func(*args, **kwargs)
1486
+ except BaseException as exc:
1487
+ self.settle(cost, 0)
1488
+ self._learn(exc)
1489
+ raise
1490
+ self.settle(cost, self._actual(result, cost))
1491
+ return result
1492
+
1493
+ setattr(wrapper, _LAYER_ATTR, getattr(self, _LAYER_ATTR))
1494
+ return wrapper
1495
+
1496
+ def __repr__(self) -> str:
1497
+ return f"TokenRateLimiter({self.name!r}, {self.tokens_per_minute}/min)"
1498
+
1499
+
1500
+ def token_rate_limit(
1501
+ tokens_per_minute: int,
1502
+ *,
1503
+ estimate: Callable[..., int] | int | None = None,
1504
+ usage: UsageReader | None = None,
1505
+ block: bool = True,
1506
+ max_wait: float | None = None,
1507
+ name: str = "tokens",
1508
+ store: Any = None,
1509
+ ) -> TokenRateLimiter:
1510
+ """Limit LLM calls to ``tokens_per_minute``, reserving estimates up front.
1511
+
1512
+ Args:
1513
+ tokens_per_minute: Bucket size and refill per minute.
1514
+ estimate: ``estimate(*args, **kwargs) -> int`` tokens for a call, or a fixed
1515
+ number; `estimate_tokens` (about four characters per token plus
1516
+ ``max_tokens``) by default.
1517
+ usage: Reads the real usage from a result when `read_usage` cannot; without
1518
+ any usage the estimate stands.
1519
+ block: Wait for tokens (emitting ``rate_limit.waited``); False raises
1520
+ `RateLimitExceeded` (with ``retry_after``) instead.
1521
+ max_wait: With ``block=True``, the longest total wait before raising.
1522
+ name: Used in events and errors.
1523
+ store: A shared window (`python_wrap.llm_shared.SQLiteTokenWindow`,
1524
+ `RedisTokenWindow`, `AsyncRedisTokenWindow`) so every worker process draws
1525
+ from one bucket and backs off together. Every worker must use the same
1526
+ ``tokens_per_minute``. Errors that carry rate-limit headers update it (see
1527
+ `TokenRateLimiter.observe_headers`).
1528
+
1529
+ Returns:
1530
+ A `TokenRateLimiter`, usable as a decorator (one instance can guard several
1531
+ functions that share a provider quota).
1532
+
1533
+ Example:
1534
+ ```python
1535
+ from python_wrap.errors import RateLimitExceeded
1536
+ from python_wrap.llm import token_rate_limit
1537
+
1538
+ limit = token_rate_limit(1000, estimate=600, block=False)
1539
+
1540
+ @limit
1541
+ def complete(prompt: str) -> dict[str, object]:
1542
+ return {"usage": {"input_tokens": 100, "output_tokens": 100}}
1543
+
1544
+ complete("a") # reserves 600, settles at the real 200
1545
+ complete("b")
1546
+ try:
1547
+ complete("c")
1548
+ except RateLimitExceeded as exc:
1549
+ assert exc.retry_after > 0
1550
+ ```
1551
+ """
1552
+ return TokenRateLimiter(
1553
+ tokens_per_minute,
1554
+ estimate=estimate,
1555
+ usage=usage,
1556
+ block=block,
1557
+ max_wait=max_wait,
1558
+ name=name,
1559
+ store=store,
1560
+ )
1561
+
1562
+
1563
+ # ------------------------------------------------------------- request keys (cache)
1564
+
1565
+
1566
+ def _plain(value: Any, depth: int = 0) -> Any:
1567
+ """A JSON-compatible, order-independent view of a request value."""
1568
+ if depth > 32:
1569
+ return repr(value)
1570
+ if value is None or isinstance(value, (str, bool, int, float)):
1571
+ return value
1572
+ if isinstance(value, Mapping):
1573
+ return {str(k): _plain(v, depth + 1) for k, v in value.items()}
1574
+ if isinstance(value, (list, tuple)):
1575
+ return [_plain(v, depth + 1) for v in value]
1576
+ if isinstance(value, (set, frozenset)):
1577
+ return sorted((_plain(v, depth + 1) for v in value), key=repr)
1578
+ dump = getattr(value, "model_dump", None)
1579
+ if callable(dump):
1580
+ try:
1581
+ return _plain(dump(), depth + 1)
1582
+ except Exception:
1583
+ return repr(value)
1584
+ if dataclasses.is_dataclass(value) and not isinstance(value, type):
1585
+ return _plain(dataclasses.asdict(value), depth + 1)
1586
+ return repr(value)
1587
+
1588
+
1589
+ def _hash(value: Any) -> str:
1590
+ text = json.dumps(_plain(value), sort_keys=True, separators=(",", ":"), ensure_ascii=False)
1591
+ return hashlib.sha256(text.encode()).hexdigest()
1592
+
1593
+
1594
+ def _request(
1595
+ signature: inspect.Signature | None, args: tuple[Any, ...], kwargs: dict[str, Any]
1596
+ ) -> dict[str, Any]:
1597
+ if signature is None:
1598
+ return {"args": list(args), **kwargs}
1599
+ bound = signature.bind(*args, **kwargs)
1600
+ bound.apply_defaults()
1601
+ request: dict[str, Any] = {}
1602
+ for name, value in bound.arguments.items():
1603
+ kind = signature.parameters[name].kind
1604
+ if kind is inspect.Parameter.VAR_KEYWORD:
1605
+ request.update(value)
1606
+ elif name not in ("self", "cls"):
1607
+ request[name] = value
1608
+ return request
1609
+
1610
+
1611
+ def _signature(func: Callable[..., Any]) -> inspect.Signature | None:
1612
+ try:
1613
+ return inspect.signature(func)
1614
+ except (TypeError, ValueError):
1615
+ return None
1616
+
1617
+
1618
+ _PROMPT_FIELDS = ("messages", "prompt", "input")
1619
+
1620
+
1621
+ def _prompt_text(request: Mapping[str, Any]) -> str:
1622
+ parts: list[str] = []
1623
+
1624
+ def walk(value: Any) -> None:
1625
+ if isinstance(value, str):
1626
+ parts.append(value)
1627
+ elif isinstance(value, Mapping):
1628
+ for name in ("content", "text"):
1629
+ walk(value.get(name))
1630
+ elif isinstance(value, (list, tuple)):
1631
+ for item in value:
1632
+ walk(item)
1633
+ elif getattr(value, "content", None) is not None:
1634
+ walk(value.content)
1635
+
1636
+ for name in _PROMPT_FIELDS:
1637
+ walk(request.get(name))
1638
+ return "\n".join(parts)
1639
+
1640
+
1641
+ def _cosine(a: Sequence[float], b: Sequence[float]) -> float:
1642
+ if len(a) != len(b) or not a:
1643
+ return -1.0
1644
+ dot = sum(x * y for x, y in zip(a, b, strict=True))
1645
+ norm = math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b))
1646
+ return dot / norm if norm else -1.0
1647
+
1648
+
1649
+ class _LRU:
1650
+ """The default `llm_cache` store: a thread-safe LRU dict."""
1651
+
1652
+ def __init__(self, maxsize: int | None) -> None:
1653
+ self.maxsize = maxsize
1654
+ self._data: OrderedDict[Hashable, Any] = OrderedDict()
1655
+ self._lock = _fork.ForkSafeLock()
1656
+
1657
+ def get(self, key: Hashable, /) -> Any:
1658
+ with self._lock:
1659
+ entry = self._data.get(key)
1660
+ if entry is not None:
1661
+ self._data.move_to_end(key)
1662
+ return entry
1663
+
1664
+ def set(self, key: Hashable, entry: Any, ttl: float | None, /) -> None:
1665
+ with self._lock:
1666
+ self._data[key] = entry
1667
+ self._data.move_to_end(key)
1668
+ while self.maxsize is not None and len(self._data) > self.maxsize:
1669
+ self._data.popitem(last=False)
1670
+
1671
+ def delete(self, key: Hashable, /) -> bool:
1672
+ with self._lock:
1673
+ return self._data.pop(key, None) is not None
1674
+
1675
+ def clear(self) -> None:
1676
+ with self._lock:
1677
+ self._data.clear()
1678
+
1679
+ def __len__(self) -> int:
1680
+ return len(self._data)
1681
+
1682
+
1683
+ async def _maybe_await(value: Any) -> Any:
1684
+ return await value if inspect.isawaitable(value) else value
1685
+
1686
+
1687
+ class _Index:
1688
+ """Recent prompt embeddings for ``similarity=`` lookups (in process, bounded)."""
1689
+
1690
+ def __init__(self, maxsize: int) -> None:
1691
+ self.maxsize = maxsize
1692
+ self._rows: OrderedDict[str, tuple[str, tuple[float, ...]]] = OrderedDict()
1693
+ self._lock = _fork.ForkSafeLock()
1694
+
1695
+ def add(self, key: str, group: str, vector: Sequence[float]) -> None:
1696
+ with self._lock:
1697
+ self._rows[key] = (group, tuple(float(x) for x in vector))
1698
+ self._rows.move_to_end(key)
1699
+ while len(self._rows) > self.maxsize:
1700
+ self._rows.popitem(last=False)
1701
+
1702
+ def best(self, group: str, vector: Sequence[float], threshold: float) -> str | None:
1703
+ with self._lock:
1704
+ rows = list(self._rows.items())
1705
+ found, score = None, threshold
1706
+ for key, (row_group, row) in rows:
1707
+ if row_group == group:
1708
+ similarity = _cosine(vector, row)
1709
+ if similarity >= score:
1710
+ found, score = key, similarity
1711
+ return found
1712
+
1713
+ def discard(self, key: str) -> None:
1714
+ with self._lock:
1715
+ self._rows.pop(key, None)
1716
+
1717
+
1718
+ _DEFAULT_IGNORE = ("stream", "timeout", "extra_headers", "user", "metadata", "request_id")
1719
+
1720
+
1721
+ def llm_cache(
1722
+ *,
1723
+ ttl: float | None = 3600.0,
1724
+ store: Any = None,
1725
+ maxsize: int = 1024,
1726
+ key: Callable[..., Hashable] | None = None,
1727
+ ignore: Sequence[str] = _DEFAULT_IGNORE,
1728
+ similarity: Callable[[str], Sequence[float]] | None = None,
1729
+ threshold: float = 0.95,
1730
+ ) -> _Decorator[..., Any]:
1731
+ """Cache LLM responses keyed on the request: model, messages or prompt, and params.
1732
+
1733
+ The key is a SHA-256 of the call's bound arguments (``**kwargs`` flattened, dicts
1734
+ order-independent, pydantic models and dataclasses dumped), minus the names in
1735
+ ``ignore`` (transport options such as ``timeout`` or ``user``). Calls with
1736
+ ``stream=True`` bypass the cache, as do failures and ``None`` results, which are
1737
+ never stored. ``disable_caching()`` turns it off in tests. Emits ``cache.hit`` and
1738
+ ``cache.miss``.
1739
+
1740
+ Semantic matching: pass ``similarity=embed``, a function turning the prompt text into
1741
+ a vector (your own embedding call; nothing is imported). On an exact miss, the
1742
+ prompt's vector is compared (cosine) with recent prompts that used the **same**
1743
+ model and parameters, and an entry at least ``threshold`` similar is served. The
1744
+ vectors are kept in process (the last ``maxsize``); the entries live in ``store``.
1745
+
1746
+ Args:
1747
+ ttl: Seconds an entry stays valid (wall clock), or None for no expiry.
1748
+ store: A `CacheStore` (sync methods) or `AsyncCacheStore` (async functions only),
1749
+ e.g. ``RedisStore(client, "llm:")``; a thread-safe in-process LRU of
1750
+ ``maxsize`` entries by default.
1751
+ maxsize: Size of the default store and of the similarity index.
1752
+ key: ``key(*args, **kwargs)`` replaces the derived key.
1753
+ ignore: Argument names left out of the key.
1754
+ similarity: Optional embedding function for semantic matches.
1755
+ threshold: Minimum cosine similarity for a semantic match (0-1].
1756
+
1757
+ Returns:
1758
+ A decorator for sync or async functions.
1759
+
1760
+ Raises:
1761
+ ValueError: For a non-positive ``ttl``/``maxsize`` or a threshold outside (0, 1].
1762
+
1763
+ Example:
1764
+ ```python
1765
+ from python_wrap.llm import llm_cache
1766
+
1767
+ calls = []
1768
+
1769
+ @llm_cache(ttl=600)
1770
+ def complete(*, model: str, messages: list[dict[str, str]], temperature: float = 0) -> str:
1771
+ calls.append(model)
1772
+ return "4"
1773
+
1774
+ question = [{"role": "user", "content": "2+2?"}]
1775
+ assert complete(model="m-1", messages=question) == "4"
1776
+ assert complete(model="m-1", messages=question, temperature=0) == "4"
1777
+ assert calls == ["m-1"] # the second call was served from the cache
1778
+ ```
1779
+ """
1780
+ if ttl is not None and (not math.isfinite(ttl) or ttl <= 0):
1781
+ raise ValueError(f"ttl must be positive or None, got {ttl!r}")
1782
+ if isinstance(maxsize, bool) or not isinstance(maxsize, int) or maxsize < 1:
1783
+ raise ValueError(f"maxsize must be an integer >= 1, got {maxsize!r}")
1784
+ if not 0 < threshold <= 1:
1785
+ raise ValueError(f"threshold must be in (0, 1], got {threshold!r}")
1786
+ skip = frozenset(ignore)
1787
+ settings = {
1788
+ "llm": "cache",
1789
+ "ttl": ttl,
1790
+ "bounded": True,
1791
+ "self_in_key": False,
1792
+ "similarity": similarity is not None,
1793
+ }
1794
+
1795
+ def decorate(func: Callable[P, R]) -> Callable[P, R]:
1796
+ backing = store if store is not None else _LRU(maxsize)
1797
+ index = _Index(maxsize) if similarity is not None else None
1798
+ signature = _signature(func)
1799
+ label = _core.qualname(func)
1800
+ prefix = f"llm:{func.__module__}.{label}:"
1801
+
1802
+ def plan(args: tuple[Any, ...], kwargs: dict[str, Any]) -> tuple[str, str, str] | None:
1803
+ """``(key, group, prompt)`` for a cacheable call, None to bypass the cache."""
1804
+ if _core.overrides.disable_caching:
1805
+ return None
1806
+ try:
1807
+ request = _request(signature, args, kwargs)
1808
+ except TypeError:
1809
+ return None # let the call raise its own argument error
1810
+ if request.get("stream") is True:
1811
+ return None
1812
+ request = {k: v for k, v in request.items() if k not in skip}
1813
+ exact = prefix + (digest(key(*args, **kwargs)) if key is not None else _hash(request))
1814
+ group = _hash({k: v for k, v in request.items() if k not in _PROMPT_FIELDS})
1815
+ return exact, group, _prompt_text(request)
1816
+
1817
+ def fresh(entry: Any) -> bool:
1818
+ return (
1819
+ isinstance(entry, tuple)
1820
+ and len(entry) == 2
1821
+ and (entry[0] is None or _core.wall_time() < entry[0])
1822
+ )
1823
+
1824
+ def entry_for(value: Any) -> tuple[float | None, Any]:
1825
+ return (None if ttl is None else _core.wall_time() + ttl, value)
1826
+
1827
+ if _core.is_async(func):
1828
+ afunc = cast("Callable[..., Awaitable[Any]]", func)
1829
+
1830
+ async def alookup(found: str) -> Any:
1831
+ entry = await _maybe_await(backing.get(found))
1832
+ return entry[1] if fresh(entry) else None
1833
+
1834
+ @functools.wraps(func)
1835
+ async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
1836
+ planned = plan(args, kwargs)
1837
+ if planned is None:
1838
+ return await afunc(*args, **kwargs)
1839
+ exact, group, prompt = planned
1840
+ value = await alookup(exact)
1841
+ vector: Sequence[float] | None = None
1842
+ if value is None and index is not None and similarity is not None:
1843
+ vector = cast("Sequence[float]", await _maybe_await(similarity(prompt)))
1844
+ near = index.best(group, vector, threshold)
1845
+ if near is not None:
1846
+ value = await alookup(near)
1847
+ if value is None:
1848
+ index.discard(near)
1849
+ if value is not None:
1850
+ _core.emit("cache.hit", label)
1851
+ return value
1852
+ _core.emit("cache.miss", label)
1853
+ result = await afunc(*args, **kwargs)
1854
+ if result is not None:
1855
+ await _maybe_await(backing.set(exact, entry_for(result), ttl))
1856
+ if index is not None and vector is not None:
1857
+ index.add(exact, group, vector)
1858
+ return result
1859
+
1860
+ setattr(async_wrapper, _LAYER_ATTR, ("cache", settings))
1861
+ return cast("Callable[P, R]", async_wrapper)
1862
+
1863
+ if inspect.iscoroutinefunction(getattr(backing, "get", None)):
1864
+ raise TypeError(
1865
+ f"{label} is synchronous but the store has async methods; use a CacheStore"
1866
+ )
1867
+
1868
+ def lookup(found: str) -> Any:
1869
+ entry = backing.get(found)
1870
+ return entry[1] if fresh(entry) else None
1871
+
1872
+ @functools.wraps(func)
1873
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
1874
+ planned = plan(args, kwargs)
1875
+ if planned is None:
1876
+ return func(*args, **kwargs)
1877
+ exact, group, prompt = planned
1878
+ value = lookup(exact)
1879
+ vector: Sequence[float] | None = None
1880
+ if value is None and index is not None and similarity is not None:
1881
+ vector = similarity(prompt)
1882
+ near = index.best(group, vector, threshold)
1883
+ if near is not None:
1884
+ value = lookup(near)
1885
+ if value is None:
1886
+ index.discard(near)
1887
+ if value is not None:
1888
+ _core.emit("cache.hit", label)
1889
+ return cast(R, value)
1890
+ _core.emit("cache.miss", label)
1891
+ result = func(*args, **kwargs)
1892
+ if result is not None:
1893
+ backing.set(exact, entry_for(result), ttl)
1894
+ if index is not None and vector is not None:
1895
+ index.add(exact, group, vector)
1896
+ return result
1897
+
1898
+ setattr(wrapper, _LAYER_ATTR, ("cache", settings))
1899
+ return wrapper
1900
+
1901
+ setattr(decorate, _LAYER_ATTR, ("cache", settings))
1902
+ return decorate
1903
+
1904
+
1905
+ # ------------------------------------------------------------------- fallback chains
1906
+
1907
+
1908
+ def _falls_back(exc: BaseException) -> bool:
1909
+ return isinstance(exc, CircuitOpenError) or llm_transient(exc)
1910
+
1911
+
1912
+ def _predicate(
1913
+ on: ExceptionTypes | Callable[[BaseException], bool] | None,
1914
+ ) -> Callable[[BaseException], bool]:
1915
+ if on is None:
1916
+ return _falls_back
1917
+ if isinstance(on, (type, tuple)):
1918
+ types = on
1919
+ return lambda exc: isinstance(exc, types)
1920
+ return on
1921
+
1922
+
1923
+ def _model_name(func: Callable[..., Any]) -> str:
1924
+ model = getattr(func, "model", None)
1925
+ return model if isinstance(model, str) and model else _core.qualname(func)
1926
+
1927
+
1928
+ @overload
1929
+ def fallback_models(
1930
+ models: Sequence[Callable[P, R]],
1931
+ /,
1932
+ *,
1933
+ names: Sequence[str] | None = ...,
1934
+ on: ExceptionTypes | Callable[[BaseException], bool] | None = ...,
1935
+ breaker: bool | Mapping[str, CircuitBreaker] = ...,
1936
+ cached_answer: bool | Any = ...,
1937
+ name: str | None = ...,
1938
+ ) -> Callable[P, R]: ...
1939
+ @overload
1940
+ def fallback_models(
1941
+ models: None = None,
1942
+ /,
1943
+ *,
1944
+ backups: Sequence[Callable[..., Any]],
1945
+ names: Sequence[str] | None = ...,
1946
+ on: ExceptionTypes | Callable[[BaseException], bool] | None = ...,
1947
+ breaker: bool | Mapping[str, CircuitBreaker] = ...,
1948
+ cached_answer: bool | Any = ...,
1949
+ name: str | None = ...,
1950
+ ) -> _Decorator[..., Any]: ...
1951
+ def fallback_models(
1952
+ models: Sequence[Callable[..., Any]] | None = None,
1953
+ /,
1954
+ *,
1955
+ backups: Sequence[Callable[..., Any]] = (),
1956
+ names: Sequence[str] | None = None,
1957
+ on: ExceptionTypes | Callable[[BaseException], bool] | None = None,
1958
+ breaker: bool | Mapping[str, CircuitBreaker] = True,
1959
+ cached_answer: bool | Any = False,
1960
+ name: str | None = None,
1961
+ ) -> Any:
1962
+ """Try LLM calls in order until one succeeds: a model fallback chain.
1963
+
1964
+ Two forms: ``fallback_models([call_a, call_b, call_c])`` returns the chain as one
1965
+ callable; ``@fallback_models(backups=[call_b, call_c])`` makes the decorated
1966
+ function the primary. All entries take the same arguments and are all sync or all
1967
+ ``async def``.
1968
+
1969
+ Each entry sits behind its own `CircuitBreaker` (``breaker=True``: 5 transient
1970
+ failures open it for 30 s; refusals and bad requests are not counted), so a
1971
+ provider that is down is skipped at once instead of timing out on every call. Pass
1972
+ a mapping ``{name: CircuitBreaker}`` to supply your own (the same instance under two
1973
+ names shares one breaker per provider), or False for none.
1974
+
1975
+ An error matching ``on`` moves on to the next entry; anything else is raised at
1976
+ once. By default that is `llm_transient` errors and `CircuitOpenError`: a
1977
+ content-policy refusal or a bad request is not hidden by another model's answer.
1978
+ With ``cached_answer=True`` (or a `CacheStore`), the last successful answer for the
1979
+ same arguments is remembered and served when every entry fails. Every served call
1980
+ emits ``llm.fallback_served`` naming the model.
1981
+
1982
+ Args:
1983
+ models: The entries, primary first (list form).
1984
+ backups: The entries after the decorated function (decorator form).
1985
+ names: Model names for events and breakers; default each entry's ``model``
1986
+ attribute or qualified name.
1987
+ on: Exception type(s) or predicate that trigger the next entry.
1988
+ breaker: True, False, or a mapping of name to breaker.
1989
+ cached_answer: False, True (in-process LRU of 1024 answers) or a store.
1990
+ name: The chain's name in events and breaker names.
1991
+
1992
+ Returns:
1993
+ The chain (list form) or a decorator (decorator form).
1994
+
1995
+ Raises:
1996
+ ValueError: For an empty chain or a wrong number of names.
1997
+ TypeError: When sync and async entries are mixed.
1998
+
1999
+ Example:
2000
+ ```python
2001
+ from python_wrap.events import listening
2002
+ from python_wrap.llm import fallback_models
2003
+
2004
+ class Overloaded(Exception):
2005
+ status_code = 529
2006
+
2007
+ def big_model(prompt: str) -> str:
2008
+ raise Overloaded
2009
+
2010
+ def small_model(prompt: str) -> str:
2011
+ return f"small: {prompt}"
2012
+
2013
+ ask = fallback_models([big_model, small_model], names=["big", "small"])
2014
+ events = []
2015
+ with listening(events.append):
2016
+ assert ask("hi") == "small: hi"
2017
+ assert events[-1].fields["model"] == "small"
2018
+ assert events[-1].fields["failed"] == ("big",)
2019
+ ```
2020
+ """
2021
+ if models is None:
2022
+ if not backups:
2023
+ raise ValueError("fallback_models() needs a list of models or backups=")
2024
+ rest = list(backups)
2025
+
2026
+ def decorate(func: Callable[P, R]) -> Callable[P, R]:
2027
+ chain = _build_chain(
2028
+ [func, *rest], names, on=on, breaker=breaker, cached_answer=cached_answer, name=name
2029
+ )
2030
+ return cast("Callable[P, R]", chain)
2031
+
2032
+ return decorate
2033
+ return _build_chain(
2034
+ list(models), names, on=on, breaker=breaker, cached_answer=cached_answer, name=name
2035
+ )
2036
+
2037
+
2038
+ def _build_chain(
2039
+ models: list[Callable[..., Any]],
2040
+ names: Sequence[str] | None,
2041
+ *,
2042
+ on: ExceptionTypes | Callable[[BaseException], bool] | None,
2043
+ breaker: bool | Mapping[str, CircuitBreaker],
2044
+ cached_answer: bool | Any,
2045
+ name: str | None,
2046
+ ) -> Callable[..., Any]:
2047
+ if not models:
2048
+ raise ValueError("fallback_models() needs at least one model")
2049
+ labels = list(names) if names is not None else [_model_name(m) for m in models]
2050
+ if len(labels) != len(models):
2051
+ raise ValueError(f"got {len(labels)} names for {len(models)} models")
2052
+ kinds = {_core.is_async(m) for m in models}
2053
+ if len(kinds) > 1:
2054
+ raise TypeError("fallback_models() entries must be all sync or all async def")
2055
+ is_async = kinds == {True}
2056
+ chain_name = name or _core.qualname(models[0])
2057
+ falls_back = _predicate(on)
2058
+
2059
+ entries: list[tuple[str, Callable[..., Any]]] = []
2060
+ for label, model in zip(labels, models, strict=True):
2061
+ if breaker is True:
2062
+ guard = _llm_breaker(
2063
+ failure_threshold=5, recovery_timeout=30.0, name=f"{chain_name}:{label}"
2064
+ )
2065
+ entries.append((label, _through_breaker(guard, model, llm_transient)))
2066
+ elif isinstance(breaker, Mapping) and label in breaker:
2067
+ given = breaker[label]
2068
+ entries.append((label, functools.partial(given.call, model)))
2069
+ else:
2070
+ entries.append((label, model))
2071
+
2072
+ store: Any = None
2073
+ if cached_answer is True:
2074
+ store = _LRU(1024)
2075
+ elif cached_answer not in (False, None):
2076
+ store = cached_answer
2077
+ signature = _signature(models[0])
2078
+
2079
+ def answer_key(args: tuple[Any, ...], kwargs: dict[str, Any]) -> str | None:
2080
+ try:
2081
+ return f"llm-fallback:{chain_name}:{_hash(_request(signature, args, kwargs))}"
2082
+ except TypeError:
2083
+ return None
2084
+
2085
+ def served(label: str, index: int, failed: list[str]) -> None:
2086
+ _core.emit(
2087
+ "llm.fallback_served", chain_name, model=label, index=index, failed=tuple(failed)
2088
+ )
2089
+
2090
+ settings = {
2091
+ "llm": "fallback",
2092
+ "models": tuple(labels),
2093
+ "breakers": breaker is not False,
2094
+ "cached_answer": store is not None,
2095
+ }
2096
+
2097
+ if is_async:
2098
+
2099
+ @functools.wraps(models[0])
2100
+ async def async_chain(*args: Any, **kwargs: Any) -> Any:
2101
+ failed: list[str] = []
2102
+ last: BaseException | None = None
2103
+ for index, (label, call) in enumerate(entries):
2104
+ try:
2105
+ result = await call(*args, **kwargs)
2106
+ except Exception as exc:
2107
+ if not falls_back(exc):
2108
+ raise
2109
+ failed.append(label)
2110
+ last = exc
2111
+ continue
2112
+ if store is not None and result is not None:
2113
+ found = answer_key(args, kwargs)
2114
+ if found is not None:
2115
+ await _maybe_await(store.set(found, (None, result), None))
2116
+ served(label, index, failed)
2117
+ return result
2118
+ if store is not None:
2119
+ found = answer_key(args, kwargs)
2120
+ entry = None if found is None else await _maybe_await(store.get(found))
2121
+ if isinstance(entry, tuple) and len(entry) == 2:
2122
+ served("cached", -1, failed)
2123
+ return entry[1]
2124
+ assert last is not None
2125
+ raise last
2126
+
2127
+ async_chain.__wrapped__ = models[0]
2128
+ setattr(async_chain, _LAYER_ATTR, ("fallback", settings))
2129
+ return async_chain
2130
+
2131
+ @functools.wraps(models[0])
2132
+ def chain(*args: Any, **kwargs: Any) -> Any:
2133
+ failed: list[str] = []
2134
+ last: BaseException | None = None
2135
+ for index, (label, call) in enumerate(entries):
2136
+ try:
2137
+ result = call(*args, **kwargs)
2138
+ except Exception as exc:
2139
+ if not falls_back(exc):
2140
+ raise
2141
+ failed.append(label)
2142
+ last = exc
2143
+ continue
2144
+ if store is not None and result is not None:
2145
+ found = answer_key(args, kwargs)
2146
+ if found is not None:
2147
+ store.set(found, (None, result), None)
2148
+ served(label, index, failed)
2149
+ return result
2150
+ if store is not None:
2151
+ found = answer_key(args, kwargs)
2152
+ entry = None if found is None else store.get(found)
2153
+ if isinstance(entry, tuple) and len(entry) == 2:
2154
+ served("cached", -1, failed)
2155
+ return entry[1]
2156
+ assert last is not None
2157
+ raise last
2158
+
2159
+ chain.__wrapped__ = models[0]
2160
+ setattr(chain, _LAYER_ATTR, ("fallback", settings))
2161
+ return chain
2162
+
2163
+
2164
+ # --------------------------------------------------------------------- stream timeout
2165
+
2166
+
2167
+ class _Limits:
2168
+ def __init__(
2169
+ self, first_token: float | None, chunk_gap: float | None, total: float | None
2170
+ ) -> None:
2171
+ for label, value in (
2172
+ ("first_token", first_token),
2173
+ ("chunk_gap", chunk_gap),
2174
+ ("total", total),
2175
+ ):
2176
+ if value is not None and (not math.isfinite(value) or value <= 0):
2177
+ raise ValueError(f"{label} must be a positive number of seconds, got {value!r}")
2178
+ if first_token is None and chunk_gap is None and total is None:
2179
+ raise ValueError("stream_timeout needs first_token=, chunk_gap= or total=")
2180
+ self.first_token, self.chunk_gap, self.total = first_token, chunk_gap, total
2181
+
2182
+ def wait(self, started: float, seen_first: bool, now: float) -> tuple[float | None, str, float]:
2183
+ """``(seconds left or None, limit name, limit value)`` for the next chunk."""
2184
+ candidates: list[tuple[float, str, float]] = []
2185
+ if not seen_first and self.first_token is not None:
2186
+ candidates.append((started + self.first_token, "first_token", self.first_token))
2187
+ if seen_first and self.chunk_gap is not None:
2188
+ candidates.append((now + self.chunk_gap, "chunk_gap", self.chunk_gap))
2189
+ if self.total is not None:
2190
+ candidates.append((started + self.total, "total", self.total))
2191
+ if not candidates:
2192
+ return None, "", 0.0
2193
+ deadline, label, limit = min(candidates)
2194
+ return max(deadline - now, 0.0), label, limit
2195
+
2196
+ def settings(self) -> dict[str, Any]:
2197
+ return {
2198
+ "llm": "stream_timeout",
2199
+ "first_token": self.first_token,
2200
+ "chunk_gap": self.chunk_gap,
2201
+ "total": self.total,
2202
+ "seconds": self.total,
2203
+ }
2204
+
2205
+
2206
+ def _expired(label: str, limit: float, function: str) -> StreamTimeout:
2207
+ _core.emit("timeout.expired", function, seconds=limit)
2208
+ what = {
2209
+ "first_token": "no first chunk within",
2210
+ "chunk_gap": "no new chunk within",
2211
+ "total": "stream not finished within",
2212
+ }[label]
2213
+ return StreamTimeout(f"{function}: {what} {limit:g}s ({label})", seconds=limit, limit=label)
2214
+
2215
+
2216
+ class _SyncStream(Iterator[T]):
2217
+ """Pulls a sync iterator in a daemon thread so waits can time out."""
2218
+
2219
+ def __init__(
2220
+ self, source: Iterable[T], limits: _Limits, started: float | None, function: str
2221
+ ) -> None:
2222
+ self._source = source
2223
+ self._limits = limits
2224
+ self._started = started
2225
+ self._function = function
2226
+ self._queue: queue.Queue[tuple[str, Any]] = queue.Queue(maxsize=1)
2227
+ self._stop = threading.Event()
2228
+ self._thread: threading.Thread | None = None
2229
+ self._first = False
2230
+ self._done = False
2231
+
2232
+ def __getattr__(self, name: str) -> Any:
2233
+ return getattr(self._source, name)
2234
+
2235
+ def __iter__(self) -> _SyncStream[T]:
2236
+ return self
2237
+
2238
+ def _put(self, item: tuple[str, Any]) -> bool:
2239
+ while not self._stop.is_set():
2240
+ try:
2241
+ self._queue.put(item, timeout=0.05)
2242
+ return True
2243
+ except queue.Full:
2244
+ continue
2245
+ return False
2246
+
2247
+ def _pump(self) -> None:
2248
+ iterator: Iterator[T] | None = None
2249
+ try:
2250
+ iterator = iter(self._source)
2251
+ for item in iterator:
2252
+ if not self._put(("item", item)):
2253
+ break
2254
+ else:
2255
+ self._put(("end", None))
2256
+ except BaseException as exc:
2257
+ self._put(("error", exc))
2258
+ finally:
2259
+ if self._stop.is_set() and iterator is not None:
2260
+ close = getattr(iterator, "close", None)
2261
+ if callable(close):
2262
+ with contextlib.suppress(Exception):
2263
+ close()
2264
+
2265
+ def __next__(self) -> T:
2266
+ if self._done:
2267
+ raise StopIteration
2268
+ if self._thread is None:
2269
+ if self._started is None:
2270
+ self._started = time.monotonic()
2271
+ context = contextvars.copy_context()
2272
+ self._thread = threading.Thread(
2273
+ target=context.run, args=(self._pump,), name="stream-timeout", daemon=True
2274
+ )
2275
+ self._thread.start()
2276
+ started = self._started if self._started is not None else time.monotonic()
2277
+ left, label, limit = self._limits.wait(started, self._first, time.monotonic())
2278
+ try:
2279
+ kind, value = self._queue.get(timeout=left)
2280
+ except queue.Empty:
2281
+ self.close()
2282
+ raise _expired(label, limit, self._function) from None
2283
+ if kind == "item":
2284
+ self._first = True
2285
+ return cast(T, value)
2286
+ self._done = True
2287
+ if kind == "error":
2288
+ raise value
2289
+ raise StopIteration
2290
+
2291
+ def close(self) -> None:
2292
+ """Stop reading; aborts the source if it has a ``close()`` (an HTTP stream)."""
2293
+ self._done = True
2294
+ self._stop.set()
2295
+ if not inspect.isgenerator(self._source):
2296
+ close = getattr(self._source, "close", None)
2297
+ if callable(close):
2298
+ with contextlib.suppress(Exception):
2299
+ close()
2300
+
2301
+ def __enter__(self) -> _SyncStream[T]:
2302
+ return self
2303
+
2304
+ def __exit__(self, *exc: object) -> None:
2305
+ self.close()
2306
+
2307
+
2308
+ class _AsyncStream(AsyncIterator[T]):
2309
+ """Times each ``__anext__`` of an async iterator."""
2310
+
2311
+ def __init__(
2312
+ self, source: AsyncIterable[T], limits: _Limits, started: float | None, function: str
2313
+ ) -> None:
2314
+ self._source = source
2315
+ self._limits = limits
2316
+ self._started = started
2317
+ self._function = function
2318
+ self._iterator: AsyncIterator[T] | None = None
2319
+ self._first = False
2320
+ self._done = False
2321
+
2322
+ def __getattr__(self, name: str) -> Any:
2323
+ return getattr(self._source, name)
2324
+
2325
+ def __aiter__(self) -> _AsyncStream[T]:
2326
+ return self
2327
+
2328
+ async def __anext__(self) -> T:
2329
+ if self._done:
2330
+ raise StopAsyncIteration
2331
+ if self._iterator is None:
2332
+ if self._started is None:
2333
+ self._started = time.monotonic()
2334
+ self._iterator = self._source.__aiter__()
2335
+ started = self._started if self._started is not None else time.monotonic()
2336
+ left, label, limit = self._limits.wait(started, self._first, time.monotonic())
2337
+ step = asyncio.ensure_future(self._iterator.__anext__())
2338
+ done, _ = await asyncio.wait({step}, timeout=left)
2339
+ if not done:
2340
+ step.cancel()
2341
+ await asyncio.wait({step})
2342
+ if not step.cancelled():
2343
+ step.exception() # retrieve it: the timeout wins
2344
+ await self.aclose()
2345
+ raise _expired(label, limit, self._function)
2346
+ try:
2347
+ item = step.result()
2348
+ except StopAsyncIteration:
2349
+ self._done = True
2350
+ raise
2351
+ self._first = True
2352
+ return item
2353
+
2354
+ async def aclose(self) -> None:
2355
+ """Close the underlying stream (``aclose()`` or ``close()``), once."""
2356
+ self._done = True
2357
+ target: Any = self._iterator if self._iterator is not None else self._source
2358
+ for method in ("aclose", "close"):
2359
+ close = getattr(target, method, None)
2360
+ if callable(close):
2361
+ with contextlib.suppress(Exception):
2362
+ await _maybe_await(close())
2363
+ return
2364
+
2365
+ async def __aenter__(self) -> _AsyncStream[T]:
2366
+ return self
2367
+
2368
+ async def __aexit__(self, *exc: object) -> None:
2369
+ await self.aclose()
2370
+
2371
+
2372
+ def _guard(source: Any, limits: _Limits, started: float | None, function: str) -> Any:
2373
+ if isinstance(source, AsyncIterable):
2374
+ return _AsyncStream(source, limits, started, function)
2375
+ if isinstance(source, Iterable) and not isinstance(source, (str, bytes)):
2376
+ return _SyncStream(source, limits, started, function)
2377
+ raise TypeError(f"stream_timeout needs an iterable or async iterable, got {type(source)!r}")
2378
+
2379
+
2380
+ @overload
2381
+ def stream_timeout(
2382
+ source: AsyncIterable[T],
2383
+ /,
2384
+ *,
2385
+ first_token: float | None = ...,
2386
+ chunk_gap: float | None = ...,
2387
+ total: float | None = ...,
2388
+ ) -> AsyncIterator[T]: ...
2389
+ @overload
2390
+ def stream_timeout(
2391
+ source: Iterable[T],
2392
+ /,
2393
+ *,
2394
+ first_token: float | None = ...,
2395
+ chunk_gap: float | None = ...,
2396
+ total: float | None = ...,
2397
+ ) -> Iterator[T]: ...
2398
+ @overload
2399
+ def stream_timeout(
2400
+ source: None = None,
2401
+ /,
2402
+ *,
2403
+ first_token: float | None = ...,
2404
+ chunk_gap: float | None = ...,
2405
+ total: float | None = ...,
2406
+ ) -> _Decorator[..., Any]: ...
2407
+ def stream_timeout(
2408
+ source: Any = None,
2409
+ /,
2410
+ *,
2411
+ first_token: float | None = None,
2412
+ chunk_gap: float | None = None,
2413
+ total: float | None = None,
2414
+ ) -> Any:
2415
+ """Time limits for a streamed LLM response: first chunk, gap between chunks, total.
2416
+
2417
+ A plain `timeout` cannot guard a stream: the call that opens it returns at once and
2418
+ the waiting happens while you iterate. ``stream_timeout`` limits
2419
+
2420
+ - ``first_token``: seconds until the first chunk (from the call when used as a
2421
+ decorator, from the first ``next()`` when wrapping a stream);
2422
+ - ``chunk_gap``: seconds to wait for each later chunk;
2423
+ - ``total``: seconds for the whole stream, measured from the same start.
2424
+
2425
+ When a limit trips, the stream is closed and `StreamTimeout` (a `TimeoutExpired`,
2426
+ so also a ``TimeoutError``) is raised with ``.limit`` naming which one; the event
2427
+ ``timeout.expired`` is emitted. Limits run on real time.
2428
+
2429
+ Use it on a stream object (``stream_timeout(client_stream, chunk_gap=10)``) or as a
2430
+ decorator on a function returning one: a generator function, an async generator
2431
+ function, a sync function returning an iterable, or an ``async def`` returning an
2432
+ async iterable (then awaiting it counts against ``first_token`` and ``total``).
2433
+ Attributes of the stream (such as an SDK's helper methods) stay reachable.
2434
+
2435
+ Sync streams are read in a daemon thread one chunk ahead, so the wait can time out;
2436
+ a read already blocked in that thread only ends when its connection does (sources
2437
+ with a ``close()`` method, like HTTP streams, are closed to abort it). Async streams
2438
+ have the pending ``__anext__`` cancelled.
2439
+
2440
+ Args:
2441
+ source: A stream to wrap, or None for the decorator form.
2442
+ first_token: Limit for the first chunk.
2443
+ chunk_gap: Limit between chunks.
2444
+ total: Limit for the whole stream.
2445
+
2446
+ Returns:
2447
+ The guarded stream, or a decorator.
2448
+
2449
+ Raises:
2450
+ ValueError: If no limit is given or one is not positive.
2451
+
2452
+ Example:
2453
+ ```python
2454
+ import time
2455
+
2456
+ from python_wrap.llm import StreamTimeout, stream_timeout
2457
+
2458
+ def chunks():
2459
+ yield "Hel"
2460
+ yield "lo"
2461
+ time.sleep(0.5) # the provider stalls
2462
+ yield "!"
2463
+
2464
+ received = []
2465
+ try:
2466
+ for chunk in stream_timeout(chunks(), first_token=1, chunk_gap=0.05):
2467
+ received.append(chunk)
2468
+ except StreamTimeout as exc:
2469
+ assert exc.limit == "chunk_gap"
2470
+ assert received == ["Hel", "lo"]
2471
+ ```
2472
+ """
2473
+ limits = _Limits(first_token, chunk_gap, total)
2474
+ if source is not None:
2475
+ return _guard(source, limits, None, type(source).__qualname__)
2476
+ settings = limits.settings()
2477
+
2478
+ def decorate(func: Callable[P, R]) -> Callable[P, R]:
2479
+ label = _core.qualname(func)
2480
+ if inspect.isasyncgenfunction(func) or not _core.is_async(func):
2481
+
2482
+ @functools.wraps(func)
2483
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
2484
+ started = time.monotonic()
2485
+ return _guard(func(*args, **kwargs), limits, started, label)
2486
+
2487
+ setattr(wrapper, _LAYER_ATTR, ("timeout", settings))
2488
+ return cast("Callable[P, R]", wrapper)
2489
+
2490
+ afunc = cast("Callable[..., Awaitable[Any]]", func)
2491
+
2492
+ @functools.wraps(func)
2493
+ async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
2494
+ started = time.monotonic()
2495
+ left, which, limit = limits.wait(started, False, started)
2496
+ opening = asyncio.ensure_future(afunc(*args, **kwargs))
2497
+ done, _ = await asyncio.wait({opening}, timeout=left)
2498
+ if not done:
2499
+ opening.cancel()
2500
+ await asyncio.wait({opening})
2501
+ if not opening.cancelled():
2502
+ opening.exception()
2503
+ raise _expired(which, limit, label)
2504
+ return _guard(opening.result(), limits, started, label)
2505
+
2506
+ setattr(async_wrapper, _LAYER_ATTR, ("timeout", settings))
2507
+ return cast("Callable[P, R]", async_wrapper)
2508
+
2509
+ setattr(decorate, _LAYER_ATTR, ("timeout", settings))
2510
+ return decorate
2511
+
2512
+
2513
+ # --------------------------------------------------------------------------- doctor
2514
+
2515
+
2516
+ def doctor_findings(layers: Sequence[Layer]) -> list[Finding]:
2517
+ """PW013-PW015: lint stacks containing LLM layers (called by `python_wrap.doctor`)."""
2518
+ from python_wrap.doctor import Finding
2519
+
2520
+ kinds = [layer.settings.get("llm") for layer in layers]
2521
+ if not any(kinds):
2522
+ return []
2523
+ found: list[Finding] = []
2524
+ if "retry" in kinds and "budget" not in kinds:
2525
+ found.append(
2526
+ Finding(
2527
+ "PW013",
2528
+ "warning",
2529
+ "LLM call is retried but has no spend budget: a retry storm or an agent "
2530
+ "loop spends without limit. Add a Budget (tokens=/usd=), for example "
2531
+ "llm_client(..., spend=Budget(...)) or @budget(...).",
2532
+ )
2533
+ )
2534
+ timeouts = [layer for layer in layers if layer.role == "timeout"]
2535
+ if not timeouts:
2536
+ found.append(
2537
+ Finding(
2538
+ "PW014",
2539
+ "warning",
2540
+ "LLM call has no timeout: a stalled provider holds the caller forever. Add "
2541
+ "timeout=timeout(seconds) (llm_client does), or stream_timeout(...) for "
2542
+ "streamed responses.",
2543
+ )
2544
+ )
2545
+ for layer in timeouts:
2546
+ if (
2547
+ layer.settings.get("llm") == "stream_timeout"
2548
+ and layer.settings.get("chunk_gap") is None
2549
+ ):
2550
+ found.append(
2551
+ Finding(
2552
+ "PW014",
2553
+ "warning",
2554
+ "stream_timeout without chunk_gap: a stream that stalls after its first "
2555
+ "chunk is only caught by total= (or never). Set chunk_gap=seconds.",
2556
+ )
2557
+ )
2558
+ for layer in layers:
2559
+ if (
2560
+ layer.role == "retry"
2561
+ and layer.settings.get("llm") is None
2562
+ and not layer.settings.get("retry_if")
2563
+ ):
2564
+ found.append(
2565
+ Finding(
2566
+ "PW015",
2567
+ "warning",
2568
+ "a generic retry wraps an LLM call without retry_if=: bad requests "
2569
+ "and content-policy refusals are retried (and billed) again. Use "
2570
+ "llm_retry(), or retry(retry_if=llm_transient, "
2571
+ "delay_from=llm_retry_after).",
2572
+ )
2573
+ )
2574
+ return found