python-wrap 0.2.1__py3-none-any.whl → 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. python_wrap/__init__.py +348 -1
  2. python_wrap/__main__.py +57 -0
  3. python_wrap/_backend.py +133 -0
  4. python_wrap/_buckets.py +162 -0
  5. python_wrap/_core.py +12 -3
  6. python_wrap/_data/agent_guide.md +103 -0
  7. python_wrap/_data/recipes.json +703 -0
  8. python_wrap/_fork.py +113 -0
  9. python_wrap/_integration.py +29 -0
  10. python_wrap/_runtime.py +157 -0
  11. python_wrap/adapters/__init__.py +101 -0
  12. python_wrap/adapters/_frameworks.py +251 -0
  13. python_wrap/adapters/_sdk.py +1978 -0
  14. python_wrap/adapters/anthropic.py +139 -0
  15. python_wrap/adapters/langchain.py +288 -0
  16. python_wrap/adapters/openai.py +169 -0
  17. python_wrap/adapters/openai_agents.py +468 -0
  18. python_wrap/adapters/pydantic_ai.py +459 -0
  19. python_wrap/adaptive.py +605 -0
  20. python_wrap/agents.py +2503 -0
  21. python_wrap/alerts.py +293 -0
  22. python_wrap/async_cache.py +745 -0
  23. python_wrap/batching.py +17 -4
  24. python_wrap/buffering.py +952 -0
  25. python_wrap/bulkhead.py +58 -6
  26. python_wrap/caching.py +425 -56
  27. python_wrap/celery.py +528 -0
  28. python_wrap/chaos.py +519 -0
  29. python_wrap/circuit.py +454 -23
  30. python_wrap/compat.py +267 -0
  31. python_wrap/concurrency.py +82 -1746
  32. python_wrap/config.py +25 -4
  33. python_wrap/coordination.py +638 -0
  34. python_wrap/credentials.py +126 -0
  35. python_wrap/dashboard.py +358 -0
  36. python_wrap/debounce.py +538 -0
  37. python_wrap/django.py +100 -0
  38. python_wrap/doctor.py +599 -0
  39. python_wrap/events.py +145 -4
  40. python_wrap/exporters.py +663 -0
  41. python_wrap/fastapi.py +81 -0
  42. python_wrap/flask.py +61 -0
  43. python_wrap/genai.py +1101 -0
  44. python_wrap/health.py +187 -0
  45. python_wrap/http.py +940 -0
  46. python_wrap/idempotency.py +446 -0
  47. python_wrap/introspect.py +738 -0
  48. python_wrap/lifecycle.py +620 -0
  49. python_wrap/llm.py +2574 -0
  50. python_wrap/llm_cassette.py +948 -0
  51. python_wrap/llm_http_chaos.py +326 -0
  52. python_wrap/llm_shared.py +772 -0
  53. python_wrap/llm_testing.py +990 -0
  54. python_wrap/llm_validate.py +383 -0
  55. python_wrap/local_state.py +395 -0
  56. python_wrap/logs.py +82 -26
  57. python_wrap/mcp.py +490 -0
  58. python_wrap/mcp_guard.py +357 -0
  59. python_wrap/metrics.py +6 -3
  60. python_wrap/migrate.py +1452 -0
  61. python_wrap/observability.py +484 -0
  62. python_wrap/periodic.py +24 -2
  63. python_wrap/policies.py +396 -0
  64. python_wrap/policy.py +14 -0
  65. python_wrap/predicates.py +276 -0
  66. python_wrap/presets.py +378 -0
  67. python_wrap/processing.py +227 -0
  68. python_wrap/propagation.py +62 -0
  69. python_wrap/pytest_plugin.py +85 -0
  70. python_wrap/quotas.py +319 -0
  71. python_wrap/ratelimit.py +560 -0
  72. python_wrap/redaction.py +228 -0
  73. python_wrap/retry.py +448 -70
  74. python_wrap/shared.py +653 -0
  75. python_wrap/singleflight.py +255 -0
  76. python_wrap/slow.py +72 -0
  77. python_wrap/stores.py +168 -0
  78. python_wrap/switches.py +164 -0
  79. python_wrap/testing.py +34 -8
  80. python_wrap/timeouts.py +874 -0
  81. python_wrap/timing.py +239 -17
  82. python_wrap/validation.py +187 -12
  83. python_wrap/web.py +723 -0
  84. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/METADATA +117 -7
  85. python_wrap-0.4.0.dist-info/RECORD +95 -0
  86. python_wrap-0.2.1.dist-info/RECORD +0 -29
  87. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/WHEEL +0 -0
  88. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,139 @@
