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.
- python_wrap/__init__.py +348 -1
- python_wrap/__main__.py +57 -0
- python_wrap/_backend.py +133 -0
- python_wrap/_buckets.py +162 -0
- python_wrap/_core.py +12 -3
- python_wrap/_data/agent_guide.md +103 -0
- python_wrap/_data/recipes.json +703 -0
- python_wrap/_fork.py +113 -0
- python_wrap/_integration.py +29 -0
- python_wrap/_runtime.py +157 -0
- python_wrap/adapters/__init__.py +101 -0
- python_wrap/adapters/_frameworks.py +251 -0
- python_wrap/adapters/_sdk.py +1978 -0
- python_wrap/adapters/anthropic.py +139 -0
- python_wrap/adapters/langchain.py +288 -0
- python_wrap/adapters/openai.py +169 -0
- python_wrap/adapters/openai_agents.py +468 -0
- python_wrap/adapters/pydantic_ai.py +459 -0
- python_wrap/adaptive.py +605 -0
- python_wrap/agents.py +2503 -0
- python_wrap/alerts.py +293 -0
- python_wrap/async_cache.py +745 -0
- python_wrap/batching.py +17 -4
- python_wrap/buffering.py +952 -0
- python_wrap/bulkhead.py +58 -6
- python_wrap/caching.py +425 -56
- python_wrap/celery.py +528 -0
- python_wrap/chaos.py +519 -0
- python_wrap/circuit.py +454 -23
- python_wrap/compat.py +267 -0
- python_wrap/concurrency.py +82 -1746
- python_wrap/config.py +25 -4
- python_wrap/coordination.py +638 -0
- python_wrap/credentials.py +126 -0
- python_wrap/dashboard.py +358 -0
- python_wrap/debounce.py +538 -0
- python_wrap/django.py +100 -0
- python_wrap/doctor.py +599 -0
- python_wrap/events.py +145 -4
- python_wrap/exporters.py +663 -0
- python_wrap/fastapi.py +81 -0
- python_wrap/flask.py +61 -0
- python_wrap/genai.py +1101 -0
- python_wrap/health.py +187 -0
- python_wrap/http.py +940 -0
- python_wrap/idempotency.py +446 -0
- python_wrap/introspect.py +738 -0
- python_wrap/lifecycle.py +620 -0
- python_wrap/llm.py +2574 -0
- python_wrap/llm_cassette.py +948 -0
- python_wrap/llm_http_chaos.py +326 -0
- python_wrap/llm_shared.py +772 -0
- python_wrap/llm_testing.py +990 -0
- python_wrap/llm_validate.py +383 -0
- python_wrap/local_state.py +395 -0
- python_wrap/logs.py +82 -26
- python_wrap/mcp.py +490 -0
- python_wrap/mcp_guard.py +357 -0
- python_wrap/metrics.py +6 -3
- python_wrap/migrate.py +1452 -0
- python_wrap/observability.py +484 -0
- python_wrap/periodic.py +24 -2
- python_wrap/policies.py +396 -0
- python_wrap/policy.py +14 -0
- python_wrap/predicates.py +276 -0
- python_wrap/presets.py +378 -0
- python_wrap/processing.py +227 -0
- python_wrap/propagation.py +62 -0
- python_wrap/pytest_plugin.py +85 -0
- python_wrap/quotas.py +319 -0
- python_wrap/ratelimit.py +560 -0
- python_wrap/redaction.py +228 -0
- python_wrap/retry.py +448 -70
- python_wrap/shared.py +653 -0
- python_wrap/singleflight.py +255 -0
- python_wrap/slow.py +72 -0
- python_wrap/stores.py +168 -0
- python_wrap/switches.py +164 -0
- python_wrap/testing.py +34 -8
- python_wrap/timeouts.py +874 -0
- python_wrap/timing.py +239 -17
- python_wrap/validation.py +187 -12
- python_wrap/web.py +723 -0
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/METADATA +117 -7
- python_wrap-0.4.0.dist-info/RECORD +95 -0
- python_wrap-0.2.1.dist-info/RECORD +0 -29
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/WHEEL +0 -0
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
"""HTTP-level fault injection for LLM clients: ``chaos.llm_http``.
|
|
2
|
+
|
|
3
|
+
`LLMHTTPFaults` reuses the rules of `python_wrap.llm_testing.LLMFaults` but delivers them
|
|
4
|
+
on the wire. Wrap any ``httpx`` transport (a real one, a ``MockTransport`` or a
|
|
5
|
+
`python_wrap.llm_cassette.ReplayTransport`) with ``chaos.llm_http.transport(inner)`` and
|
|
6
|
+
the provider SDK on top sees what a flaky API produces: real 429 and 529 responses with a
|
|
7
|
+
``Retry-After`` header, 5xx errors, a request that hangs, a read timeout, a body cut short
|
|
8
|
+
or a stream that stalls halfway. That exercises the SDK's own error mapping and your
|
|
9
|
+
retries together, which the in-process fakes cannot.
|
|
10
|
+
|
|
11
|
+
Like all chaos rules nothing happens until a rule is added.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import dataclasses
|
|
17
|
+
import json
|
|
18
|
+
from collections.abc import AsyncIterator, Iterator
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from python_wrap import _core
|
|
22
|
+
from python_wrap.chaos import Fault, FaultInjector
|
|
23
|
+
from python_wrap.llm_cassette import (
|
|
24
|
+
TransportContext,
|
|
25
|
+
_header_pairs,
|
|
26
|
+
_httpx,
|
|
27
|
+
build_response,
|
|
28
|
+
stream_class,
|
|
29
|
+
)
|
|
30
|
+
from python_wrap.llm_testing import APIStatusError, APITimeoutError, LLMFaults
|
|
31
|
+
|
|
32
|
+
__all__ = ["ChaosTransport", "LLMHTTPFaults"]
|
|
33
|
+
|
|
34
|
+
POINT = "llm.http"
|
|
35
|
+
|
|
36
|
+
_ERROR_TYPES = {
|
|
37
|
+
429: "rate_limit_error",
|
|
38
|
+
529: "overloaded_error",
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclasses.dataclass(frozen=True)
|
|
43
|
+
class _Truncate:
|
|
44
|
+
keep: float
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclasses.dataclass(frozen=True)
|
|
48
|
+
class _StallStream:
|
|
49
|
+
after_chunks: int
|
|
50
|
+
seconds: float
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class LLMHTTPFaults(LLMFaults):
|
|
54
|
+
"""LLM fault rules that act on HTTP exchanges; reach it as ``chaos.llm_http``.
|
|
55
|
+
|
|
56
|
+
Inherits ``rate_limit`` (429), ``overloaded`` (529), ``server_error`` (5xx) and
|
|
57
|
+
``timeout`` from `LLMFaults`: here they become real HTTP error responses (or a read
|
|
58
|
+
timeout) instead of Python exceptions, and the point name defaults to ``"llm.http"``.
|
|
59
|
+
Adds `stall` and `truncate`. Build the faulty transport with `transport`.
|
|
60
|
+
|
|
61
|
+
Example:
|
|
62
|
+
```python
|
|
63
|
+
from python_wrap.chaos import FaultInjector
|
|
64
|
+
from python_wrap.llm_cassette import build_response
|
|
65
|
+
from python_wrap.llm_http_chaos import LLMHTTPFaults
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class Request: # stands in for an httpx request
|
|
69
|
+
method, url, headers, content = "POST", "https://llm.example/v1", {}, b"{}"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class Wire: # stands in for the real transport
|
|
73
|
+
def handle_request(self, request):
|
|
74
|
+
return build_response(request, 200, [], [b"{}"], asynchronous=False)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
faults = LLMHTTPFaults(FaultInjector())
|
|
78
|
+
wire = faults.transport(Wire())
|
|
79
|
+
with faults.rate_limit(times=1, retry_after=2):
|
|
80
|
+
first = wire.handle_request(Request())
|
|
81
|
+
assert first.status_code == 429 and first.headers["retry-after"] == "2"
|
|
82
|
+
assert wire.handle_request(Request()).status_code == 200
|
|
83
|
+
```
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
def rate_limit(
|
|
87
|
+
self,
|
|
88
|
+
name: str = POINT,
|
|
89
|
+
*,
|
|
90
|
+
retry_after: float | None = 1.0,
|
|
91
|
+
rate: float = 1.0,
|
|
92
|
+
times: int | None = None,
|
|
93
|
+
message: str = "Rate limit exceeded",
|
|
94
|
+
) -> Fault:
|
|
95
|
+
"""Answer with HTTP 429 and a ``Retry-After`` header of ``retry_after`` seconds."""
|
|
96
|
+
return super().rate_limit(
|
|
97
|
+
name, retry_after=retry_after, rate=rate, times=times, message=message
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
def overloaded(
|
|
101
|
+
self,
|
|
102
|
+
name: str = POINT,
|
|
103
|
+
*,
|
|
104
|
+
rate: float = 1.0,
|
|
105
|
+
times: int | None = None,
|
|
106
|
+
message: str = "Overloaded",
|
|
107
|
+
) -> Fault:
|
|
108
|
+
"""Answer with HTTP 529."""
|
|
109
|
+
return super().overloaded(name, rate=rate, times=times, message=message)
|
|
110
|
+
|
|
111
|
+
def server_error(
|
|
112
|
+
self,
|
|
113
|
+
name: str = POINT,
|
|
114
|
+
*,
|
|
115
|
+
status: int = 500,
|
|
116
|
+
rate: float = 1.0,
|
|
117
|
+
times: int | None = None,
|
|
118
|
+
message: str = "Internal server error",
|
|
119
|
+
) -> Fault:
|
|
120
|
+
"""Answer with a 5xx ``status``."""
|
|
121
|
+
return super().server_error(name, status=status, rate=rate, times=times, message=message)
|
|
122
|
+
|
|
123
|
+
def timeout(
|
|
124
|
+
self,
|
|
125
|
+
name: str = POINT,
|
|
126
|
+
*,
|
|
127
|
+
after: float | None = None,
|
|
128
|
+
rate: float = 1.0,
|
|
129
|
+
times: int | None = None,
|
|
130
|
+
message: str = "Request timed out",
|
|
131
|
+
) -> Fault:
|
|
132
|
+
"""Raise a read timeout (``httpx.ReadTimeout``, else ``TimeoutError``), optionally late."""
|
|
133
|
+
return super().timeout(name, after=after, rate=rate, times=times, message=message)
|
|
134
|
+
|
|
135
|
+
def stall(
|
|
136
|
+
self,
|
|
137
|
+
name: str = POINT,
|
|
138
|
+
*,
|
|
139
|
+
seconds: float = 30.0,
|
|
140
|
+
after_chunks: int | None = None,
|
|
141
|
+
rate: float = 1.0,
|
|
142
|
+
times: int | None = None,
|
|
143
|
+
) -> Fault:
|
|
144
|
+
"""Hang for ``seconds``: before the response, or after ``after_chunks`` stream chunks.
|
|
145
|
+
|
|
146
|
+
Time passes through ``python_wrap._core``, so ``fake_clock`` skips the wait.
|
|
147
|
+
"""
|
|
148
|
+
if seconds < 0:
|
|
149
|
+
raise ValueError("seconds must be >= 0")
|
|
150
|
+
if after_chunks is None:
|
|
151
|
+
return self._injector.inject(name, latency=float(seconds), rate=rate, times=times)
|
|
152
|
+
if after_chunks < 0:
|
|
153
|
+
raise ValueError("after_chunks must be >= 0")
|
|
154
|
+
return self._injector.inject(
|
|
155
|
+
name, result=_StallStream(after_chunks, float(seconds)), rate=rate, times=times
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
def truncate(
|
|
159
|
+
self, name: str = POINT, *, keep: float = 0.5, rate: float = 1.0, times: int | None = None
|
|
160
|
+
) -> Fault:
|
|
161
|
+
"""Let the real response through but cut its body to the first ``keep`` fraction."""
|
|
162
|
+
if not 0 <= keep < 1:
|
|
163
|
+
raise ValueError("keep must be in [0, 1)")
|
|
164
|
+
return self._injector.inject(name, result=_Truncate(keep), rate=rate, times=times)
|
|
165
|
+
|
|
166
|
+
def transport(self, inner: Any, *, point: str = POINT) -> ChaosTransport:
|
|
167
|
+
"""Wrap ``inner`` so this injector's rules for ``point`` apply to its traffic."""
|
|
168
|
+
return ChaosTransport(inner, self._injector, point=point)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _error_response(request: Any, exc: APIStatusError, asynchronous: bool) -> Any:
|
|
172
|
+
status = int(exc.status_code or 500)
|
|
173
|
+
headers = [("content-type", "application/json")]
|
|
174
|
+
if exc.retry_after is not None:
|
|
175
|
+
shown = exc.retry_after
|
|
176
|
+
headers.append(
|
|
177
|
+
("retry-after", str(int(shown)) if float(shown).is_integer() else str(shown))
|
|
178
|
+
)
|
|
179
|
+
kind = _ERROR_TYPES.get(status, "api_error")
|
|
180
|
+
body = json.dumps({"type": "error", "error": {"type": kind, "message": str(exc)}})
|
|
181
|
+
return build_response(request, status, headers, [body.encode()], asynchronous=asynchronous)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _timeout_error(request: Any, message: str) -> Exception:
|
|
185
|
+
mod = _httpx()
|
|
186
|
+
if mod is not None:
|
|
187
|
+
error: Exception = mod.ReadTimeout(message, request=request)
|
|
188
|
+
return error
|
|
189
|
+
return TimeoutError(message)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
class _Stalling:
|
|
193
|
+
def __init__(self, inner: Any, after_chunks: int, seconds: float) -> None:
|
|
194
|
+
self._inner, self._after, self._seconds = inner, after_chunks, seconds
|
|
195
|
+
|
|
196
|
+
def __iter__(self) -> Iterator[bytes]:
|
|
197
|
+
for count, chunk in enumerate(self._inner):
|
|
198
|
+
if count == self._after:
|
|
199
|
+
_core.sleep(self._seconds)
|
|
200
|
+
yield chunk
|
|
201
|
+
|
|
202
|
+
async def __aiter__(self) -> AsyncIterator[bytes]:
|
|
203
|
+
count = 0
|
|
204
|
+
async for chunk in self._inner:
|
|
205
|
+
if count == self._after:
|
|
206
|
+
await _core.async_sleep(self._seconds)
|
|
207
|
+
count += 1
|
|
208
|
+
yield chunk
|
|
209
|
+
|
|
210
|
+
def close(self) -> None:
|
|
211
|
+
close = getattr(self._inner, "close", None)
|
|
212
|
+
if callable(close):
|
|
213
|
+
close()
|
|
214
|
+
|
|
215
|
+
async def aclose(self) -> None:
|
|
216
|
+
aclose = getattr(self._inner, "aclose", None)
|
|
217
|
+
if callable(aclose):
|
|
218
|
+
await aclose()
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
class ChaosTransport(TransportContext):
|
|
222
|
+
"""A transport that breaks another one on demand; build it with ``chaos.llm_http.transport``.
|
|
223
|
+
|
|
224
|
+
Args:
|
|
225
|
+
inner: The transport to wrap (anything with ``handle_request`` /
|
|
226
|
+
``handle_async_request``).
|
|
227
|
+
injector: The `FaultInjector` whose rules apply.
|
|
228
|
+
point: The fault point name rules match; ``"llm.http"`` by default.
|
|
229
|
+
"""
|
|
230
|
+
|
|
231
|
+
def __init__(self, inner: Any, injector: FaultInjector, *, point: str = POINT) -> None:
|
|
232
|
+
self.inner, self.injector, self.point = inner, injector, point
|
|
233
|
+
|
|
234
|
+
def _wrapped(self) -> Any:
|
|
235
|
+
return self.inner
|
|
236
|
+
|
|
237
|
+
def _plan(self) -> list[Any]:
|
|
238
|
+
inj = self.injector
|
|
239
|
+
return inj._plan(self.point) if inj._rules and inj.enabled else []
|
|
240
|
+
|
|
241
|
+
def _early(self, request: Any, action: Any, asynchronous: bool) -> tuple[Any, Any]:
|
|
242
|
+
"""Handle an exception/result action: ``(response, post_processing_marker)``."""
|
|
243
|
+
if action.kind == "exception":
|
|
244
|
+
exc = action.exception
|
|
245
|
+
if isinstance(exc, APIStatusError):
|
|
246
|
+
return _error_response(request, exc, asynchronous), None
|
|
247
|
+
if isinstance(exc, APITimeoutError):
|
|
248
|
+
raise _timeout_error(request, str(exc))
|
|
249
|
+
raise exc
|
|
250
|
+
return None, action.result
|
|
251
|
+
|
|
252
|
+
def _finish(self, request: Any, response: Any, post: Any, asynchronous: bool) -> Any:
|
|
253
|
+
if isinstance(post, _StallStream):
|
|
254
|
+
response.stream = stream_class(_Stalling)(
|
|
255
|
+
response.stream, post.after_chunks, post.seconds
|
|
256
|
+
)
|
|
257
|
+
return response
|
|
258
|
+
|
|
259
|
+
def _truncated(
|
|
260
|
+
self, request: Any, response: Any, body: bytes, keep: float, asynchronous: bool
|
|
261
|
+
) -> Any:
|
|
262
|
+
headers = [
|
|
263
|
+
(k, v)
|
|
264
|
+
for k, v in _header_pairs(getattr(response, "headers", None))
|
|
265
|
+
if k.lower() not in ("content-length", "content-encoding")
|
|
266
|
+
]
|
|
267
|
+
cut = body[: int(len(body) * keep)]
|
|
268
|
+
return build_response(
|
|
269
|
+
request,
|
|
270
|
+
int(response.status_code),
|
|
271
|
+
headers,
|
|
272
|
+
[cut] if cut else [],
|
|
273
|
+
asynchronous=asynchronous,
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
def handle_request(self, request: Any) -> Any:
|
|
277
|
+
"""Apply matching rules, then forward the request (sync)."""
|
|
278
|
+
post = None
|
|
279
|
+
for action in self._plan():
|
|
280
|
+
_emit(self.point, action)
|
|
281
|
+
if action.kind == "latency":
|
|
282
|
+
_core.sleep(action.seconds)
|
|
283
|
+
continue
|
|
284
|
+
response, post = self._early(request, action, False)
|
|
285
|
+
if response is not None:
|
|
286
|
+
return response
|
|
287
|
+
response = self.inner.handle_request(request)
|
|
288
|
+
if isinstance(post, _Truncate):
|
|
289
|
+
return self._truncated(request, response, bytes(response.read()), post.keep, False)
|
|
290
|
+
return self._finish(request, response, post, False)
|
|
291
|
+
|
|
292
|
+
async def handle_async_request(self, request: Any) -> Any:
|
|
293
|
+
"""Apply matching rules, then forward the request (async)."""
|
|
294
|
+
post = None
|
|
295
|
+
for action in self._plan():
|
|
296
|
+
_emit(self.point, action)
|
|
297
|
+
if action.kind == "latency":
|
|
298
|
+
await _core.async_sleep(action.seconds)
|
|
299
|
+
continue
|
|
300
|
+
response, post = self._early(request, action, True)
|
|
301
|
+
if response is not None:
|
|
302
|
+
return response
|
|
303
|
+
response = await self.inner.handle_async_request(request)
|
|
304
|
+
if isinstance(post, _Truncate):
|
|
305
|
+
reader = getattr(response, "aread", None)
|
|
306
|
+
body = bytes(await reader() if callable(reader) else response.read())
|
|
307
|
+
return self._truncated(request, response, body, post.keep, True)
|
|
308
|
+
return self._finish(request, response, post, True)
|
|
309
|
+
|
|
310
|
+
def close(self) -> None:
|
|
311
|
+
"""Close the inner transport."""
|
|
312
|
+
close = getattr(self.inner, "close", None)
|
|
313
|
+
if callable(close):
|
|
314
|
+
close()
|
|
315
|
+
|
|
316
|
+
async def aclose(self) -> None:
|
|
317
|
+
"""Close the inner transport (async)."""
|
|
318
|
+
aclose = getattr(self.inner, "aclose", None)
|
|
319
|
+
if callable(aclose):
|
|
320
|
+
await aclose()
|
|
321
|
+
else:
|
|
322
|
+
self.close()
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _emit(point: str, action: Any) -> None:
|
|
326
|
+
_core.emit("chaos.injected", point, kind=action.kind, point=point, pattern=action.pattern)
|