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,383 @@
1
+ """Validate structured LLM output and repair it with a cheap, capped re-ask.
2
+
3
+ `validated` wraps a function that calls a model. The reply text is handed to your
4
+ ``parse`` callable (``Model.model_validate_json``, a JSON-schema checker, ``json.loads``
5
+ plus your own checks: anything that raises on bad output). When it raises, the call is
6
+ repeated with only the error text added to the conversation (``repair="error_only"``), up
7
+ to ``max_repairs`` times and never past an optional token or `Budget` cap. When repairs
8
+ run out, `ValidationRepairExhausted` carries every attempt and what they cost.
9
+
10
+ Nothing here imports pydantic or a provider SDK: ``parse`` is any callable, and a class
11
+ with ``model_validate_json`` (pydantic v2) is accepted directly.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import dataclasses
17
+ import functools
18
+ import re
19
+ from collections.abc import Awaitable, Callable, Mapping
20
+ from typing import Any, Literal, ParamSpec, TypeVar, cast
21
+
22
+ from python_wrap import _core
23
+ from python_wrap.errors import PythonWrapError
24
+ from python_wrap.llm import Usage, _usage_of
25
+
26
+ __all__ = ["Attempt", "ValidationRepairExhausted", "validated"]
27
+
28
+ P = ParamSpec("P")
29
+ T = TypeVar("T")
30
+
31
+ RepairMode = Literal["error_only", "full"]
32
+ _REPAIRS = ("error_only", "full")
33
+ _FENCE = re.compile(r"^\s*```[a-zA-Z0-9_+-]*\s*\n?(.*?)\n?\s*```\s*$", re.DOTALL)
34
+
35
+
36
+ @dataclasses.dataclass(frozen=True)
37
+ class Attempt:
38
+ """One model call and how its output validated.
39
+
40
+ Attributes:
41
+ number: 1 for the first call, 2 for the first repair, and so on.
42
+ output: The text that was validated (empty when none could be read).
43
+ error: The validation error text, or None for the accepted attempt.
44
+ usage: Tokens the call used, or None when the reply carried no usage.
45
+ """
46
+
47
+ number: int
48
+ output: str
49
+ error: str | None
50
+ usage: Usage | None
51
+
52
+
53
+ class ValidationRepairExhausted(PythonWrapError):
54
+ """The model kept returning output that fails validation.
55
+
56
+ Attributes:
57
+ attempts: Every `Attempt`, in order.
58
+ tokens: Total tokens used by the attempts that reported usage.
59
+ reason: ``"max_repairs"``, ``"max_tokens"`` or ``"budget"``: what stopped the loop.
60
+ last_error: The final validation error text.
61
+ """
62
+
63
+ def __init__(self, function: str, attempts: list[Attempt], reason: str) -> None:
64
+ self.attempts = list(attempts)
65
+ self.reason = reason
66
+ self.tokens = sum(a.usage.total_tokens for a in attempts if a.usage is not None)
67
+ self.last_error = attempts[-1].error or "" if attempts else ""
68
+ super().__init__(
69
+ f"{function}: output still invalid after {len(attempts)} attempt(s) "
70
+ f"({reason}, {self.tokens} tokens): {self.last_error[:200]}"
71
+ )
72
+
73
+
74
+ def _text_of(response: Any) -> str:
75
+ """Pull the reply text out of a string, dict or SDK-style response."""
76
+ if isinstance(response, str):
77
+ return response
78
+ if isinstance(response, (bytes, bytearray)):
79
+ return bytes(response).decode("utf-8", "replace")
80
+ pieces: list[str] = []
81
+
82
+ def field(obj: Any, name: str) -> Any:
83
+ if isinstance(obj, Mapping):
84
+ return obj.get(name)
85
+ return getattr(obj, name, None)
86
+
87
+ direct = field(response, "text")
88
+ if isinstance(direct, str):
89
+ return direct
90
+ direct = field(response, "output_text")
91
+ if isinstance(direct, str):
92
+ return direct
93
+ content = field(response, "content")
94
+ if isinstance(content, str):
95
+ return content
96
+ if isinstance(content, (list, tuple)):
97
+ for block in content:
98
+ text = block if isinstance(block, str) else field(block, "text")
99
+ if isinstance(text, str):
100
+ pieces.append(text)
101
+ if pieces:
102
+ return "".join(pieces)
103
+ choices = field(response, "choices")
104
+ if isinstance(choices, (list, tuple)) and choices:
105
+ message = field(choices[0], "message")
106
+ text = field(message, "content") if message is not None else field(choices[0], "text")
107
+ if isinstance(text, str):
108
+ return text
109
+ raise TypeError(
110
+ f"cannot find text in a {type(response).__name__}; pass text= to validated() to read it"
111
+ )
112
+
113
+
114
+ def _unfence(text: str) -> str:
115
+ found = _FENCE.match(text)
116
+ return found.group(1) if found else text
117
+
118
+
119
+ def _resolve_parse(parse: Any) -> Callable[[str], Any]:
120
+ validate = getattr(parse, "model_validate_json", None)
121
+ if callable(validate):
122
+ return cast("Callable[[str], Any]", validate)
123
+ if callable(parse):
124
+ return cast("Callable[[str], Any]", parse)
125
+ raise TypeError(
126
+ f"parse must be a callable or a class with model_validate_json, got {type(parse)!r}"
127
+ )
128
+
129
+
130
+ def _error_text(exc: BaseException, limit: int) -> str:
131
+ text = " ".join(str(exc).split()) or type(exc).__name__
132
+ return text if len(text) <= limit else text[: limit - 1] + "…"
133
+
134
+
135
+ def _repair_message(mode: str, error: str, previous: str) -> str:
136
+ if mode == "full":
137
+ return (
138
+ "Your previous reply failed validation.\n"
139
+ f"Previous reply:\n{previous}\n"
140
+ f"Validation error:\n{error}\n"
141
+ "Reply again with the complete corrected output only."
142
+ )
143
+ return f"That reply failed validation: {error}\nReply with the corrected output only."
144
+
145
+
146
+ def _default_reask(
147
+ args: tuple[Any, ...],
148
+ kwargs: dict[str, Any],
149
+ previous: str,
150
+ error: str,
151
+ mode: str,
152
+ ) -> tuple[tuple[Any, ...], dict[str, Any]]:
153
+ """Extend a chat ``messages=`` list (or a ``prompt=`` string) with the repair turn."""
154
+ message = _repair_message(mode, error, previous)
155
+ messages = kwargs.get("messages")
156
+ if isinstance(messages, (list, tuple)):
157
+ extra: list[Any] = []
158
+ if mode == "error_only":
159
+ extra.append({"role": "assistant", "content": previous})
160
+ extra.append({"role": "user", "content": message})
161
+ return args, {**kwargs, "messages": [*messages, *extra]}
162
+ prompt = kwargs.get("prompt")
163
+ if isinstance(prompt, str):
164
+ return args, {**kwargs, "prompt": f"{prompt}\n\n{previous}\n\n{message}"}
165
+ if args and isinstance(args[0], str) and "prompt" not in kwargs:
166
+ return (f"{args[0]}\n\n{previous}\n\n{message}", *args[1:]), kwargs
167
+ raise TypeError(
168
+ "validated() can only re-ask calls that take messages=[...] or a prompt string; "
169
+ "pass reask=(args, kwargs, previous, error) -> (args, kwargs) for other shapes"
170
+ )
171
+
172
+
173
+ class _Plan:
174
+ def __init__(
175
+ self,
176
+ parse: Any,
177
+ max_repairs: int,
178
+ repair: str,
179
+ text: Callable[[Any], str] | None,
180
+ usage: Callable[[Any], Any] | None,
181
+ reask: Callable[..., tuple[tuple[Any, ...], dict[str, Any]]] | None,
182
+ max_tokens: int | None,
183
+ budget: Any,
184
+ budget_key: Callable[..., Any] | None,
185
+ max_error_chars: int,
186
+ unfence: bool,
187
+ ) -> None:
188
+ if isinstance(max_repairs, bool) or not isinstance(max_repairs, int) or max_repairs < 0:
189
+ raise ValueError(f"max_repairs must be an integer >= 0, got {max_repairs!r}")
190
+ if repair not in _REPAIRS:
191
+ raise ValueError(f"repair must be one of {', '.join(_REPAIRS)}; got {repair!r}")
192
+ if max_tokens is not None and (
193
+ isinstance(max_tokens, bool) or not isinstance(max_tokens, int) or max_tokens < 1
194
+ ):
195
+ raise ValueError(f"max_tokens must be an integer >= 1, got {max_tokens!r}")
196
+ if max_error_chars < 20:
197
+ raise ValueError("max_error_chars must be >= 20")
198
+ self.parse = _resolve_parse(parse)
199
+ self.max_repairs, self.repair = max_repairs, repair
200
+ self.text = text or _text_of
201
+ self.usage, self.reask = usage, reask
202
+ self.max_tokens, self.budget, self.budget_key = max_tokens, budget, budget_key
203
+ self.max_error_chars, self.unfence = max_error_chars, unfence
204
+
205
+ def read(self, response: Any) -> tuple[str, Usage | None]:
206
+ try:
207
+ text = self.text(response)
208
+ except Exception as exc:
209
+ if isinstance(exc, TypeError):
210
+ raise
211
+ text = ""
212
+ return text, _usage_of(response, self.usage)
213
+
214
+ def stop_reason(
215
+ self, attempts: list[Attempt], args: tuple[Any, ...], kw: dict[str, Any]
216
+ ) -> str:
217
+ """Why no further repair may run ('' when one may)."""
218
+ if len(attempts) > self.max_repairs:
219
+ return "max_repairs"
220
+ spent = sum(a.usage.total_tokens for a in attempts if a.usage is not None)
221
+ if self.max_tokens is not None and spent >= self.max_tokens:
222
+ return "max_tokens"
223
+ if self.budget is not None:
224
+ key = self.budget_key(*args, **kw) if self.budget_key is not None else None
225
+ if self.budget.exhausted(key=key) if key is not None else self.budget.exhausted():
226
+ return "budget"
227
+ return ""
228
+
229
+ def check(self, text: str) -> tuple[Any, str | None]:
230
+ try:
231
+ return self.parse(_unfence(text) if self.unfence else text), None
232
+ except Exception as exc:
233
+ return None, _error_text(exc, self.max_error_chars)
234
+
235
+ def next_call(
236
+ self, args: tuple[Any, ...], kwargs: dict[str, Any], text: str, error: str
237
+ ) -> tuple[tuple[Any, ...], dict[str, Any]]:
238
+ if self.reask is not None:
239
+ return self.reask(args, kwargs, text, error)
240
+ return _default_reask(args, kwargs, text, error, self.repair)
241
+
242
+
243
+ def validated(
244
+ parse: Any,
245
+ *,
246
+ max_repairs: int = 2,
247
+ repair: RepairMode = "error_only",
248
+ text: Callable[[Any], str] | None = None,
249
+ usage: Callable[[Any], Any] | None = None,
250
+ reask: Callable[..., tuple[tuple[Any, ...], dict[str, Any]]] | None = None,
251
+ max_tokens: int | None = None,
252
+ budget: Any = None,
253
+ budget_key: Callable[..., Any] | None = None,
254
+ max_error_chars: int = 600,
255
+ unfence: bool = True,
256
+ name: str | None = None,
257
+ ) -> Callable[[Callable[P, Any]], Callable[P, Any]]:
258
+ """Validate a model call's output and repair it with at most ``max_repairs`` re-asks.
259
+
260
+ The wrapped function makes one model call and returns its response (a string, a dict
261
+ or an SDK object). The decorator reads the reply text, runs ``parse`` on it and:
262
+
263
+ - returns the parsed value when ``parse`` succeeds;
264
+ - otherwise calls the function again with a repair turn added, up to
265
+ ``max_repairs`` times, and raises `ValidationRepairExhausted` after that.
266
+
267
+ There are never more than ``1 + max_repairs`` calls, and a repair is skipped (the
268
+ error raised with ``reason="max_tokens"`` / ``"budget"``) once the attempts' tokens
269
+ reach ``max_tokens`` or the ``budget`` is exhausted. Exceptions from the call itself
270
+ (including a `BudgetExceeded` from a decorated function) propagate untouched.
271
+
272
+ Args:
273
+ parse: ``parse(text) -> value``, raising on invalid output (any exception counts).
274
+ A class with ``model_validate_json`` is used through that method.
275
+ max_repairs: Re-asks allowed after the first call; 0 validates without repairing.
276
+ repair: ``"error_only"`` continues the chat with the model's reply and just the
277
+ error text (cheapest); ``"full"`` restates the previous reply and the error in
278
+ one user turn (for prompt-style APIs). Both add the turn to ``messages=``
279
+ (a list) or to ``prompt=`` / the first string argument.
280
+ text: ``text(response) -> str`` when the reply is not a string, ``.text``,
281
+ ``.content`` blocks, ``.choices[0].message.content`` or a dict of those.
282
+ usage: ``usage(response)`` for token counts `read_usage` cannot find.
283
+ reask: ``reask(args, kwargs, previous_text, error) -> (args, kwargs)`` to build the
284
+ repair call yourself (needed for call shapes other than the above).
285
+ max_tokens: Stop repairing once the attempts used this many tokens in total.
286
+ budget: A `python_wrap.llm.Budget` (anything with ``exhausted()``) that must not be
287
+ exhausted for a repair to run. Pair it with the same budget decorating the call
288
+ so each attempt is charged.
289
+ budget_key: ``budget_key(*args, **kwargs)`` for ``per="key"`` budgets.
290
+ max_error_chars: Longest error text sent back to the model.
291
+ unfence: Strip a surrounding markdown code fence before parsing.
292
+ name: Label for events and errors; defaults to the function's name.
293
+
294
+ Returns:
295
+ A decorator for sync or async functions. The wrapped function returns the parsed
296
+ value; it emits ``llm.validation_failed`` per failed attempt.
297
+
298
+ Raises:
299
+ ValidationRepairExhausted: When repairs ran out.
300
+
301
+ Example:
302
+ ```python
303
+ import json
304
+
305
+ from python_wrap.llm_validate import ValidationRepairExhausted, validated
306
+
307
+ replies = iter(['{"city": ', '{"city": "Oslo"}']) # truncated, then fixed
308
+
309
+
310
+ def parse(text: str) -> dict[str, str]:
311
+ data = json.loads(text)
312
+ if "city" not in data:
313
+ raise ValueError("missing 'city'")
314
+ return {"city": data["city"]}
315
+
316
+
317
+ @validated(parse, max_repairs=2)
318
+ def ask(messages: list[dict[str, str]]) -> str:
319
+ return next(replies)
320
+
321
+
322
+ assert ask(messages=[{"role": "user", "content": "Where?"}]) == {"city": "Oslo"}
323
+ ```
324
+ """
325
+ plan = _Plan(
326
+ parse, max_repairs, repair, text, usage, reask, max_tokens, budget, budget_key,
327
+ max_error_chars, unfence,
328
+ ) # fmt: skip
329
+
330
+ def decorate(func: Callable[P, Any]) -> Callable[P, Any]:
331
+ label = name or _core.qualname(func)
332
+
333
+ def failure(attempts: list[Attempt], reason: str) -> ValidationRepairExhausted:
334
+ _core.emit("llm.repair_exhausted", label, attempts=len(attempts), reason=reason)
335
+ return ValidationRepairExhausted(label, attempts, reason)
336
+
337
+ def judged(
338
+ response: Any, attempts: list[Attempt]
339
+ ) -> tuple[Any, str | None, str, Usage | None]:
340
+ output, used = plan.read(response)
341
+ value, error = plan.check(output)
342
+ attempts.append(Attempt(len(attempts) + 1, output, error, used))
343
+ if error is not None:
344
+ _core.emit("llm.validation_failed", label, attempt=len(attempts), error=error[:200])
345
+ return value, error, output, used
346
+
347
+ if _core.is_async(func):
348
+ afunc = cast("Callable[..., Awaitable[Any]]", func)
349
+
350
+ @functools.wraps(func)
351
+ async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
352
+ attempts: list[Attempt] = []
353
+ call_args, call_kwargs = args, kwargs
354
+ while True:
355
+ response = await afunc(*call_args, **call_kwargs)
356
+ value, error, output, _ = judged(response, attempts)
357
+ if error is None:
358
+ return value
359
+ reason = plan.stop_reason(attempts, args, kwargs)
360
+ if reason:
361
+ raise failure(attempts, reason)
362
+ call_args, call_kwargs = plan.next_call(call_args, call_kwargs, output, error)
363
+
364
+ return cast("Callable[P, Any]", async_wrapper)
365
+
366
+ @functools.wraps(func)
367
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> Any:
368
+ attempts: list[Attempt] = []
369
+ call_args: tuple[Any, ...] = args
370
+ call_kwargs: dict[str, Any] = kwargs
371
+ while True:
372
+ response = func(*call_args, **call_kwargs)
373
+ value, error, output, _ = judged(response, attempts)
374
+ if error is None:
375
+ return value
376
+ reason = plan.stop_reason(attempts, args, kwargs)
377
+ if reason:
378
+ raise failure(attempts, reason)
379
+ call_args, call_kwargs = plan.next_call(call_args, call_kwargs, output, error)
380
+
381
+ return wrapper
382
+
383
+ return decorate