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,948 @@
1
+ """Record and replay LLM HTTP traffic so tests run offline, fast and deterministically.
2
+
3
+ A `Cassette` sits at the HTTP transport level, below any provider SDK: build the SDK's
4
+ ``httpx`` client with ``transport=cassette.transport()`` (or wrap a transport you already
5
+ have) and the first run talks to the real API and writes a JSON file; later runs replay
6
+ it with no network and no key. The classes are duck-typed against the ``httpx`` transport
7
+ protocol (``handle_request`` / ``handle_async_request`` taking a request with ``method``,
8
+ ``url``, ``headers`` and ``read()``/``content``); httpx is only imported lazily, to build
9
+ real ``httpx.Response`` objects, and a minimal stand-in is used when it is absent.
10
+
11
+ What a cassette guarantees:
12
+
13
+ - **Secrets are never stored.** Authorization-style headers, sensitive JSON keys,
14
+ sensitive query parameters, the literal values in ``secrets=`` and well-known key
15
+ shapes (bearer tokens, ``sk-...``, cloud keys) are masked before anything is written,
16
+ and the request key is computed from the masked form, so a changed API key still
17
+ matches.
18
+ - **Requests match by hash** of method, URL (query sorted) and JSON body (keys sorted),
19
+ after dropping ``ignore_body_keys`` / ``ignore_query``. Repeated identical requests
20
+ replay in recorded order (a 429 then a 200 replays as a 429 then a 200).
21
+ - **Streams keep their chunks**: a streamed (server-sent events) body is recorded chunk
22
+ by chunk as it is consumed and replayed with the same boundaries.
23
+ - **Strict replay**: an unrecorded request raises `CassetteMiss` instead of reaching the
24
+ network. A truncated or corrupt file raises `CassetteError`; it is never half-used.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import base64
30
+ import contextlib
31
+ import copy
32
+ import hashlib
33
+ import importlib
34
+ import json
35
+ import os
36
+ import re
37
+ import threading
38
+ from collections.abc import AsyncIterator, Callable, Iterable, Iterator, Mapping, Sequence
39
+ from types import TracebackType
40
+ from typing import Any, Literal, cast
41
+ from urllib.parse import parse_qsl, quote, urlsplit
42
+
43
+ from python_wrap import _core
44
+ from python_wrap.errors import PythonWrapError
45
+ from python_wrap.redaction import MASK, is_sensitive, redact
46
+
47
+ __all__ = [
48
+ "SECRET_FRAGMENTS",
49
+ "Cassette",
50
+ "CassetteError",
51
+ "CassetteMiss",
52
+ "RecordingTransport",
53
+ "ReplayTransport",
54
+ ]
55
+
56
+ CassetteMode = Literal["once", "record", "replay", "new"]
57
+ _MODES = ("once", "record", "replay", "new")
58
+ _VERSION = 1
59
+
60
+ #: Name fragments treated as secret in headers, JSON keys and query parameters. Unlike
61
+ #: ``redaction.DEFAULT_REDACT`` it leaves ``tokens`` alone, because LLM requests and
62
+ #: responses are full of ``max_tokens`` and ``input_tokens`` that must stay readable.
63
+ SECRET_FRAGMENTS: tuple[str, ...] = (
64
+ "password",
65
+ "passwd",
66
+ "secret",
67
+ "api_key",
68
+ "apikey",
69
+ "authorization",
70
+ "proxy_authorization",
71
+ "credential",
72
+ "private_key",
73
+ "cookie",
74
+ "set_cookie",
75
+ "access_token",
76
+ "refresh_token",
77
+ "id_token",
78
+ "auth_token",
79
+ "bearer",
80
+ "x_api_key",
81
+ "signature",
82
+ )
83
+
84
+ #: Query parameters are stricter: a bare ``key``, ``token``, ``sig`` or ``auth`` is a secret there.
85
+ _QUERY_FRAGMENTS = (*SECRET_FRAGMENTS, "key", "token", "sig", "auth")
86
+
87
+ _SECRET_TEXT = re.compile(
88
+ r"(?i)\bbearer\s+[A-Za-z0-9._~+/=-]{6,}"
89
+ r"|\bsk-[A-Za-z0-9_-]{16,}"
90
+ r"|\bAKIA[0-9A-Z]{16}\b"
91
+ r"|\bAIza[0-9A-Za-z_-]{20,}"
92
+ r"|\bgh[pousr]_[A-Za-z0-9]{20,}"
93
+ r"|\bxox[abprs]-[A-Za-z0-9-]{10,}"
94
+ r"|\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}"
95
+ )
96
+ _DROP_ON_REPLAY = frozenset({"content-length", "transfer-encoding"})
97
+ _IGNORED = object()
98
+
99
+
100
+ class CassetteError(PythonWrapError):
101
+ """A cassette file is unreadable, truncated or in an unknown format."""
102
+
103
+
104
+ class CassetteMiss(CassetteError):
105
+ """A request has no (unused) recording, and the cassette is not recording.
106
+
107
+ Attributes:
108
+ method: The request method.
109
+ url: The request URL with secrets masked.
110
+ key: The request's match key (hex digest).
111
+ """
112
+
113
+ def __init__(self, message: str, *, method: str, url: str, key: str) -> None:
114
+ super().__init__(message)
115
+ self.method, self.url, self.key = method, url, key
116
+
117
+
118
+ # ------------------------------------------------------------------------ duck typing
119
+
120
+
121
+ def _httpx() -> Any:
122
+ try:
123
+ return importlib.import_module("httpx")
124
+ except ImportError:
125
+ return None
126
+
127
+
128
+ def _header_pairs(headers: Any) -> list[tuple[str, str]]:
129
+ """Every ``(name, value)`` of a headers object, repeated names included."""
130
+ if headers is None:
131
+ return []
132
+ multi = getattr(headers, "multi_items", None)
133
+ items: Iterable[Any] = cast("Iterable[Any]", multi()) if callable(multi) else _items(headers)
134
+ pairs: list[tuple[str, str]] = []
135
+ for key, value in items:
136
+ if isinstance(key, bytes):
137
+ key = key.decode("latin-1")
138
+ if isinstance(value, bytes):
139
+ value = value.decode("latin-1")
140
+ pairs.append((str(key), str(value)))
141
+ return pairs
142
+
143
+
144
+ def _items(headers: Any) -> Iterable[Any]:
145
+ return cast("Iterable[Any]", headers.items() if hasattr(headers, "items") else headers)
146
+
147
+
148
+ def _body_of(request: Any) -> bytes:
149
+ reader = getattr(request, "read", None)
150
+ data = reader() if callable(reader) else getattr(request, "content", b"")
151
+ return _as_bytes(data)
152
+
153
+
154
+ async def _abody_of(request: Any) -> bytes:
155
+ reader = getattr(request, "aread", None)
156
+ if callable(reader):
157
+ return _as_bytes(await reader())
158
+ return _body_of(request)
159
+
160
+
161
+ def _as_bytes(data: Any) -> bytes:
162
+ if data is None:
163
+ return b""
164
+ if isinstance(data, str):
165
+ return data.encode("utf-8")
166
+ return bytes(data)
167
+
168
+
169
+ class _PlainResponse:
170
+ """The stand-in response used when httpx is not installed."""
171
+
172
+ def __init__(self, status_code: int, headers: list[tuple[str, str]], stream: Any, request: Any):
173
+ self.status_code = status_code
174
+ self.headers = dict(headers)
175
+ self.stream = stream
176
+ self.request = request
177
+ self._content: bytes | None = None
178
+
179
+ @property
180
+ def content(self) -> bytes:
181
+ if self._content is None:
182
+ self._content = b"".join(self.stream)
183
+ return self._content
184
+
185
+ def read(self) -> bytes:
186
+ return self.content
187
+
188
+ def iter_bytes(self) -> Iterator[bytes]:
189
+ yield from self.stream
190
+
191
+ def close(self) -> None:
192
+ close = getattr(self.stream, "close", None)
193
+ if callable(close):
194
+ close()
195
+
196
+
197
+ class _Chunks:
198
+ """A replayable chunk list usable as a sync or an async byte stream."""
199
+
200
+ def __init__(self, chunks: Sequence[bytes], then: BaseException | None = None) -> None:
201
+ self._chunks, self._then = list(chunks), then
202
+
203
+ def __iter__(self) -> Iterator[bytes]:
204
+ yield from self._chunks
205
+ if self._then is not None:
206
+ raise self._then
207
+
208
+ async def __aiter__(self) -> AsyncIterator[bytes]:
209
+ for chunk in self._chunks:
210
+ yield chunk
211
+ if self._then is not None:
212
+ raise self._then
213
+
214
+ def close(self) -> None:
215
+ return None
216
+
217
+ async def aclose(self) -> None:
218
+ return None
219
+
220
+
221
+ def build_response(
222
+ request: Any,
223
+ status: int,
224
+ headers: Sequence[tuple[str, str]],
225
+ chunks: Sequence[bytes],
226
+ *,
227
+ asynchronous: bool,
228
+ then: BaseException | None = None,
229
+ ) -> Any:
230
+ """Make a response object (``httpx.Response`` when httpx is installed) from recorded parts."""
231
+ kept = [(k, v) for k, v in headers if k.lower() not in _DROP_ON_REPLAY]
232
+ mod = _httpx()
233
+ if mod is None:
234
+ return _PlainResponse(status, kept, _Chunks(chunks, then), request)
235
+ body = _Chunks(chunks, then)
236
+ content: Any = body.__aiter__() if asynchronous else iter(body)
237
+ if then is None and not asynchronous:
238
+ content = b"".join(chunks) if len(chunks) <= 1 else iter(body)
239
+ return mod.Response(status, headers=kept, content=content, request=request)
240
+
241
+
242
+ # -------------------------------------------------------------------------- recording
243
+
244
+
245
+ class _Tee:
246
+ """Passes a response's byte stream through while remembering its chunks."""
247
+
248
+ def __init__(self, inner: Any, finish: Callable[[list[bytes], bool], None]) -> None:
249
+ self._inner, self._finish = inner, finish
250
+ self._chunks: list[bytes] = []
251
+ self._complete = False
252
+ self._done = False
253
+ self._lock = threading.Lock()
254
+
255
+ def _settle(self) -> None:
256
+ with self._lock:
257
+ if self._done:
258
+ return
259
+ self._done = True
260
+ self._finish(self._chunks, self._complete)
261
+
262
+ def __iter__(self) -> Iterator[bytes]:
263
+ try:
264
+ for chunk in self._inner:
265
+ self._chunks.append(bytes(chunk))
266
+ yield chunk
267
+ self._complete = True
268
+ finally:
269
+ self._settle()
270
+
271
+ async def __aiter__(self) -> AsyncIterator[bytes]:
272
+ try:
273
+ async for chunk in self._inner:
274
+ self._chunks.append(bytes(chunk))
275
+ yield chunk
276
+ self._complete = True
277
+ finally:
278
+ self._settle()
279
+
280
+ def close(self) -> None:
281
+ try:
282
+ close = getattr(self._inner, "close", None)
283
+ if callable(close):
284
+ close()
285
+ finally:
286
+ self._settle()
287
+
288
+ async def aclose(self) -> None:
289
+ try:
290
+ aclose = getattr(self._inner, "aclose", None)
291
+ if callable(aclose):
292
+ await aclose()
293
+ finally:
294
+ self._settle()
295
+
296
+
297
+ def _tee_for(inner: Any, finish: Callable[[list[bytes], bool], None]) -> Any:
298
+ """A `_Tee` that is also an instance of httpx's stream base classes when present."""
299
+ return stream_class(_Tee)(inner, finish)
300
+
301
+
302
+ _STREAM_CLASSES: dict[tuple[type, int], type] = {}
303
+
304
+
305
+ def stream_class(impl: type) -> type:
306
+ """``impl`` extended with httpx's sync and async byte-stream bases, when httpx exists.
307
+
308
+ httpx checks ``isinstance(response.stream, SyncByteStream)``, so a stream wrapper must
309
+ inherit from them; doing it here keeps httpx a lazy, optional import.
310
+ """
311
+ mod = _httpx()
312
+ if mod is None:
313
+ return impl
314
+ found = _STREAM_CLASSES.get((impl, id(mod)))
315
+ if found is None:
316
+ bases = tuple(
317
+ b
318
+ for b in (getattr(mod, "SyncByteStream", None), getattr(mod, "AsyncByteStream", None))
319
+ if isinstance(b, type)
320
+ )
321
+ found = type(f"_Httpx{impl.__name__}", (impl, *bases), {})
322
+ _STREAM_CLASSES[(impl, id(mod))] = found
323
+ return found
324
+
325
+
326
+ # ---------------------------------------------------------------------------- cassette
327
+
328
+
329
+ def _mask_text(text: str, secrets: Sequence[str]) -> str:
330
+ for secret in secrets:
331
+ text = text.replace(secret, MASK)
332
+ return _SECRET_TEXT.sub(MASK, text)
333
+
334
+
335
+ def _clean(value: Any, secrets: Sequence[str]) -> Any:
336
+ """Mask secret-looking text in every string of a JSON value (keys untouched)."""
337
+ if isinstance(value, str):
338
+ return _mask_text(value, secrets)
339
+ if isinstance(value, Mapping):
340
+ return {k: _clean(v, secrets) for k, v in value.items()}
341
+ if isinstance(value, (list, tuple)):
342
+ return [_clean(v, secrets) for v in value]
343
+ return value
344
+
345
+
346
+ def _drop_keys(value: Any, names: frozenset[str], paths: frozenset[str], path: str = "") -> Any:
347
+ if isinstance(value, Mapping):
348
+ out: dict[str, Any] = {}
349
+ for key, item in value.items():
350
+ here = f"{path}.{key}" if path else str(key)
351
+ if str(key) in names or here in paths:
352
+ continue
353
+ out[key] = _drop_keys(item, names, paths, here)
354
+ return out
355
+ if isinstance(value, list):
356
+ return [_drop_keys(item, names, paths, path) for item in value]
357
+ return value
358
+
359
+
360
+ def _encode_body(chunks: Sequence[bytes], secrets: Sequence[str]) -> dict[str, Any]:
361
+ """The cassette form of a body: masked UTF-8 text, or base64 when it is not text."""
362
+ try:
363
+ texts = [chunk.decode("utf-8") for chunk in chunks]
364
+ except UnicodeDecodeError:
365
+ try:
366
+ texts = [b"".join(chunks).decode("utf-8")]
367
+ except UnicodeDecodeError:
368
+ return {
369
+ "encoding": "base64",
370
+ "chunks": [base64.b64encode(chunk).decode("ascii") for chunk in chunks],
371
+ }
372
+ joined = "".join(texts)
373
+ masked = _mask_text(joined, secrets)
374
+ if masked != joined: # a secret may straddle chunks: keep one masked chunk
375
+ texts = [masked]
376
+ return {"encoding": "utf-8", "chunks": texts}
377
+
378
+
379
+ def _decode_body(body: Mapping[str, Any]) -> list[bytes]:
380
+ chunks = body["chunks"]
381
+ if body["encoding"] == "base64":
382
+ return [base64.b64decode(c) for c in chunks]
383
+ if body["encoding"] == "utf-8":
384
+ return [c.encode("utf-8") for c in chunks]
385
+ raise ValueError(f"unknown body encoding {body['encoding']!r}")
386
+
387
+
388
+ class Cassette:
389
+ """A file of recorded HTTP exchanges, used through `transport`.
390
+
391
+ Args:
392
+ path: The JSON file (parent directories are created on save).
393
+ mode: ``"once"`` (default) replays when the file exists and records when it does
394
+ not; ``"replay"`` never touches the network (unrecorded requests raise
395
+ `CassetteMiss`); ``"record"`` ignores any existing file and records
396
+ everything; ``"new"`` replays recorded requests and records the rest.
397
+ ignore_body_keys: JSON body keys left out of matching and storage, anywhere in
398
+ the body (``"user"``) or by dotted path from the root (``"metadata.run_id"``).
399
+ ignore_query: Query parameter names left out of matching.
400
+ ignore_host: Match on path and query only, so a base-URL change still replays.
401
+ match_headers: Header names (lowercase) whose values must also match.
402
+ redactor: ``redactor(obj) -> obj`` applied to the request headers mapping and the
403
+ decoded JSON request body before they are stored and hashed; the default masks
404
+ keys named by `SECRET_FRAGMENTS`.
405
+ redact_responses: Apply ``redactor`` to non-streamed JSON response bodies too
406
+ (text-level secret masking always applies).
407
+ secrets: Literal secret values (an API key you hold) masked everywhere.
408
+ allow_repeat: When every recording of a request has been replayed, serve the last
409
+ one again instead of raising `CassetteMiss`.
410
+ autosave: Write the file after every recorded exchange (otherwise on `save` or on
411
+ leaving the ``with`` block).
412
+
413
+ Example:
414
+ ```python
415
+ import os
416
+ import tempfile
417
+
418
+ from python_wrap.llm_cassette import Cassette
419
+
420
+ class Call: # a stand-in for an httpx request
421
+ method, url, headers = "POST", "https://llm.example/v1/chat", {"x-api-key": "k-123"}
422
+ content = b'{"model": "m", "messages": []}'
423
+
424
+ class Wire: # a stand-in for the real network transport
425
+ def handle_request(self, request):
426
+ from python_wrap.llm_cassette import build_response
427
+ return build_response(request, 200, [("content-type", "application/json")],
428
+ [b'{"text": "hi"}'], asynchronous=False)
429
+
430
+ path = os.path.join(tempfile.mkdtemp(), "chat.json")
431
+ first = Cassette(path).transport(Wire()).handle_request(Call())
432
+ assert first.read() == b'{"text": "hi"}'
433
+ replay = Cassette(path).transport() # no network object needed any more
434
+ assert replay.handle_request(Call()).read() == b'{"text": "hi"}'
435
+ assert "k-123" not in open(path).read()
436
+ ```
437
+ """
438
+
439
+ def __init__(
440
+ self,
441
+ path: str | os.PathLike[str],
442
+ *,
443
+ mode: CassetteMode = "once",
444
+ ignore_body_keys: Iterable[str] = (),
445
+ ignore_query: Iterable[str] = (),
446
+ ignore_host: bool = False,
447
+ match_headers: Iterable[str] = (),
448
+ redactor: Callable[[Any], Any] | None = None,
449
+ redact_responses: bool = False,
450
+ secrets: Iterable[str] = (),
451
+ allow_repeat: bool = False,
452
+ autosave: bool = True,
453
+ ) -> None:
454
+ if mode not in _MODES:
455
+ raise ValueError(f"mode must be one of {', '.join(_MODES)}; got {mode!r}")
456
+ self.path = os.fspath(path)
457
+ self.mode = mode
458
+ names: set[str] = set()
459
+ paths: set[str] = set()
460
+ for item in ignore_body_keys:
461
+ (paths if "." in item else names).add(item)
462
+ self._names, self._paths = frozenset(names), frozenset(paths)
463
+ self._ignore_query = frozenset(ignore_query)
464
+ self.ignore_host = ignore_host
465
+ self._match_headers = tuple(h.lower() for h in match_headers)
466
+ self._redactor = redactor
467
+ self.redact_responses = redact_responses
468
+ self._secrets = tuple(s for s in secrets if isinstance(s, str) and len(s) >= 4)
469
+ self.allow_repeat, self.autosave = allow_repeat, autosave
470
+ self._lock = threading.RLock()
471
+ self._entries: list[dict[str, Any]] = []
472
+ self._used: set[int] = set()
473
+ self.recorded = 0
474
+ self.replayed = 0
475
+ exists = os.path.exists(self.path)
476
+ self.replaying = mode == "replay" or (mode == "once" and exists)
477
+ self.recording = mode in ("record", "new") or (mode == "once" and not exists)
478
+ if mode == "replay" and not exists:
479
+ raise CassetteError(f"cassette {self.path!r} does not exist (mode='replay')")
480
+ if exists and mode != "record":
481
+ self._entries = self._load()
482
+
483
+ # -- file -----------------------------------------------------------------------
484
+ def _load(self) -> list[dict[str, Any]]:
485
+ try:
486
+ with open(self.path, encoding="utf-8") as handle:
487
+ data = json.load(handle)
488
+ except (ValueError, UnicodeDecodeError) as exc:
489
+ raise CassetteError(
490
+ f"cassette {self.path!r} is truncated or corrupt ({type(exc).__name__}); "
491
+ "re-record it with mode='record'"
492
+ ) from exc
493
+ if (
494
+ not isinstance(data, dict)
495
+ or data.get("version") != _VERSION
496
+ or not isinstance(data.get("entries"), list)
497
+ ):
498
+ raise CassetteError(f"cassette {self.path!r} has an unknown format")
499
+ entries = data["entries"]
500
+ for entry in entries:
501
+ try:
502
+ _decode_body(entry["response"]["body"])
503
+ int(entry["response"]["status"])
504
+ str(entry["key"])
505
+ except (KeyError, TypeError, ValueError) as exc:
506
+ raise CassetteError(f"cassette {self.path!r} has a damaged entry: {exc}") from exc
507
+ return [dict(e) for e in entries]
508
+
509
+ def save(self) -> None:
510
+ """Write the file atomically (temp file, then rename), readable by the owner only."""
511
+ with self._lock:
512
+ payload = json.dumps(
513
+ {"version": _VERSION, "entries": self._entries}, indent=2, ensure_ascii=False
514
+ )
515
+ folder = os.path.dirname(os.path.abspath(self.path))
516
+ os.makedirs(folder, exist_ok=True)
517
+ tmp = f"{self.path}.{os.getpid()}.{threading.get_ident()}.tmp"
518
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
519
+ try:
520
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
521
+ handle.write(payload)
522
+ os.replace(tmp, self.path)
523
+ except BaseException:
524
+ with contextlib.suppress(OSError):
525
+ os.unlink(tmp)
526
+ raise
527
+
528
+ def __enter__(self) -> Cassette:
529
+ return self
530
+
531
+ def __exit__(
532
+ self,
533
+ exc_type: type[BaseException] | None,
534
+ exc: BaseException | None,
535
+ tb: TracebackType | None,
536
+ ) -> None:
537
+ if self.recorded and exc_type is None:
538
+ self.save()
539
+
540
+ @property
541
+ def entries(self) -> list[dict[str, Any]]:
542
+ """A deep copy of the recorded exchanges (already free of secrets)."""
543
+ with self._lock:
544
+ return copy.deepcopy(self._entries)
545
+
546
+ @property
547
+ def size(self) -> int:
548
+ """How many exchanges the cassette holds."""
549
+ with self._lock:
550
+ return len(self._entries)
551
+
552
+ @property
553
+ def unused(self) -> int:
554
+ """How many recorded exchanges have not been replayed."""
555
+ with self._lock:
556
+ return len(self._entries) - len(self._used)
557
+
558
+ def assert_all_replayed(self) -> None:
559
+ """Raise `AssertionError` when some recorded exchange was never replayed."""
560
+ if self.unused:
561
+ raise AssertionError(
562
+ f"{self.unused} recorded request(s) in {self.path!r} never replayed"
563
+ )
564
+
565
+ # -- describing requests ------------------------------------------------------------
566
+ def _redact(self, obj: Any) -> Any:
567
+ if self._redactor is not None:
568
+ return self._redactor(obj)
569
+ return redact(obj, fragments=SECRET_FRAGMENTS)
570
+
571
+ def _url(self, url: str) -> tuple[str, str]:
572
+ """The masked URL to store and the canonical form to hash."""
573
+ parts = urlsplit(url)
574
+ pairs = []
575
+ for name, value in parse_qsl(parts.query, keep_blank_values=True):
576
+ if is_sensitive(name, _QUERY_FRAGMENTS, match="segment"):
577
+ value = MASK
578
+ pairs.append((name, _mask_text(value, self._secrets)))
579
+ shown = "&".join(f"{quote(n, safe='')}={quote(v, safe='*')}" for n, v in pairs)
580
+ host = f"{parts.scheme}://{parts.hostname or ''}" + (f":{parts.port}" if parts.port else "")
581
+ stored = f"{host}{parts.path}" + (f"?{shown}" if shown else "")
582
+ keep = sorted((n, v) for n, v in pairs if n not in self._ignore_query)
583
+ canonical = ("" if self.ignore_host else host) + parts.path + repr(keep)
584
+ return _mask_text(stored, self._secrets), canonical
585
+
586
+ def _headers(self, pairs: Sequence[tuple[str, str]]) -> list[list[str]]:
587
+ masked = self._redact(dict(pairs))
588
+ out: list[list[str]] = []
589
+ for name, value in pairs:
590
+ hidden = isinstance(masked, Mapping) and masked.get(name) == MASK
591
+ if hidden or is_sensitive(name.replace("-", "_"), SECRET_FRAGMENTS):
592
+ value = MASK
593
+ out.append([name, _mask_text(value, self._secrets)])
594
+ return out
595
+
596
+ def describe(
597
+ self, method: str, url: str, headers: Any, body: bytes
598
+ ) -> tuple[str, dict[str, Any]]:
599
+ """The match key and the secret-free stored form of a request."""
600
+ stored_url, canonical_url = self._url(url)
601
+ pairs = _header_pairs(headers)
602
+ shown_headers = self._headers(pairs)
603
+ decoded: Any = _IGNORED
604
+ if body:
605
+ try:
606
+ decoded = json.loads(body)
607
+ except (ValueError, UnicodeDecodeError):
608
+ decoded = _IGNORED
609
+ if decoded is not _IGNORED:
610
+ trimmed = _drop_keys(decoded, self._names, self._paths)
611
+ safe = _clean(self._redact(trimmed), self._secrets)
612
+ stored_body: dict[str, Any] = {"encoding": "json", "json": safe}
613
+ canonical_body: Any = safe
614
+ else:
615
+ stored_body = _encode_body([body], self._secrets)
616
+ canonical_body = stored_body
617
+ wanted = {
618
+ name: next((v for k, v in pairs if k.lower() == name), None)
619
+ for name in self._match_headers
620
+ }
621
+ canonical = json.dumps(
622
+ [method.upper(), canonical_url, canonical_body, wanted],
623
+ sort_keys=True,
624
+ separators=(",", ":"),
625
+ ensure_ascii=False,
626
+ default=str,
627
+ )
628
+ key = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
629
+ return key, {
630
+ "method": method.upper(),
631
+ "url": stored_url,
632
+ "headers": shown_headers,
633
+ "body": stored_body,
634
+ }
635
+
636
+ def _describe_request(self, request: Any, body: bytes) -> tuple[str, dict[str, Any]]:
637
+ return self.describe(
638
+ str(request.method), str(request.url), getattr(request, "headers", None), body
639
+ )
640
+
641
+ # -- recording and replaying ----------------------------------------------------------
642
+ def add(
643
+ self,
644
+ key: str,
645
+ request: dict[str, Any],
646
+ status: int,
647
+ headers: Sequence[tuple[str, str]],
648
+ chunks: Sequence[bytes],
649
+ complete: bool = True,
650
+ ) -> None:
651
+ """Store one exchange (headers and body are masked here) and autosave."""
652
+ shown = self._headers(list(headers))
653
+ body = _encode_body(chunks, self._secrets)
654
+ if self.redact_responses and body["encoding"] == "utf-8" and len(body["chunks"]) == 1:
655
+ with contextlib.suppress(ValueError):
656
+ inner = json.loads(body["chunks"][0])
657
+ body["chunks"] = [json.dumps(self._redact(inner), ensure_ascii=False)]
658
+ entry = {
659
+ "key": key,
660
+ "request": request,
661
+ "response": {
662
+ "status": int(status),
663
+ "headers": shown,
664
+ "body": body,
665
+ "complete": complete,
666
+ },
667
+ }
668
+ with self._lock:
669
+ self._entries.append(entry)
670
+ self.recorded += 1
671
+ if self.autosave:
672
+ self.save()
673
+ _core.emit("llm.cassette_recorded", "cassette", status=int(status), key=key[:12])
674
+
675
+ def lookup(self, key: str) -> tuple[int, dict[str, Any]] | None:
676
+ """The next unused recording for ``key`` (or the last one with ``allow_repeat``)."""
677
+ with self._lock:
678
+ last = None
679
+ for index, entry in enumerate(self._entries):
680
+ if entry["key"] != key:
681
+ continue
682
+ last = index
683
+ if index not in self._used:
684
+ self._used.add(index)
685
+ self.replayed += 1
686
+ return index, entry
687
+ if last is not None and self.allow_repeat:
688
+ self.replayed += 1
689
+ return last, self._entries[last]
690
+ return None
691
+
692
+ def knows(self, key: str) -> bool:
693
+ """Whether ``key`` has any recording, used or not."""
694
+ with self._lock:
695
+ return any(e["key"] == key for e in self._entries)
696
+
697
+ def transport(self, inner: Any = None) -> Any:
698
+ """A transport for the cassette's mode.
699
+
700
+ Args:
701
+ inner: The real transport to record from (``httpx.HTTPTransport()`` when
702
+ omitted and httpx is installed). Not needed when only replaying.
703
+
704
+ Returns:
705
+ A `ReplayTransport` or a `RecordingTransport`, to pass as ``transport=`` to
706
+ an ``httpx`` client (sync or async) or to the provider SDK's ``http_client``.
707
+ """
708
+ if self.replaying and self.mode != "new":
709
+ return ReplayTransport(self)
710
+ if self.mode == "new":
711
+ return ReplayTransport(self, fallback=RecordingTransport(self, inner))
712
+ return RecordingTransport(self, inner)
713
+
714
+
715
+ # ----------------------------------------------------------------------- transports
716
+
717
+
718
+ class _DefaultWire:
719
+ """httpx's real transports, created on first use."""
720
+
721
+ def __init__(self) -> None:
722
+ self._sync: Any = None
723
+ self._async: Any = None
724
+
725
+ def handle_request(self, request: Any) -> Any:
726
+ if self._sync is None:
727
+ self._sync = _require_httpx().HTTPTransport()
728
+ return self._sync.handle_request(request)
729
+
730
+ async def handle_async_request(self, request: Any) -> Any:
731
+ if self._async is None:
732
+ self._async = _require_httpx().AsyncHTTPTransport()
733
+ return await self._async.handle_async_request(request)
734
+
735
+ def close(self) -> None:
736
+ if self._sync is not None:
737
+ self._sync.close()
738
+
739
+ async def aclose(self) -> None:
740
+ if self._async is not None:
741
+ await self._async.aclose()
742
+
743
+
744
+ def _require_httpx() -> Any:
745
+ mod = _httpx()
746
+ if mod is None:
747
+ raise RuntimeError("recording needs an inner transport (httpx is not installed)")
748
+ return mod
749
+
750
+
751
+ def _force_identity(request: Any) -> None:
752
+ """Ask for an uncompressed body so the cassette can mask secrets in it."""
753
+ headers = getattr(request, "headers", None)
754
+ with contextlib.suppress(Exception):
755
+ if headers is not None:
756
+ headers["accept-encoding"] = "identity"
757
+
758
+
759
+ class TransportContext:
760
+ """``with`` / ``async with`` support and closing for transports that wrap another.
761
+
762
+ httpx enters its transport when a client is entered, so every wrapper forwards the
763
+ context to the transport it wraps (``_wrapped``).
764
+ """
765
+
766
+ def _wrapped(self) -> Any:
767
+ return None
768
+
769
+ def __enter__(self) -> Any:
770
+ inner = self._wrapped()
771
+ if inner is not None and hasattr(inner, "__enter__"):
772
+ inner.__enter__()
773
+ return self
774
+
775
+ def __exit__(
776
+ self,
777
+ exc_type: type[BaseException] | None = None,
778
+ exc: BaseException | None = None,
779
+ tb: TracebackType | None = None,
780
+ ) -> None:
781
+ inner = self._wrapped()
782
+ if inner is not None and hasattr(inner, "__exit__"):
783
+ inner.__exit__(exc_type, exc, tb)
784
+ elif inner is not None and callable(getattr(inner, "close", None)):
785
+ inner.close()
786
+
787
+ async def __aenter__(self) -> Any:
788
+ inner = self._wrapped()
789
+ if inner is not None and hasattr(inner, "__aenter__"):
790
+ await inner.__aenter__()
791
+ return self
792
+
793
+ async def __aexit__(
794
+ self,
795
+ exc_type: type[BaseException] | None = None,
796
+ exc: BaseException | None = None,
797
+ tb: TracebackType | None = None,
798
+ ) -> None:
799
+ inner = self._wrapped()
800
+ if inner is not None and hasattr(inner, "__aexit__"):
801
+ await inner.__aexit__(exc_type, exc, tb)
802
+ elif inner is not None and callable(getattr(inner, "aclose", None)):
803
+ await inner.aclose()
804
+
805
+
806
+ class RecordingTransport(TransportContext):
807
+ """Forwards requests to a real transport and records each exchange in a `Cassette`.
808
+
809
+ Streamed bodies are passed through as they arrive and written to the cassette when the
810
+ stream ends or is closed (an early close is recorded as incomplete). Requests are sent
811
+ with ``accept-encoding: identity`` so recorded bodies are readable text.
812
+
813
+ Args:
814
+ cassette: Where to record.
815
+ inner: The transport to forward to; httpx's default transports when omitted.
816
+ """
817
+
818
+ def __init__(self, cassette: Cassette, inner: Any = None) -> None:
819
+ self.cassette = cassette
820
+ self.inner = inner if inner is not None else _DefaultWire()
821
+
822
+ def _wrap(self, request: Any, response: Any, key: str, described: dict[str, Any]) -> Any:
823
+ headers = _header_pairs(getattr(response, "headers", None))
824
+ status = int(response.status_code)
825
+ if getattr(response, "is_stream_consumed", False) and hasattr(response, "content"):
826
+ kept = [(k, v) for k, v in headers if k.lower() != "content-encoding"]
827
+ self.cassette.add(key, described, status, kept, [_as_bytes(response.content)], True)
828
+ return response
829
+
830
+ def finish(chunks: list[bytes], complete: bool) -> None:
831
+ self.cassette.add(key, described, status, headers, chunks, complete)
832
+
833
+ response.stream = _tee_for(response.stream, finish)
834
+ return response
835
+
836
+ def _wrapped(self) -> Any:
837
+ return self.inner
838
+
839
+ def handle_request(self, request: Any) -> Any:
840
+ """Forward one request (sync) and record the exchange."""
841
+ key, described = self.cassette._describe_request(request, _body_of(request))
842
+ _force_identity(request)
843
+ response = self.inner.handle_request(request)
844
+ return self._wrap(request, response, key, described)
845
+
846
+ async def handle_async_request(self, request: Any) -> Any:
847
+ """Forward one request (async) and record the exchange."""
848
+ key, described = self.cassette._describe_request(request, await _abody_of(request))
849
+ _force_identity(request)
850
+ response = await self.inner.handle_async_request(request)
851
+ return self._wrap(request, response, key, described)
852
+
853
+ def close(self) -> None:
854
+ """Close the inner transport."""
855
+ close = getattr(self.inner, "close", None)
856
+ if callable(close):
857
+ close()
858
+
859
+ async def aclose(self) -> None:
860
+ """Close the inner transport (async)."""
861
+ aclose = getattr(self.inner, "aclose", None)
862
+ if callable(aclose):
863
+ await aclose()
864
+ else:
865
+ self.close()
866
+
867
+
868
+ class ReplayTransport(TransportContext):
869
+ """Answers requests from a `Cassette` without any network access.
870
+
871
+ A request with no unused recording raises `CassetteMiss` (strict replay), unless a
872
+ ``fallback`` transport was given (the ``"new"`` mode), which then handles and records it.
873
+ A recorded stream that was closed early replays its chunks and then raises
874
+ `CassetteError` if the caller reads further.
875
+
876
+ Args:
877
+ cassette: What to replay.
878
+ fallback: A `RecordingTransport` for unrecorded requests; none means fail.
879
+ """
880
+
881
+ def __init__(self, cassette: Cassette, fallback: RecordingTransport | None = None) -> None:
882
+ self.cassette = cassette
883
+ self.fallback = fallback
884
+
885
+ def _miss(self, request: Any, key: str, described: dict[str, Any]) -> CassetteMiss:
886
+ seen = self.cassette.knows(key)
887
+ why = (
888
+ "every recording of it was already replayed"
889
+ if seen
890
+ else f"nothing like it is recorded ({self.cassette.size} exchange(s) in the file)"
891
+ )
892
+ return CassetteMiss(
893
+ f"cassette {self.cassette.path!r}: {described['method']} {described['url']} "
894
+ f"(key {key[:12]}) cannot be served: {why}. Re-record with mode='record' "
895
+ "or 'new' if the request legitimately changed.",
896
+ method=described["method"],
897
+ url=described["url"],
898
+ key=key,
899
+ )
900
+
901
+ def _serve(self, request: Any, key: str, described: dict[str, Any], asynchronous: bool) -> Any:
902
+ found = self.cassette.lookup(key)
903
+ if found is None:
904
+ return None
905
+ recorded = found[1]["response"]
906
+ headers = [(str(k), str(v)) for k, v in recorded["headers"]]
907
+ then = (
908
+ None
909
+ if recorded.get("complete", True)
910
+ else CassetteError("the recorded stream was closed before it finished")
911
+ )
912
+ chunks = _decode_body(recorded["body"])
913
+ return build_response(
914
+ request, int(recorded["status"]), headers, chunks, asynchronous=asynchronous, then=then
915
+ )
916
+
917
+ def _wrapped(self) -> Any:
918
+ return self.fallback
919
+
920
+ def handle_request(self, request: Any) -> Any:
921
+ """Replay one request (sync)."""
922
+ key, described = self.cassette._describe_request(request, _body_of(request))
923
+ response = self._serve(request, key, described, False)
924
+ if response is not None:
925
+ return response
926
+ if self.fallback is not None:
927
+ return self.fallback.handle_request(request)
928
+ raise self._miss(request, key, described)
929
+
930
+ async def handle_async_request(self, request: Any) -> Any:
931
+ """Replay one request (async)."""
932
+ key, described = self.cassette._describe_request(request, await _abody_of(request))
933
+ response = self._serve(request, key, described, True)
934
+ if response is not None:
935
+ return response
936
+ if self.fallback is not None:
937
+ return await self.fallback.handle_async_request(request)
938
+ raise self._miss(request, key, described)
939
+
940
+ def close(self) -> None:
941
+ """Close the fallback transport, if any."""
942
+ if self.fallback is not None:
943
+ self.fallback.close()
944
+
945
+ async def aclose(self) -> None:
946
+ """Close the fallback transport, if any (async)."""
947
+ if self.fallback is not None:
948
+ await self.fallback.aclose()