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,990 @@
1
+ """Test doubles for LLM-calling code: a scripted fake provider and LLM-shaped faults.
2
+
3
+ Two pieces work together with `python_wrap.chaos` and `python_wrap.testing.fake_clock`:
4
+
5
+ * `FakeProvider` (built by `fake_llm`) is a deterministic stand-in for a model API. It plays
6
+ back a script of replies, streams them in chunks with configurable delays, records every
7
+ call, reports token usage in Anthropic style (``input_tokens``/``output_tokens``) or OpenAI
8
+ style (``prompt_tokens``/``completion_tokens``) and can raise scripted errors.
9
+ * ``chaos.llm`` (an `LLMFaults`) adds LLM-specific faults to the ordinary fault injector:
10
+ rate limits with ``Retry-After``, overloaded (529) and server errors, timeouts, truncated
11
+ JSON, slow first tokens, stalled streams, tool calls with invalid arguments and
12
+ content-policy refusals. Rules take the usual ``name``/``rate``/``times`` arguments and can
13
+ be loaded from ``PW_CHAOS`` with an ``"llm"`` key.
14
+
15
+ No provider SDK is imported anywhere. The errors raised here are duck-typed look-alikes
16
+ (``status_code``, ``response.status_code``, familiar class names), so retry and
17
+ classification code that matches errors by those attributes treats them like the real thing.
18
+
19
+ All waiting goes through `python_wrap._core`, so under ``fake_clock`` stream delays advance
20
+ the fake clock and a test finishes in milliseconds.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import re
27
+ import threading
28
+ from collections.abc import AsyncIterator, Callable, Iterator, Mapping, Sequence
29
+ from dataclasses import dataclass
30
+ from types import SimpleNamespace, TracebackType
31
+ from typing import TYPE_CHECKING, Any
32
+
33
+ from python_wrap import _core
34
+ from python_wrap.chaos import FaultInjector, fault_point
35
+
36
+ if TYPE_CHECKING:
37
+ from python_wrap.chaos import Fault
38
+
39
+ __all__ = [
40
+ "APIConnectionError",
41
+ "APIStatusError",
42
+ "APITimeoutError",
43
+ "FakeCall",
44
+ "FakeChunk",
45
+ "FakeProvider",
46
+ "FakeProviderExhausted",
47
+ "FakeResponse",
48
+ "FakeStream",
49
+ "InternalServerError",
50
+ "LLMError",
51
+ "LLMFaults",
52
+ "OverloadedError",
53
+ "RateLimitError",
54
+ "ToolCall",
55
+ "fake_llm",
56
+ ]
57
+
58
+ # ------------------------------------------------------------------------------ errors
59
+
60
+
61
+ class LLMError(Exception):
62
+ """Base class of the look-alike provider errors raised by the fakes."""
63
+
64
+
65
+ class _FakeHTTPResponse:
66
+ def __init__(self, status_code: int, headers: Mapping[str, str]) -> None:
67
+ self.status_code = status_code
68
+ self.headers = dict(headers)
69
+
70
+
71
+ class APIStatusError(LLMError):
72
+ """An HTTP error status from a model API.
73
+
74
+ Attributes:
75
+ status_code: The HTTP status.
76
+ response: A minimal object with ``status_code`` and ``headers``.
77
+ retry_after: Seconds from a ``Retry-After`` header, or ``None``.
78
+ body: The decoded error body.
79
+ """
80
+
81
+ default_status = 500
82
+
83
+ def __init__(
84
+ self,
85
+ message: str = "",
86
+ *,
87
+ status_code: int | None = None,
88
+ retry_after: float | None = None,
89
+ headers: Mapping[str, str] | None = None,
90
+ body: Any = None,
91
+ ) -> None:
92
+ code = self.default_status if status_code is None else status_code
93
+ super().__init__(message or f"Error code: {code}")
94
+ self.message = message or f"Error code: {code}"
95
+ self.status_code = code
96
+ self.retry_after = retry_after
97
+ merged = dict(headers or {})
98
+ if retry_after is not None:
99
+ merged.setdefault("retry-after", f"{retry_after:g}")
100
+ self.response = _FakeHTTPResponse(code, merged)
101
+ self.body = body
102
+
103
+
104
+ class RateLimitError(APIStatusError):
105
+ """HTTP 429, optionally with a ``Retry-After`` hint."""
106
+
107
+ default_status = 429
108
+
109
+
110
+ class OverloadedError(APIStatusError):
111
+ """HTTP 529: the service is overloaded."""
112
+
113
+ default_status = 529
114
+
115
+
116
+ class InternalServerError(APIStatusError):
117
+ """HTTP 5xx server error (500 by default)."""
118
+
119
+ default_status = 500
120
+
121
+
122
+ class APITimeoutError(LLMError, TimeoutError):
123
+ """The request or stream timed out."""
124
+
125
+
126
+ class APIConnectionError(LLMError, ConnectionError):
127
+ """The connection to the API failed."""
128
+
129
+
130
+ class FakeProviderExhausted(LLMError, LookupError):
131
+ """A `FakeProvider` was called more often than its script allows."""
132
+
133
+
134
+ # ---------------------------------------------------------------------------- responses
135
+
136
+
137
+ def make_usage(style: str, input_tokens: int, output_tokens: int) -> Any:
138
+ """A usage object in ``"anthropic"`` or ``"openai"`` style."""
139
+ if style == "anthropic":
140
+ return SimpleNamespace(input_tokens=input_tokens, output_tokens=output_tokens)
141
+ if style == "openai":
142
+ return SimpleNamespace(
143
+ prompt_tokens=input_tokens,
144
+ completion_tokens=output_tokens,
145
+ total_tokens=input_tokens + output_tokens,
146
+ )
147
+ raise ValueError("style must be 'anthropic' or 'openai'")
148
+
149
+
150
+ def _tokens(usage: Any) -> tuple[int, int]:
151
+ for a, b in (("input_tokens", "output_tokens"), ("prompt_tokens", "completion_tokens")):
152
+ if isinstance(usage, Mapping):
153
+ if a in usage:
154
+ return int(usage[a]), int(usage.get(b, 0))
155
+ elif hasattr(usage, a):
156
+ return int(getattr(usage, a)), int(getattr(usage, b, 0))
157
+ return 0, 0
158
+
159
+
160
+ def _estimate(text: str) -> int:
161
+ return max(1, len(text) // 4) if text else 0
162
+
163
+
164
+ @dataclass(frozen=True)
165
+ class ToolCall:
166
+ """A model-requested tool call; ``arguments`` is the raw string as sent."""
167
+
168
+ name: str
169
+ arguments: str
170
+ id: str = "call_1"
171
+
172
+ @property
173
+ def input(self) -> dict[str, Any]:
174
+ """Parsed arguments, or ``{}`` when they are not a JSON object."""
175
+ try:
176
+ parsed = json.loads(self.arguments)
177
+ except ValueError:
178
+ return {}
179
+ return parsed if isinstance(parsed, dict) else {}
180
+
181
+
182
+ @dataclass
183
+ class FakeResponse:
184
+ """A duck-typed model response readable the Anthropic way and the OpenAI way.
185
+
186
+ ``.content`` is a list of blocks (``text`` / ``tool_use``) with ``.usage.input_tokens``;
187
+ ``.choices[0].message.content`` and ``.choices[0].finish_reason`` follow the chat
188
+ completions shape. ``.text`` is a shortcut for the reply text.
189
+ """
190
+
191
+ text: str = ""
192
+ usage: Any = None
193
+ model: str = "fake-model"
194
+ stop_reason: str = "end_turn"
195
+ finish_reason: str = "stop"
196
+ tool_calls: tuple[ToolCall, ...] = ()
197
+ refusal: str | None = None
198
+ id: str = "fake-response"
199
+
200
+ @property
201
+ def content(self) -> list[Any]:
202
+ blocks: list[Any] = []
203
+ if self.text:
204
+ blocks.append(SimpleNamespace(type="text", text=self.text))
205
+ for call in self.tool_calls:
206
+ blocks.append(
207
+ SimpleNamespace(type="tool_use", id=call.id, name=call.name, input=call.input)
208
+ )
209
+ return blocks
210
+
211
+ @property
212
+ def choices(self) -> list[Any]:
213
+ calls = [
214
+ SimpleNamespace(
215
+ id=c.id,
216
+ type="function",
217
+ function=SimpleNamespace(name=c.name, arguments=c.arguments),
218
+ )
219
+ for c in self.tool_calls
220
+ ]
221
+ message = SimpleNamespace(
222
+ role="assistant",
223
+ content=self.text or None,
224
+ tool_calls=calls or None,
225
+ refusal=self.refusal,
226
+ )
227
+ return [SimpleNamespace(index=0, message=message, finish_reason=self.finish_reason)]
228
+
229
+ def __str__(self) -> str:
230
+ return self.text
231
+
232
+
233
+ def _response(
234
+ text: str,
235
+ style: str,
236
+ *,
237
+ model: str = "fake-model",
238
+ usage: tuple[int, int] | None = None,
239
+ **extra: Any,
240
+ ) -> FakeResponse:
241
+ inp, out = usage if usage is not None else (0, _estimate(text))
242
+ return FakeResponse(text=text, usage=make_usage(style, inp, out), model=model, **extra)
243
+
244
+
245
+ # ------------------------------------------------------------------------------ streams
246
+
247
+
248
+ @dataclass
249
+ class FakeChunk:
250
+ """One streamed piece: ``.text``, ``.delta.text``, ``.choices[0].delta.content``."""
251
+
252
+ text: str
253
+ index: int = 0
254
+ usage: Any = None
255
+ finish_reason: str | None = None
256
+
257
+ @property
258
+ def delta(self) -> Any:
259
+ return SimpleNamespace(text=self.text, content=self.text)
260
+
261
+ @property
262
+ def choices(self) -> list[Any]:
263
+ return [SimpleNamespace(index=0, delta=self.delta, finish_reason=self.finish_reason)]
264
+
265
+ def __str__(self) -> str:
266
+ return self.text
267
+
268
+
269
+ class FakeStream:
270
+ """A re-iterable scripted stream usable with ``for`` and ``async for``.
271
+
272
+ Args:
273
+ chunks: Strings or `FakeChunk` objects.
274
+ first_token_delay: Extra seconds before the first chunk.
275
+ chunk_delay: Seconds before each chunk: one number, or a sequence with one entry
276
+ per chunk (a large entry is a stalled stream).
277
+ error: Raise this (instance, class or factory) once ``error_after`` chunks have
278
+ been delivered, after that gap's delay.
279
+ error_after: Number of chunks delivered before ``error`` (default: all of them).
280
+ usage: Usage attached to the last chunk.
281
+
282
+ Delays use the package sleep, so ``fake_clock`` makes them instant.
283
+
284
+ Example:
285
+ ```python
286
+ from python_wrap.llm_testing import FakeStream
287
+ from python_wrap.testing import fake_clock
288
+
289
+ stream = FakeStream(["a", "b"], chunk_delay=[0.5, 20.0])
290
+ with fake_clock() as clock:
291
+ assert [c.text for c in stream] == ["a", "b"]
292
+ assert clock.total_slept == 20.5
293
+ ```
294
+ """
295
+
296
+ def __init__(
297
+ self,
298
+ chunks: Sequence[str | FakeChunk],
299
+ *,
300
+ first_token_delay: float = 0.0,
301
+ chunk_delay: float | Sequence[float] = 0.0,
302
+ error: BaseException | type[BaseException] | Callable[[], BaseException] | None = None,
303
+ error_after: int | None = None,
304
+ usage: Any = None,
305
+ ) -> None:
306
+ self._chunks = [
307
+ c if isinstance(c, FakeChunk) else FakeChunk(c, index=i) for i, c in enumerate(chunks)
308
+ ]
309
+ if first_token_delay < 0:
310
+ raise ValueError("first_token_delay must be >= 0")
311
+ if not isinstance(chunk_delay, (int, float)):
312
+ chunk_delay = list(chunk_delay)
313
+ if len(chunk_delay) != len(self._chunks):
314
+ raise ValueError("chunk_delay sequence needs one entry per chunk")
315
+ self._first = float(first_token_delay)
316
+ self._delay = chunk_delay
317
+ self._error = error
318
+ self._error_after = len(self._chunks) if error_after is None else error_after
319
+ if self._error_after < 0 or self._error_after > len(self._chunks):
320
+ raise ValueError("error_after must be between 0 and the number of chunks")
321
+ self.usage = usage
322
+ if usage is not None and self._chunks:
323
+ self._chunks[-1].usage = usage
324
+
325
+ @property
326
+ def text(self) -> str:
327
+ """The full text of all chunks."""
328
+ return "".join(c.text for c in self._chunks)
329
+
330
+ def _gap(self, i: int) -> float:
331
+ d = self._delay
332
+ base = float(d) if isinstance(d, (int, float)) else float(d[i]) if i < len(d) else 0.0
333
+ return base + (self._first if i == 0 else 0.0)
334
+
335
+ def _raise(self) -> None:
336
+ err = self._error
337
+ if err is None:
338
+ return
339
+ if isinstance(err, BaseException):
340
+ raise err
341
+ made = err()
342
+ raise made
343
+
344
+ def __iter__(self) -> Iterator[FakeChunk]:
345
+ for i, chunk in enumerate(self._chunks):
346
+ gap = self._gap(i)
347
+ if gap:
348
+ _core.sleep(gap)
349
+ if self._error is not None and i == self._error_after:
350
+ self._raise()
351
+ yield chunk
352
+ if self._error is not None and self._error_after == len(self._chunks):
353
+ self._raise()
354
+
355
+ async def __aiter__(self) -> AsyncIterator[FakeChunk]:
356
+ for i, chunk in enumerate(self._chunks):
357
+ gap = self._gap(i)
358
+ if gap:
359
+ await _core.async_sleep(gap)
360
+ if self._error is not None and i == self._error_after:
361
+ self._raise()
362
+ yield chunk
363
+ if self._error is not None and self._error_after == len(self._chunks):
364
+ self._raise()
365
+
366
+ def __enter__(self) -> FakeStream:
367
+ return self
368
+
369
+ def __exit__(
370
+ self, typ: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None
371
+ ) -> None:
372
+ return None
373
+
374
+ async def __aenter__(self) -> FakeStream:
375
+ return self
376
+
377
+ async def __aexit__(
378
+ self, typ: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None
379
+ ) -> None:
380
+ return None
381
+
382
+
383
+ _WORDS = re.compile(r"\S+\s*")
384
+
385
+
386
+ def _split(text: str, size: int) -> list[str]:
387
+ words = _WORDS.findall(text) or ([text] if text else [])
388
+ return ["".join(words[i : i + size]) for i in range(0, len(words), size)]
389
+
390
+
391
+ # ------------------------------------------------------------------------------ provider
392
+
393
+
394
+ @dataclass
395
+ class FakeCall:
396
+ """One recorded call. ``served`` is false when an injected fault answered instead."""
397
+
398
+ args: tuple[Any, ...]
399
+ kwargs: dict[str, Any]
400
+ stream: bool = False
401
+ started: float = 0.0
402
+ served: bool = False
403
+ usage: tuple[int, int] = (0, 0)
404
+
405
+ @property
406
+ def model(self) -> Any:
407
+ return self.kwargs.get("model")
408
+
409
+ @property
410
+ def messages(self) -> Any:
411
+ return self.kwargs.get("messages")
412
+
413
+ @property
414
+ def prompt(self) -> str:
415
+ """Text of the last message (or the first positional string), best effort."""
416
+ messages = self.kwargs.get("messages")
417
+ if isinstance(messages, Sequence) and not isinstance(messages, str) and messages:
418
+ last = messages[-1]
419
+ content = last.get("content") if isinstance(last, Mapping) else last
420
+ return content if isinstance(content, str) else str(content)
421
+ for value in (*self.args, self.kwargs.get("prompt")):
422
+ if isinstance(value, str):
423
+ return value
424
+ return ""
425
+
426
+
427
+ Reply = Any # str | BaseException | exception class | response object | callable(FakeCall)
428
+ UsageSpec = tuple[int, int] | Callable[[FakeCall, str], tuple[int, int]] | None
429
+
430
+
431
+ class _Endpoint:
432
+ def __init__(self, fn: Callable[..., Any]) -> None:
433
+ self.create = fn
434
+
435
+
436
+ class _Surface:
437
+ """``messages.create`` / ``chat.completions.create`` look-alike namespaces."""
438
+
439
+ def __init__(self, provider: FakeProvider, is_async: bool) -> None:
440
+ async def acreate(*args: Any, **kwargs: Any) -> Any:
441
+ if kwargs.get("stream"):
442
+ return await provider.astream(*args, **kwargs)
443
+ return await provider.acomplete(*args, **kwargs)
444
+
445
+ def create(*args: Any, **kwargs: Any) -> Any:
446
+ if kwargs.get("stream"):
447
+ return provider.stream(*args, **kwargs)
448
+ return provider.complete(*args, **kwargs)
449
+
450
+ fn: Callable[..., Any] = acreate if is_async else create
451
+
452
+ self.messages = _Endpoint(fn)
453
+ self.chat = SimpleNamespace(completions=_Endpoint(fn))
454
+
455
+
456
+ class FakeProvider:
457
+ """A deterministic, scripted model API for tests.
458
+
459
+ Replies are served in order, one per call that reaches the provider. A reply can be a
460
+ string (becomes a `FakeResponse`), an exception instance or class (raised), a
461
+ `FakeResponse`/`FakeStream`/any other object or dict (returned as is) or a callable
462
+ taking the `FakeCall` and returning one of those.
463
+
464
+ Calls are recorded in `calls` even when a chaos rule answers instead of the provider.
465
+ Fault rules for the provider's `point` (default ``"llm.<name>"``) apply to every entry
466
+ point.
467
+
468
+ Args:
469
+ responses: The script.
470
+ usage: ``(input_tokens, output_tokens)`` for every reply, a callable
471
+ ``(call, text) -> (in, out)``, or ``None`` to estimate from text length.
472
+ style: ``"anthropic"`` or ``"openai"`` usage objects.
473
+ model: Model name reported on responses.
474
+ name: Used to build the default point name.
475
+ point: Fault point name.
476
+ injector: The chaos injector to consult; defaults to the global `chaos`.
477
+ cycle: Loop the script instead of raising `FakeProviderExhausted`.
478
+ default: Reply used once the script runs out (takes precedence over ``cycle``).
479
+ delay: Seconds each non-streaming call takes.
480
+ first_token_delay: Seconds before a stream's first chunk.
481
+ chunk_delay: Seconds before each stream chunk (for per-chunk gaps, make a
482
+ `FakeStream` reply).
483
+ chunk_size: Words per streamed chunk.
484
+
485
+ Example:
486
+ ```python
487
+ from python_wrap.llm_testing import fake_llm
488
+
489
+ llm = fake_llm(["hello"], usage=(10, 5))
490
+ assert llm.complete(messages=[{"role": "user", "content": "hi"}]).text == "hello"
491
+ llm.assert_called_with(messages=[{"role": "user", "content": "hi"}])
492
+ llm.assert_tokens(input_tokens=10, output_tokens=5)
493
+ ```
494
+ """
495
+
496
+ def __init__(
497
+ self,
498
+ responses: Sequence[Reply] = (),
499
+ *,
500
+ usage: UsageSpec = None,
501
+ style: str = "anthropic",
502
+ model: str = "fake-model",
503
+ name: str = "fake",
504
+ point: str | None = None,
505
+ injector: FaultInjector | None = None,
506
+ cycle: bool = False,
507
+ default: Reply = None,
508
+ delay: float = 0.0,
509
+ first_token_delay: float = 0.0,
510
+ chunk_delay: float = 0.0,
511
+ chunk_size: int = 1,
512
+ ) -> None:
513
+ make_usage(style, 0, 0) # validates the style
514
+ if chunk_size < 1:
515
+ raise ValueError("chunk_size must be >= 1")
516
+ self._script = list(responses)
517
+ self._usage = usage
518
+ self.style = style
519
+ self.model = model
520
+ self.name = name
521
+ self.point = point or f"llm.{name}"
522
+ self._cycle = cycle
523
+ self._default = default
524
+ self._delay = delay
525
+ self._first = first_token_delay
526
+ self._chunk_delay = chunk_delay
527
+ self._chunk_size = chunk_size
528
+ self._lock = threading.Lock()
529
+ self._next = 0
530
+ self.calls: list[FakeCall] = []
531
+ self._run = fault_point(self.point, injector=injector)(self._serve)
532
+ self._arun = fault_point(self.point, injector=injector)(self._aserve)
533
+ self.messages = _Surface(self, False).messages
534
+ self.chat = _Surface(self, False).chat
535
+ self.aio = _Surface(self, True)
536
+
537
+ # -- entry points --------------------------------------------------------------
538
+
539
+ def complete(self, *args: Any, **kwargs: Any) -> Any:
540
+ """Serve the next reply (sync)."""
541
+ return self._run(self._record(args, kwargs, False))
542
+
543
+ async def acomplete(self, *args: Any, **kwargs: Any) -> Any:
544
+ """Serve the next reply (async)."""
545
+ return await self._arun(self._record(args, kwargs, False))
546
+
547
+ def stream(self, *args: Any, **kwargs: Any) -> Any:
548
+ """Serve the next reply as a `FakeStream` (sync iteration or async)."""
549
+ kwargs.pop("stream", None)
550
+ return self._as_stream(self._run(self._record(args, kwargs, True)))
551
+
552
+ async def astream(self, *args: Any, **kwargs: Any) -> Any:
553
+ """Like `stream`, awaitable; iterate the result with ``async for``."""
554
+ kwargs.pop("stream", None)
555
+ return self._as_stream(await self._arun(self._record(args, kwargs, True)))
556
+
557
+ __call__ = complete
558
+
559
+ # -- internals -----------------------------------------------------------------
560
+
561
+ def _record(self, args: tuple[Any, ...], kwargs: dict[str, Any], stream: bool) -> FakeCall:
562
+ call = FakeCall(args, dict(kwargs), stream, _core.monotonic())
563
+ with self._lock:
564
+ self.calls.append(call)
565
+ return call
566
+
567
+ def _pick(self) -> Reply:
568
+ with self._lock:
569
+ if self._next < len(self._script):
570
+ reply = self._script[self._next]
571
+ self._next += 1
572
+ return reply
573
+ if self._default is not None:
574
+ return self._default
575
+ if self._cycle and self._script:
576
+ reply = self._script[self._next % len(self._script)]
577
+ self._next += 1
578
+ return reply
579
+ raise FakeProviderExhausted(
580
+ f"{self.point}: script of {len(self._script)} replies is used up"
581
+ )
582
+
583
+ def _build(self, call: FakeCall) -> Any:
584
+ call.served = True
585
+ reply = self._pick()
586
+ if callable(reply) and not isinstance(reply, type):
587
+ reply = reply(call)
588
+ if isinstance(reply, BaseException):
589
+ raise reply
590
+ if isinstance(reply, type) and issubclass(reply, BaseException):
591
+ raise reply()
592
+ if isinstance(reply, str):
593
+ usage = self._usage
594
+ if callable(usage):
595
+ call.usage = usage(call, reply)
596
+ elif usage is not None:
597
+ call.usage = usage
598
+ else:
599
+ call.usage = (_estimate(call.prompt), _estimate(reply))
600
+ return _response(reply, self.style, model=self.model, usage=call.usage)
601
+ call.usage = _tokens(
602
+ reply.get("usage") if isinstance(reply, Mapping) else getattr(reply, "usage", None)
603
+ )
604
+ return reply
605
+
606
+ def _serve(self, call: FakeCall) -> Any:
607
+ if self._delay and not call.stream:
608
+ _core.sleep(self._delay)
609
+ return self._build(call)
610
+
611
+ async def _aserve(self, call: FakeCall) -> Any:
612
+ if self._delay and not call.stream:
613
+ await _core.async_sleep(self._delay)
614
+ return self._build(call)
615
+
616
+ def _as_stream(self, reply: Any) -> Any:
617
+ if isinstance(reply, str):
618
+ reply = FakeResponse(text=reply)
619
+ if isinstance(reply, FakeResponse):
620
+ chunks = _split(reply.text, self._chunk_size)
621
+ return FakeStream(
622
+ chunks,
623
+ first_token_delay=self._first,
624
+ chunk_delay=self._chunk_delay,
625
+ usage=reply.usage,
626
+ )
627
+ return reply
628
+
629
+ # -- assertions ----------------------------------------------------------------
630
+
631
+ @property
632
+ def call_count(self) -> int:
633
+ """Calls made, including ones answered by an injected fault."""
634
+ return len(self.calls)
635
+
636
+ @property
637
+ def served_count(self) -> int:
638
+ """Calls that reached the provider (not intercepted by chaos)."""
639
+ return sum(1 for c in self.calls if c.served)
640
+
641
+ @property
642
+ def input_tokens(self) -> int:
643
+ """Total input tokens across served calls."""
644
+ return sum(c.usage[0] for c in self.calls)
645
+
646
+ @property
647
+ def output_tokens(self) -> int:
648
+ """Total output tokens across served calls."""
649
+ return sum(c.usage[1] for c in self.calls)
650
+
651
+ @property
652
+ def total_tokens(self) -> int:
653
+ """Input plus output tokens."""
654
+ return self.input_tokens + self.output_tokens
655
+
656
+ def reset(self) -> None:
657
+ """Forget recorded calls and rewind the script."""
658
+ with self._lock:
659
+ self.calls.clear()
660
+ self._next = 0
661
+
662
+ def assert_call_count(self, n: int) -> None:
663
+ """Assert exactly ``n`` calls were made."""
664
+ if len(self.calls) != n:
665
+ raise AssertionError(f"expected {n} call(s) to {self.point}, got {len(self.calls)}")
666
+
667
+ def assert_not_called(self) -> None:
668
+ """Assert no call was made."""
669
+ self.assert_call_count(0)
670
+
671
+ def assert_called_with(self, *args: Any, **kwargs: Any) -> None:
672
+ """Assert the most recent call included these arguments.
673
+
674
+ Positional ``args`` must equal the start of the call's positional arguments, and
675
+ every given keyword must be present with an equal value (other keywords such as
676
+ ``max_tokens`` are ignored).
677
+
678
+ Raises:
679
+ AssertionError: If never called or the last call differs.
680
+ """
681
+ if not self.calls:
682
+ raise AssertionError(f"expected a call to {self.point}, but it was never called")
683
+ last = self.calls[-1]
684
+ ok = last.args[: len(args)] == args and all(
685
+ k in last.kwargs and last.kwargs[k] == v for k, v in kwargs.items()
686
+ )
687
+ if not ok:
688
+ raise AssertionError(
689
+ f"expected last call with args={args!r} kwargs={kwargs!r}, "
690
+ f"got args={last.args!r} kwargs={last.kwargs!r}"
691
+ )
692
+
693
+ def assert_tokens(
694
+ self, *, input_tokens: int | None = None, output_tokens: int | None = None
695
+ ) -> None:
696
+ """Assert the token totals (check only the ones you pass)."""
697
+ if input_tokens is not None and self.input_tokens != input_tokens:
698
+ raise AssertionError(f"expected {input_tokens} input tokens, got {self.input_tokens}")
699
+ if output_tokens is not None and self.output_tokens != output_tokens:
700
+ raise AssertionError(
701
+ f"expected {output_tokens} output tokens, got {self.output_tokens}"
702
+ )
703
+
704
+
705
+ def fake_llm(
706
+ responses: Sequence[Reply] = (), *, usage: UsageSpec = None, **options: Any
707
+ ) -> FakeProvider:
708
+ """Build a `FakeProvider`; shorthand for ``FakeProvider(responses, usage=usage, ...)``."""
709
+ return FakeProvider(responses, usage=usage, **options)
710
+
711
+
712
+ # ------------------------------------------------------------------------------- faults
713
+
714
+ _DEFAULT_JSON = '{"answer": "forty-two", "sources": ["alpha", "beta", "gamma"]}'
715
+
716
+
717
+ def _status_rule(
718
+ cls: type[APIStatusError], status: int | None, retry_after: float | None, message: str
719
+ ) -> dict[str, Any]:
720
+ if retry_after is not None and (isinstance(retry_after, bool) or retry_after < 0):
721
+ raise ValueError("retry_after must be a number >= 0")
722
+ return {
723
+ "exception": lambda: cls(message, status_code=status, retry_after=retry_after),
724
+ }
725
+
726
+
727
+ def _b_rate_limit(
728
+ *, retry_after: float | None = 1.0, message: str = "Rate limit exceeded"
729
+ ) -> dict[str, Any]:
730
+ return _status_rule(RateLimitError, 429, retry_after, message)
731
+
732
+
733
+ def _b_overloaded(*, message: str = "Overloaded") -> dict[str, Any]:
734
+ return _status_rule(OverloadedError, 529, None, message)
735
+
736
+
737
+ def _b_server_error(*, status: int = 500, message: str = "Internal server error") -> dict[str, Any]:
738
+ if not 500 <= status <= 599:
739
+ raise ValueError("status must be a 5xx code")
740
+ return _status_rule(InternalServerError, status, None, message)
741
+
742
+
743
+ def _b_timeout(*, after: float | None = None, message: str = "Request timed out") -> dict[str, Any]:
744
+ rule: dict[str, Any] = {"exception": lambda: APITimeoutError(message)}
745
+ if after is not None:
746
+ rule["latency"] = after
747
+ return rule
748
+
749
+
750
+ def _b_malformed_json(
751
+ *, text: str = _DEFAULT_JSON, keep: float = 0.6, style: str = "anthropic"
752
+ ) -> dict[str, Any]:
753
+ if not 0 <= keep < 1:
754
+ raise ValueError("keep must be in [0, 1)")
755
+ cut = text[: int(len(text) * keep)]
756
+ return {
757
+ "result": _response(cut, style, stop_reason="max_tokens", finish_reason="length"),
758
+ }
759
+
760
+
761
+ def _b_slow_first_token(*, delay: float = 5.0) -> dict[str, Any]:
762
+ if delay < 0:
763
+ raise ValueError("delay must be >= 0")
764
+ return {"latency": float(delay)}
765
+
766
+
767
+ def _b_stalled_stream(
768
+ *,
769
+ after_chunks: int = 1,
770
+ stall: float = 30.0,
771
+ chunks: Sequence[str] = ("The", " answer", " is", " forty-two."),
772
+ fail: bool = False,
773
+ message: str = "Stream stalled",
774
+ ) -> dict[str, Any]:
775
+ items = list(chunks)
776
+ if not 0 <= after_chunks < len(items) or stall < 0:
777
+ raise ValueError("after_chunks must index a chunk and stall must be >= 0")
778
+ delays = [0.0] * len(items)
779
+ delays[after_chunks] = float(stall)
780
+ stream = FakeStream(
781
+ items,
782
+ chunk_delay=delays,
783
+ error=(lambda: APITimeoutError(message)) if fail else None,
784
+ error_after=after_chunks if fail else None,
785
+ )
786
+ return {"result": stream}
787
+
788
+
789
+ def _b_invalid_tool_call(
790
+ *,
791
+ tool: str = "get_weather",
792
+ arguments: str | Mapping[str, Any] = '{"city": ',
793
+ style: str = "anthropic",
794
+ ) -> dict[str, Any]:
795
+ raw = arguments if isinstance(arguments, str) else json.dumps(dict(arguments))
796
+ response = _response(
797
+ "",
798
+ style,
799
+ stop_reason="tool_use",
800
+ finish_reason="tool_calls",
801
+ tool_calls=(ToolCall(tool, raw),),
802
+ )
803
+ return {"result": response}
804
+
805
+
806
+ def _b_refusal(
807
+ *, message: str = "I can't help with that request.", style: str = "anthropic"
808
+ ) -> dict[str, Any]:
809
+ response = _response(
810
+ message, style, stop_reason="refusal", finish_reason="content_filter", refusal=message
811
+ )
812
+ return {"result": response}
813
+
814
+
815
+ _BUILDERS: dict[str, Callable[..., dict[str, Any]]] = {
816
+ "rate_limit": _b_rate_limit,
817
+ "overloaded": _b_overloaded,
818
+ "server_error": _b_server_error,
819
+ "timeout": _b_timeout,
820
+ "malformed_json": _b_malformed_json,
821
+ "slow_first_token": _b_slow_first_token,
822
+ "stalled_stream": _b_stalled_stream,
823
+ "invalid_tool_call": _b_invalid_tool_call,
824
+ "refusal": _b_refusal,
825
+ }
826
+
827
+
828
+ def build_rule(kind: str, options: Mapping[str, Any]) -> dict[str, Any]:
829
+ """Translate an LLM fault ``kind`` and its options into `FaultInjector.inject` kwargs.
830
+
831
+ Raises:
832
+ ValueError: For an unknown kind or option, or an invalid value.
833
+ """
834
+ builder = _BUILDERS.get(kind)
835
+ if builder is None:
836
+ raise ValueError(f"unknown llm fault {kind!r} (use one of {', '.join(sorted(_BUILDERS))})")
837
+ try:
838
+ return builder(**options)
839
+ except TypeError as exc:
840
+ raise ValueError(f"llm fault {kind!r}: {exc}") from exc
841
+
842
+
843
+ class LLMFaults:
844
+ """LLM-shaped fault rules on a `FaultInjector`, reached as ``chaos.llm``.
845
+
846
+ Every method adds one rule for the point name or glob ``name`` and returns the
847
+ `Fault` handle (a context manager). ``rate``, ``times`` and seeding behave as for
848
+ `FaultInjector.inject`. Provider replies that carry data (truncated JSON, bad tool
849
+ call, refusal) replace the call's result, so they exercise your parsing, not your
850
+ transport.
851
+
852
+ Example:
853
+ ```python
854
+ from python_wrap import retry
855
+ from python_wrap.chaos import chaos
856
+ from python_wrap.llm_testing import RateLimitError, fake_llm
857
+ from python_wrap.testing import fake_clock
858
+
859
+ llm = fake_llm(["done"])
860
+
861
+ @retry(max_attempts=3, delay=1.0, on=RateLimitError)
862
+ def ask() -> str:
863
+ return llm.complete(prompt="hi").text
864
+
865
+ with fake_clock(), chaos.llm.rate_limit("llm.*", times=2, retry_after=1):
866
+ assert ask() == "done"
867
+ assert llm.call_count == 3
868
+ ```
869
+ """
870
+
871
+ def __init__(self, injector: FaultInjector) -> None:
872
+ self._injector = injector
873
+
874
+ def _add(self, name: str, rate: float, times: int | None, kind: str, **options: Any) -> Fault:
875
+ return self._injector.inject(name, rate=rate, times=times, **build_rule(kind, options))
876
+
877
+ def rate_limit(
878
+ self,
879
+ name: str,
880
+ *,
881
+ retry_after: float | None = 1.0,
882
+ rate: float = 1.0,
883
+ times: int | None = None,
884
+ message: str = "Rate limit exceeded",
885
+ ) -> Fault:
886
+ """Raise `RateLimitError` (429) carrying a ``Retry-After`` of ``retry_after`` seconds."""
887
+ return self._add(name, rate, times, "rate_limit", retry_after=retry_after, message=message)
888
+
889
+ def overloaded(
890
+ self, name: str, *, rate: float = 1.0, times: int | None = None, message: str = "Overloaded"
891
+ ) -> Fault:
892
+ """Raise `OverloadedError` (529)."""
893
+ return self._add(name, rate, times, "overloaded", message=message)
894
+
895
+ def server_error(
896
+ self,
897
+ name: str,
898
+ *,
899
+ status: int = 500,
900
+ rate: float = 1.0,
901
+ times: int | None = None,
902
+ message: str = "Internal server error",
903
+ ) -> Fault:
904
+ """Raise `InternalServerError` with a 5xx ``status``."""
905
+ return self._add(name, rate, times, "server_error", status=status, message=message)
906
+
907
+ def timeout(
908
+ self,
909
+ name: str,
910
+ *,
911
+ after: float | None = None,
912
+ rate: float = 1.0,
913
+ times: int | None = None,
914
+ message: str = "Request timed out",
915
+ ) -> Fault:
916
+ """Raise `APITimeoutError`, optionally after waiting ``after`` seconds."""
917
+ return self._add(name, rate, times, "timeout", after=after, message=message)
918
+
919
+ def malformed_json(
920
+ self,
921
+ name: str,
922
+ *,
923
+ text: str = _DEFAULT_JSON,
924
+ keep: float = 0.6,
925
+ style: str = "anthropic",
926
+ rate: float = 1.0,
927
+ times: int | None = None,
928
+ ) -> Fault:
929
+ """Return a response whose text is ``text`` cut to the first ``keep`` fraction."""
930
+ return self._add(name, rate, times, "malformed_json", text=text, keep=keep, style=style)
931
+
932
+ def slow_first_token(
933
+ self, name: str, *, delay: float = 5.0, rate: float = 1.0, times: int | None = None
934
+ ) -> Fault:
935
+ """Wait ``delay`` seconds before the call (a slow time-to-first-token)."""
936
+ return self._add(name, rate, times, "slow_first_token", delay=delay)
937
+
938
+ def stalled_stream(
939
+ self,
940
+ name: str,
941
+ *,
942
+ after_chunks: int = 1,
943
+ stall: float = 30.0,
944
+ chunks: Sequence[str] = ("The", " answer", " is", " forty-two."),
945
+ fail: bool = False,
946
+ rate: float = 1.0,
947
+ times: int | None = None,
948
+ ) -> Fault:
949
+ """Answer with a stream that pauses ``stall`` seconds after ``after_chunks`` chunks.
950
+
951
+ With ``fail=True`` the stream raises `APITimeoutError` after the pause instead of
952
+ continuing.
953
+ """
954
+ return self._add(
955
+ name,
956
+ rate,
957
+ times,
958
+ "stalled_stream",
959
+ after_chunks=after_chunks,
960
+ stall=stall,
961
+ chunks=chunks,
962
+ fail=fail,
963
+ )
964
+
965
+ def invalid_tool_call(
966
+ self,
967
+ name: str,
968
+ *,
969
+ tool: str = "get_weather",
970
+ arguments: str | Mapping[str, Any] = '{"city": ',
971
+ style: str = "anthropic",
972
+ rate: float = 1.0,
973
+ times: int | None = None,
974
+ ) -> Fault:
975
+ """Return a response asking for ``tool`` with broken (or wrongly typed) arguments."""
976
+ return self._add(
977
+ name, rate, times, "invalid_tool_call", tool=tool, arguments=arguments, style=style
978
+ )
979
+
980
+ def refusal(
981
+ self,
982
+ name: str,
983
+ *,
984
+ message: str = "I can't help with that request.",
985
+ style: str = "anthropic",
986
+ rate: float = 1.0,
987
+ times: int | None = None,
988
+ ) -> Fault:
989
+ """Return a content-policy refusal (``stop_reason="refusal"``, ``content_filter``)."""
990
+ return self._add(name, rate, times, "refusal", message=message, style=style)