1
+ """Guard an Anthropic Python SDK client: one retry loop, a budget, a token limit, safe streams.
2
+
3
+ `guard_anthropic` wraps an ``anthropic.Anthropic`` or ``anthropic.AsyncAnthropic``
4
+ client (or anything shaped like one) in a proxy with the same call surface:
5
+
6
+ - ``guarded.messages.create(...)``, including ``stream=True``;
7
+ - ``with guarded.messages.stream(...) as stream:`` (``async with`` for async clients);
8
+ - ``guarded.beta.messages.tool_runner(...)``: each step is budgeted, rate limited and
9
+ fed to the `CacheGuard`.
10
+
11
+ Calls go through the same layers as `guard_openai`; the limiter follows
12
+ ``anthropic-ratelimit-tokens-remaining`` / ``anthropic-ratelimit-input-tokens-remaining``.
13
+ The tool runner is the exception for retries: a step runs your tools before the next
14
+ request, so python-wrap never repeats a step; the runner uses the original client,
15
+ whose SDK retries repeat only the HTTP request.
16
+
17
+ The ``anthropic`` package is never imported here.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from collections.abc import Callable, Mapping
23
+ from typing import Any
24
+
25
+ from python_wrap.adapters._sdk import CacheGuard, GuardedClient, _Endpoint, _Namespace, _Runner
26
+ from python_wrap.llm import Budget, TokenRateLimiter
27
+
28
+ __all__ = ["GuardedAnthropic", "guard_anthropic"]
29
+
30
+
31
+ class _BetaMessages:
32
+ """``guarded.beta.messages``: ``tool_runner`` is accounted; the rest passes through."""
33
+
34
+ def __init__(self, guard: GuardedAnthropic) -> None:
35
+ self._guard = guard
36
+
37
+ def tool_runner(self, *args: Any, **kwargs: Any) -> _Runner:
38
+ """Start the SDK's tool runner; every step is budgeted and rate limited."""
39
+ runner = self._guard.raw.beta.messages.tool_runner(*args, **kwargs)
40
+ return _Runner(self._guard, runner, kwargs, "anthropic.beta.messages.tool_runner")
41
+
42
+ def __getattr__(self, name: str) -> Any:
43
+ if name.startswith("_"):
44
+ raise AttributeError(name)
45
+ return getattr(self._guard.raw.beta.messages, name)
46
+
47
+
48
+ class GuardedAnthropic(GuardedClient):
49
+ """The proxy `guard_anthropic` returns; see `GuardedClient` for the layers.
50
+
51
+ Attributes:
52
+ messages: ``create`` and ``stream`` are guarded; ``count_tokens``... pass
53
+ through.
54
+ beta: ``beta.messages.tool_runner`` is accounted per step.
55
+ """
56
+
57
+ def __init__(self, client: Any, **options: Any) -> None:
58
+ super().__init__(client, system="anthropic", **options)
59
+ self.messages = _Endpoint(self, ("messages",), "messages")
60
+ self.beta = _Namespace(self, ("beta",), messages=_BetaMessages(self))
61
+
62
+ def _primary(self) -> _Endpoint:
63
+ return self.messages
64
+
65
+
66
+ def guard_anthropic(
67
+ client: Any,
68
+ *,
69
+ budget: Budget | None = None,
70
+ limiter: TokenRateLimiter | None = None,
71
+ policy: Callable[[Callable[..., Any]], Callable[..., Any]] | None = None,
72
+ attempts: int = 4,
73
+ retry: Mapping[str, Any] | None = None,
74
+ owns_retries: bool = True,
75
+ trace: bool | Mapping[str, Any] = False,
76
+ cache_guard: CacheGuard | None = None,
77
+ read_headers: bool = True,
78
+ first_token: float | None = None,
79
+ chunk_gap: float | None = None,
80
+ total: float | None = None,
81
+ is_async: bool | None = None,
82
+ ) -> GuardedAnthropic:
83
+ """Wrap an Anthropic SDK client so every call is retried, budgeted and rate limited once.
84
+
85
+ The arguments are those of `guard_openai`. Usage is read from ``response.usage``
86
+ (``input_tokens``, ``output_tokens`` and the cache read/creation counts); streams
87
+ add ``message_start`` and ``message_delta`` usage.
88
+
89
+ Returns:
90
+ A `GuardedAnthropic`.
91
+
92
+ Example:
93
+ ```python
94
+ from types import SimpleNamespace
95
+
96
+ from python_wrap.adapters import guard_anthropic
97
+ from python_wrap.llm import Budget
98
+
99
+
100
+ class Messages:
101
+ def create(self, **kwargs: object) -> SimpleNamespace:
102
+ usage = SimpleNamespace(input_tokens=20, output_tokens=5,
103
+ cache_read_input_tokens=0,
104
+ cache_creation_input_tokens=0)
105
+ return SimpleNamespace(model="m-1", usage=usage, content=[])
106
+
107
+
108
+ class Client: # the shape of anthropic.Anthropic
109
+ max_retries = 2
110
+ messages = Messages()
111
+
112
+ def with_options(self, *, max_retries: int) -> "Client":
113
+ clone = Client()
114
+ clone.max_retries = max_retries
115
+ return clone
116
+
117
+
118
+ spend = Budget(tokens=100)
119
+ client = guard_anthropic(Client(), budget=spend)
120
+ client.messages.create(model="m-1", max_tokens=10, messages=[])
121
+ assert spend.spent().tokens == 25
122
+ ```
123
+ """
124
+ return GuardedAnthropic(
125
+ client,
126
+ budget=budget,
127
+ limiter=limiter,
128
+ policy=policy,
129
+ attempts=attempts,
130
+ retry=retry,
131
+ owns_retries=owns_retries,
132
+ trace=trace,
133
+ cache_guard=cache_guard,
134
+ read_headers=read_headers,
135
+ first_token=first_token,
136
+ chunk_gap=chunk_gap,
137
+ total=total,
138
+ is_async=is_async,
139
+ )
@@ -0,0 +1,288 @@
1
+ """Guard a LangChain chat model: one retry owner, one budget, one token limit, safe streams.
2
+
3
+ LangChain models retry by themselves (``max_retries``, ``with_retry``) on top of the
4
+ provider SDK, so a python-wrap retry around them multiplies attempts and ignores the
5
+ `RetryBudget`. `guard_chat_model` rebuilds the model with ``max_retries=0`` and runs
6
+ ``invoke``/``ainvoke`` through the same layers as `guard_openai`: tracing (optional), the
7
+ `Budget` (charged once with the final ``usage_metadata``), python-wrap's retry loop, your
8
+ per-attempt ``policy`` and the `TokenRateLimiter` (lowered to the provider's
9
+ rate-limit headers when ``response_metadata["headers"]`` carries them).
10
+ ``stream``/``astream`` return a `ResumableStream`: reopened only before any output.
11
+
12
+ `PythonWrapCallback` only observes (usage, latency, errors) and emits the
13
+ ``genai.llm_call`` event, for code paths where the model cannot be wrapped.
14
+
15
+ LangChain is never imported here.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import time
21
+ import uuid
22
+ from collections.abc import Callable, Mapping
23
+ from typing import Any
24
+
25
+ from python_wrap import _core
26
+ from python_wrap.adapters._sdk import GuardedClient, ResumableStream
27
+ from python_wrap.llm import Budget, TokenRateLimiter, read_usage
28
+
29
+ __all__ = ["GuardedChatModel", "PythonWrapCallback", "guard_chat_model", "without_retries"]
30
+
31
+
32
+ def without_retries(model: Any) -> Any:
33
+ """A copy of a LangChain chat model (or a binding around one) that never retries.
34
+
35
+ The model is rebuilt from the fields you set plus ``max_retries=0``, so the
36
+ provider client inside it is created again without its own retries. A
37
+ ``with_retry()`` wrapper is refused: unwrap it and let python-wrap retry.
38
+
39
+ Raises:
40
+ ValueError: For a ``RunnableRetry`` (``model.with_retry(...)``).
41
+ TypeError: If a retrying model cannot be rebuilt.
42
+ """
43
+ if (getattr(model, "max_attempt_number", 0) or 0) > 1:
44
+ raise ValueError("unwrap .with_retry(): python-wrap owns the retries")
45
+ bound = getattr(model, "bound", None)
46
+ if bound is not None and hasattr(model, "model_copy"): # bind_tools() and friends
47
+ return model.model_copy(update={"bound": without_retries(bound)})
48
+ if not getattr(model, "max_retries", 0):
49
+ return model
50
+ fields = {name: getattr(model, name) for name in getattr(model, "model_fields_set", ())}
51
+ try:
52
+ return type(model)(**{**fields, "max_retries": 0})
53
+ except Exception as exc:
54
+ raise TypeError(
55
+ f"cannot rebuild {type(model).__name__} with max_retries=0; "
56
+ "construct it with max_retries=0 yourself"
57
+ ) from exc
58
+
59
+
60
+ class _NoSdk:
61
+ """Stands in for an SDK client: the model's own retries were removed already."""
62
+
63
+ max_retries = 0
64
+
65
+
66
+ def _text(value: Any) -> str:
67
+ """The prompt text of a LangChain input, for the token estimate."""
68
+ if isinstance(value, str):
69
+ return value
70
+ to_string = getattr(value, "to_string", None) # a PromptValue
71
+ if callable(to_string):
72
+ return str(to_string())
73
+ if isinstance(value, (list, tuple)):
74
+ return "\n".join(_text(getattr(item, "content", item)) for item in value)
75
+ if isinstance(value, Mapping):
76
+ return _text(value.get("content", ""))
77
+ return str(value)
78
+
79
+
80
+ def _headers(result: Any) -> Any:
81
+ meta = getattr(result, "response_metadata", None)
82
+ return meta.get("headers") if isinstance(meta, Mapping) else None
83
+
84
+
85
+ class GuardedChatModel:
86
+ """The wrapper `guard_chat_model` returns.
87
+
88
+ ``invoke``, ``ainvoke``, ``stream`` and ``astream`` are guarded; every other attribute
89
+ is the retry-free model's (``batch`` and tools such as ``bind_tools`` are not guarded).
90
+
91
+ Attributes:
92
+ raw: The model you passed.
93
+ model: The copy calls go through (``max_retries=0``).
94
+ """
95
+
96
+ def __init__(self, model: Any, **options: Any) -> None:
97
+ self.raw = model
98
+ self.model = without_retries(model)
99
+ self._sync = GuardedClient(_NoSdk(), system="langchain", is_async=False, **options)
100
+ self._async = GuardedClient(_NoSdk(), system="langchain", is_async=True, **options)
101
+ self._invoke = self._sync._compose("langchain.invoke", self._attempt)
102
+ self._ainvoke = self._async._compose("langchain.ainvoke", self._aattempt)
103
+
104
+ def _attempt(self, input: Any, config: Any = None, **kwargs: Any) -> Any:
105
+ request = {"input": _text(input)}
106
+ cost = self._sync._reserve((), request, "langchain.invoke")
107
+ try:
108
+ result = self.model.invoke(input, config, **kwargs)
109
+ except BaseException as exc:
110
+ self._sync._failed(cost, exc, request)
111
+ raise
112
+ self._sync._settled(cost, result, _headers(result), request)
113
+ return result
114
+
115
+ async def _aattempt(self, input: Any, config: Any = None, **kwargs: Any) -> Any:
116
+ request = {"input": _text(input)}
117
+ cost = await self._async._areserve((), request, "langchain.ainvoke")
118
+ try:
119
+ result = await self.model.ainvoke(input, config, **kwargs)
120
+ except BaseException as exc:
121
+ self._async._failed(cost, exc, request)
122
+ raise
123
+ self._async._settled(cost, result, _headers(result), request)
124
+ return result
125
+
126
+ def invoke(self, input: Any, config: Any = None, **kwargs: Any) -> Any:
127
+ return self._invoke(input, config, **kwargs)
128
+
129
+ async def ainvoke(self, input: Any, config: Any = None, **kwargs: Any) -> Any:
130
+ return await self._ainvoke(input, config, **kwargs)
131
+
132
+ def stream(self, input: Any, config: Any = None, **kwargs: Any) -> ResumableStream[Any]:
133
+ """Chunks of the model's stream; reopened on a transient error before output."""
134
+ request = {"input": _text(input)}
135
+ admission = self._sync._admit((input,), request, "langchain.stream")
136
+ return self._sync._resumable(
137
+ "langchain.stream",
138
+ lambda: self.model.stream(input, config, **kwargs),
139
+ admission,
140
+ request,
141
+ )
142
+
143
+ async def astream(self, input: Any, config: Any = None, **kwargs: Any) -> Any:
144
+ """Async `stream`: iterate the result with ``async for``."""
145
+ request = {"input": _text(input)}
146
+ admission = await self._async._aadmit((input,), request, "langchain.astream")
147
+ stream = self._async._resumable(
148
+ "langchain.astream",
149
+ lambda: self.model.astream(input, config, **kwargs),
150
+ admission,
151
+ request,
152
+ )
153
+ async for chunk in stream:
154
+ yield chunk
155
+
156
+ def __getattr__(self, name: str) -> Any:
157
+ if name.startswith("_"):
158
+ raise AttributeError(name)
159
+ return getattr(self.model, name)
160
+
161
+ def __repr__(self) -> str:
162
+ return f"GuardedChatModel({type(self.raw).__name__}, attempts={self._sync.attempts})"
163
+
164
+
165
+ def guard_chat_model(
166
+ model: Any,
167
+ *,
168
+ budget: Budget | None = None,
169
+ limiter: TokenRateLimiter | None = None,
170
+ policy: Callable[[Callable[..., Any]], Callable[..., Any]] | None = None,
171
+ attempts: int = 4,
172
+ retry: Mapping[str, Any] | None = None,
173
+ trace: bool | Mapping[str, Any] = False,
174
+ first_token: float | None = None,
175
+ chunk_gap: float | None = None,
176
+ total: float | None = None,
177
+ ) -> GuardedChatModel:
178
+ """Wrap a LangChain chat model so each call is retried, budgeted and limited once.
179
+
180
+ Args:
181
+ model: A LangChain chat model (``ChatOpenAI``, ``ChatAnthropic``...) or a binding
182
+ around one (``model.bind_tools(...)``).
183
+ budget: Checked before each call, charged once with the final ``usage_metadata``.
184
+ limiter: Reserves an estimate per attempt and settles with the real usage.
185
+ policy: A per-attempt decorator (a timeout, a breaker); no retry in it.
186
+ attempts: Total attempts per call (python-wrap's `llm_retry`).
187
+ retry: Extra `llm_retry` options (``delay``, ``max_delay``, ``retry_if``...).
188
+ trace: Wrap calls in `traced_llm` (True, or its options).
189
+ first_token: Seconds to wait for a stream's first chunk.
190
+ chunk_gap: Longest pause between stream chunks.
191
+ total: Longest whole stream.
192
+
193
+ Returns:
194
+ A `GuardedChatModel`.
195
+
196
+ Example:
197
+ ```python
198
+ from python_wrap.adapters.langchain import guard_chat_model
199
+
200
+
201
+ class FakeModel: # stands in for ChatOpenAI(...)
202
+ max_retries = 0
203
+
204
+ def invoke(self, input, config=None):
205
+ return {"content": "hi", "usage": {"input_tokens": 3, "output_tokens": 1}}
206
+
207
+
208
+ assert guard_chat_model(FakeModel()).invoke("hello")["content"] == "hi"
209
+ ```
210
+ """
211
+ return GuardedChatModel(
212
+ model,
213
+ budget=budget,
214
+ limiter=limiter,
215
+ policy=policy,
216
+ attempts=attempts,
217
+ retry=retry,
218
+ trace=trace,
219
+ first_token=first_token,
220
+ chunk_gap=chunk_gap,
221
+ total=total,
222
+ )
223
+
224
+
225
+ class PythonWrapCallback:
226
+ """A LangChain callback handler that observes calls and emits ``genai.llm_call``.
227
+
228
+ Use it where a model cannot be wrapped (inside a chain built elsewhere):
229
+ ``model.invoke(prompt, config={"callbacks": [PythonWrapCallback()]})``. It records
230
+ tokens, latency, model and errors; it never changes a call and captures no content.
231
+ Duck-typed: LangChain need not be importable when it is created.
232
+ """
233
+
234
+ # Attributes LangChain's callback manager reads on every handler.
235
+ ignore_llm = ignore_chat_model = ignore_retry = False
236
+ ignore_chain = ignore_agent = ignore_retriever = ignore_custom_event = True
237
+ raise_error = False
238
+ run_inline = True
239
+
240
+ def __init__(self, name: str = "langchain") -> None:
241
+ self.name = name
242
+ self._started: dict[Any, tuple[float, float]] = {}
243
+
244
+ def on_llm_start(self, serialized: Any, prompts: Any, *, run_id: Any = None, **_: Any) -> None:
245
+ self._started[run_id] = (time.monotonic(), time.time())
246
+
247
+ def on_chat_model_start(
248
+ self, serialized: Any, messages: Any, *, run_id: Any = None, **_: Any
249
+ ) -> None:
250
+ self._started[run_id] = (time.monotonic(), time.time())
251
+
252
+ def _emit(self, run_id: Any, status: str, **fields: Any) -> None:
253
+ began, wall = self._started.pop(run_id, (time.monotonic(), time.time()))
254
+ _core.emit(
255
+ "genai.llm_call",
256
+ self.name,
257
+ kind="llm",
258
+ run_id=str(run_id or uuid.uuid4()),
259
+ step=None,
260
+ tool=None,
261
+ system="langchain",
262
+ cost=None,
263
+ latency=time.monotonic() - began,
264
+ started=wall,
265
+ status=status,
266
+ attempts=None,
267
+ **{"model": None, "input_tokens": None, "output_tokens": None, "error_type": None}
268
+ | fields,
269
+ )
270
+
271
+ def on_llm_end(self, response: Any, *, run_id: Any = None, **_: Any) -> None:
272
+ output = getattr(response, "llm_output", None) or {}
273
+ usage = read_usage({"usage": output.get("token_usage") or output.get("usage")})
274
+ if usage is None: # chat models put usage_metadata on the message
275
+ for batch in getattr(response, "generations", None) or ():
276
+ for generation in batch:
277
+ usage = read_usage(getattr(generation, "message", None)) or usage
278
+ model = output.get("model_name") or (usage.model if usage else None)
279
+ self._emit(
280
+ run_id,
281
+ "ok",
282
+ model=model,
283
+ input_tokens=usage.input_tokens if usage else None,
284
+ output_tokens=usage.output_tokens if usage else None,
285
+ )
286
+
287
+ def on_llm_error(self, error: BaseException, *, run_id: Any = None, **_: Any) -> None:
288
+ self._emit(run_id, "error", error_type=type(error).__name__)
@@ -0,0 +1,169 @@
1
+ """Guard an OpenAI Python SDK client: one retry loop, a budget, a token limit, safe streams.
2
+
3
+ `guard_openai` wraps an ``openai.OpenAI`` or ``openai.AsyncOpenAI`` client (or anything
4
+ shaped like one) in a proxy with the same call surface:
5
+
6
+ - ``guarded.chat.completions.create(...)``
7
+ - ``guarded.responses.create(...)``
8
+ - ``guarded.embeddings.create(...)`` (charges input tokens; embeddings report no output)
9
+
10
+ Each call goes through tracing (optional), the `Budget`, python-wrap's retry loop (the
11
+ SDK's own retries are switched off with `no_sdk_retries`, so attempts never multiply),
12
+ your per-attempt ``policy`` and the `TokenRateLimiter`, which is lowered to the
13
+ ``x-ratelimit-remaining-tokens`` header read through ``with_raw_response``. With
14
+ ``stream=True`` the result is a `ResumableStream`: reopened when it fails before any
15
+ output, `StreamInterrupted` after. Chat streams get
16
+ ``stream_options={"include_usage": True}`` (unless you pass ``stream_options``) so
17
+ their usage can be charged. Every other attribute (``models``,
18
+ ``files``...) is the original client's, unguarded. ``AzureOpenAI`` and
19
+ ``AsyncAzureOpenAI`` clients work the same way; their ``model`` argument is the
20
+ deployment name, so map deployments in `Budget` ``prices=`` by deployment name.
21
+
22
+ The ``openai`` package is never imported here.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ from collections.abc import Callable, Mapping
28
+ from typing import Any
29
+
30
+ from python_wrap.adapters._sdk import CacheGuard, GuardedClient, _Endpoint, _Namespace
31
+ from python_wrap.llm import Budget, TokenRateLimiter
32
+
33
+ __all__ = ["GuardedOpenAI", "guard_openai"]
34
+
35
+
36
+ class GuardedOpenAI(GuardedClient):
37
+ """The proxy `guard_openai` returns; see `GuardedClient` for the layers.
38
+
39
+ Attributes:
40
+ chat: ``chat.completions.create`` is guarded; other attributes pass through.
41
+ responses: ``responses.create`` is guarded; ``retrieve``/``delete``... pass
42
+ through.
43
+ embeddings: ``embeddings.create`` is guarded (budget, limiter, retries).
44
+ """
45
+
46
+ def __init__(self, client: Any, **options: Any) -> None:
47
+ super().__init__(client, system="openai", **options)
48
+ self.chat = _Namespace(
49
+ self, ("chat",), completions=_Endpoint(self, ("chat", "completions"), "chat")
50
+ )
51
+ self.responses = _Endpoint(self, ("responses",), "responses")
52
+ self.embeddings = _Endpoint(self, ("embeddings",), "embeddings")
53
+
54
+ def _primary(self) -> _Endpoint:
55
+ return self.chat.completions # type: ignore[no-any-return]
56
+
57
+
58
+ def guard_openai(
59
+ client: Any,
60
+ *,
61
+ budget: Budget | None = None,
62
+ limiter: TokenRateLimiter | None = None,
63
+ policy: Callable[[Callable[..., Any]], Callable[..., Any]] | None = None,
64
+ attempts: int = 4,
65
+ retry: Mapping[str, Any] | None = None,
66
+ owns_retries: bool = True,
67
+ trace: bool | Mapping[str, Any] = False,
68
+ cache_guard: CacheGuard | None = None,
69
+ read_headers: bool = True,
70
+ first_token: float | None = None,
71
+ chunk_gap: float | None = None,
72
+ total: float | None = None,
73
+ is_async: bool | None = None,
74
+ limiter_key: Callable[[Mapping[str, Any]], str] | None = None,
75
+ ) -> GuardedOpenAI:
76
+ """Wrap an OpenAI SDK client so every call is retried, budgeted and rate limited once.
77
+
78
+ Args:
79
+ client: ``OpenAI()`` / ``AsyncOpenAI()`` (or a look-alike).
80
+ budget: Checked before each call and charged with ``response.usage`` after.
81
+ limiter: Reserves an estimate per attempt, settles with the real usage, and is
82
+ lowered to the provider's ``x-ratelimit-remaining-tokens``; a 429's
83
+ ``retry-after`` drains it.
84
+ policy: A per-attempt decorator (a `Policy` with a timeout or breaker). Do not
85
+ put a retry in it: retries belong to ``attempts``.
86
+ attempts: Total attempts per call (python-wrap's loop, `llm_retry`).
87
+ retry: Extra `llm_retry` options (``delay``, ``max_delay``, ``max_time``,
88
+ ``budget``, ``retry_if``); ``delay``/``max_delay``/``retry_if`` also apply
89
+ to reopening streams.
90
+ owns_retries: True (default): python-wrap retries and the client is copied with
91
+ ``max_retries=0``. False: the SDK keeps its retries and python-wrap makes a
92
+ single attempt. Either way exactly one layer retries.
93
+ trace: True (or `traced_llm` options) to publish a ``genai.llm_call`` event per
94
+ call.
95
+ cache_guard: A `CacheGuard` fed every response and request.
96
+ read_headers: Use ``with_raw_response`` to read rate-limit headers.
97
+ first_token: Stall limit before a stream's first event (reopened while safe).
98
+ chunk_gap: Stall limit between stream events.
99
+ total: Limit for a whole stream.
100
+ is_async: Force sync/async; detected from the client class name otherwise.
101
+ limiter_key: ``limiter_key(kwargs) -> str`` gives each value its own token
102
+ window with ``limiter``'s settings, e.g. ``lambda kw: kw["model"]`` for one
103
+ window per Azure deployment (quotas there are per deployment and region).
104
+
105
+ Returns:
106
+ A `GuardedOpenAI`.
107
+
108
+ Example:
109
+ ```python
110
+ from types import SimpleNamespace
111
+
112
+ from python_wrap.adapters import guard_openai
113
+ from python_wrap.llm import Budget
114
+ from python_wrap.testing import fake_clock
115
+
116
+
117
+ class RateLimitError(Exception):
118
+ status_code = 429
119
+
120
+
121
+ class Completions:
122
+ def __init__(self) -> None:
123
+ self.calls = 0
124
+
125
+ def create(self, **kwargs: object) -> SimpleNamespace:
126
+ self.calls += 1
127
+ if self.calls == 1:
128
+ raise RateLimitError
129
+ usage = SimpleNamespace(prompt_tokens=12, completion_tokens=3)
130
+ return SimpleNamespace(model="m-1", usage=usage, choices=[])
131
+
132
+
133
+ class Client: # the shape of openai.OpenAI
134
+ max_retries = 2
135
+
136
+ def __init__(self, completions: Completions | None = None) -> None:
137
+ self.chat = SimpleNamespace(completions=completions or Completions())
138
+
139
+ def with_options(self, *, max_retries: int) -> "Client":
140
+ clone = Client(self.chat.completions)
141
+ clone.max_retries = max_retries
142
+ return clone
143
+
144
+
145
+ spend = Budget(tokens=1_000)
146
+ client = guard_openai(Client(), budget=spend)
147
+ with fake_clock():
148
+ client.chat.completions.create(model="m-1", messages=[])
149
+ assert client.client.max_retries == 0 # only python-wrap retries
150
+ assert spend.spent().tokens == 15
151
+ ```
152
+ """
153
+ return GuardedOpenAI(
154
+ client,
155
+ budget=budget,
156
+ limiter=limiter,
157
+ policy=policy,
158
+ attempts=attempts,
159
+ retry=retry,
160
+ owns_retries=owns_retries,
161
+ trace=trace,
162
+ cache_guard=cache_guard,
163
+ read_headers=read_headers,
164
+ first_token=first_token,
165
+ chunk_gap=chunk_gap,
166
+ total=total,
167
+ is_async=is_async,
168
+ limiter_key=limiter_key,
169
+ )