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,459 @@
1
+ """python-wrap for pydantic-ai agents: guarded tools, one budget, an audit tape, loop guards.
2
+
3
+ pydantic-ai is never imported at module level. `PythonWrapCapability` holds the settings
4
+ and does the work; it reaches pydantic-ai in two duck-typed ways:
5
+
6
+ * `PythonWrapCapability.wrap` turns any pydantic-ai toolset into a ``WrapperToolset``
7
+ (imported lazily) whose ``call_tool`` goes through the capability, and
8
+ `PythonWrapCapability.toolset` builds one from plain functions;
9
+ * `PythonWrapCapability.tool` (or `guard_tool`) wraps a single tool function for
10
+ ``agent.tool`` / ``agent.tool_plain`` and keeps its signature and docstring, so the
11
+ schema pydantic-ai builds is unchanged.
12
+
13
+ Every tool call then: counts against ``max_tool_calls`` / ``max_repeats`` and the current
14
+ `RunGuard` (identical repeated calls end the run with `LoopDetected`), passes the
15
+ `ToolPolicy` checks and approval, is deduplicated by an `EffectLedger` keyed on
16
+ pydantic-ai's ``tool_call_id``, runs under a per-attempt ``timeout`` and ``retry`` that
17
+ never retries ``ModelRetry`` (that exception is pydantic-ai's way of asking the model to
18
+ try again, so it passes straight through), and is written to an `AuditTape`.
19
+
20
+ Token usage: ``RunContext.usage`` (seen at every tool call) and the run result's
21
+ ``usage()`` are running totals; `PythonWrapCapability` adds only their growth to a
22
+ python-wrap `Budget`, so one budget can span pydantic-ai runs, direct SDK calls and
23
+ other frameworks. Keep pydantic-ai's ``UsageLimits`` for per-run request and token caps
24
+ enforced inside the model loop; use the `Budget` for dollars, per-user or per-tenant
25
+ limits, limits across many runs and processes, and stacks that mix frameworks.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import contextlib
31
+ import contextvars
32
+ import fnmatch
33
+ import functools
34
+ import importlib
35
+ from collections.abc import Awaitable, Callable, Iterable, Iterator
36
+ from typing import Any, TypeVar, cast
37
+
38
+ from python_wrap import _core
39
+ from python_wrap.adapters._frameworks import (
40
+ _LAYER_ATTR,
41
+ CallCounter,
42
+ PassThrough,
43
+ UsageBridge,
44
+ is_model_retry,
45
+ record_llm,
46
+ record_tool,
47
+ usage_totals,
48
+ )
49
+ from python_wrap.agents import (
50
+ EffectLedger,
51
+ RunGuard,
52
+ ToolNotAllowed,
53
+ ToolPolicy,
54
+ current_run,
55
+ tool,
56
+ with_call_id,
57
+ )
58
+
59
+ __all__ = ["PythonWrapCapability", "guard_tool", "usage_totals"]
60
+
61
+ F = TypeVar("F", bound=Callable[..., Any])
62
+ FRAMEWORK = "pydantic-ai"
63
+
64
+ _NEXT: contextvars.ContextVar[Callable[[], Awaitable[Any]] | None] = contextvars.ContextVar(
65
+ "python_wrap_pydantic_ai_next", default=None
66
+ )
67
+
68
+
69
+ def _matcher(patterns: Iterable[str] | str | None) -> Callable[[str], bool]:
70
+ if patterns is None:
71
+ return lambda name: False
72
+ found = (patterns,) if isinstance(patterns, str) else tuple(patterns)
73
+ return lambda name: any(fnmatch.fnmatchcase(name, p) for p in found)
74
+
75
+
76
+ def _passthrough(func: Callable[..., Any]) -> Callable[..., Any]:
77
+ """Turn ``ModelRetry`` into `PassThrough` so an enclosing retry cannot catch it."""
78
+ if _core.is_async(func):
79
+
80
+ @functools.wraps(func)
81
+ async def async_inner(*args: Any, **kwargs: Any) -> Any:
82
+ try:
83
+ return await func(*args, **kwargs)
84
+ except Exception as exc:
85
+ if is_model_retry(exc):
86
+ raise PassThrough(exc) from None
87
+ raise
88
+
89
+ return async_inner
90
+
91
+ @functools.wraps(func)
92
+ def inner(*args: Any, **kwargs: Any) -> Any:
93
+ try:
94
+ return func(*args, **kwargs)
95
+ except Exception as exc:
96
+ if is_model_retry(exc):
97
+ raise PassThrough(exc) from None
98
+ raise
99
+
100
+ return inner
101
+
102
+
103
+ def _unwrap(func: Callable[..., Any]) -> Callable[..., Any]:
104
+ if _core.is_async(func):
105
+
106
+ @functools.wraps(func)
107
+ async def async_outer(*args: Any, **kwargs: Any) -> Any:
108
+ try:
109
+ return await func(*args, **kwargs)
110
+ except PassThrough as wrapped:
111
+ raise wrapped.error from None
112
+
113
+ return async_outer
114
+
115
+ @functools.wraps(func)
116
+ def outer(*args: Any, **kwargs: Any) -> Any:
117
+ try:
118
+ return func(*args, **kwargs)
119
+ except PassThrough as wrapped:
120
+ raise wrapped.error from None
121
+
122
+ return outer
123
+
124
+
125
+ def compose(
126
+ func: Callable[..., Any],
127
+ *,
128
+ timeout: float | str | None,
129
+ retry: Callable[[Callable[..., Any]], Callable[..., Any]] | None,
130
+ ) -> Callable[..., Any]:
131
+ """``func`` under a per-attempt timeout and a retry that lets ``ModelRetry`` through."""
132
+ core = func
133
+ if timeout is not None:
134
+ from python_wrap._runtime import seconds
135
+ from python_wrap.concurrency import timeout as make_timeout
136
+
137
+ core = make_timeout(seconds(timeout))(core)
138
+ if retry is None:
139
+ return core
140
+ return _unwrap(retry(_passthrough(core)))
141
+
142
+
143
+ class PythonWrapCapability:
144
+ """python-wrap's tool safety, budget, audit and loop guards for pydantic-ai agents.
145
+
146
+ Args:
147
+ timeout: Per-attempt time limit for every tool (seconds or ``"30s"``); None
148
+ leaves tools unbounded (`doctor` reports PW020 for wrapped tools).
149
+ retry: A retry decorator (``retry(max_attempts=3, on=ConnectionError)``) applied
150
+ per call, inside the ledger; ``ModelRetry`` is never retried.
151
+ ledger: An `EffectLedger`; side-effect tools are then replay-safe per
152
+ ``tool_call_id``. Without one tools are not deduplicated.
153
+ read_only: Glob patterns of tools without side effects (they still run in
154
+ read-only and dry runs of a `ToolPolicy`).
155
+ approval: Glob patterns of tools that need the approver's yes (``ToolPolicy``
156
+ of the current run, or ``policy``).
157
+ policy: A `ToolPolicy` in effect for every call (in addition to the run's).
158
+ guard: A `RunGuard` entered by `run` / `run_sync`.
159
+ budget: A python-wrap `Budget` fed with the run's token usage.
160
+ tape: An `AuditTape` receiving every tool call and the run's usage.
161
+ max_tool_calls: Most tool calls per run (`StepLimitExceeded`).
162
+ max_repeats: Most identical tool calls (same name and arguments) per run
163
+ (`LoopDetected`).
164
+ on_denied: ``"raise"`` ends the run when a policy or the approver refuses a
165
+ tool; ``"retry"`` tells the model instead (as ``ModelRetry``).
166
+ model: The model name used to price usage that does not name one.
167
+
168
+ Example:
169
+ ```python
170
+ from python_wrap.agents import EffectLedger
171
+ from python_wrap.adapters.pydantic_ai import PythonWrapCapability
172
+
173
+ cap = PythonWrapCapability(timeout=10, ledger=EffectLedger(), max_repeats=2)
174
+
175
+ @cap.tool
176
+ def add_note(ticket: str, text: str) -> str:
177
+ "Attach a note to a ticket."
178
+ return f"noted {ticket}"
179
+
180
+ assert add_note("T-1", "hi") == "noted T-1"
181
+ assert add_note.__doc__ == "Attach a note to a ticket."
182
+ ```
183
+ """
184
+
185
+ def __init__(
186
+ self,
187
+ *,
188
+ timeout: float | str | None = None,
189
+ retry: Callable[[Callable[..., Any]], Callable[..., Any]] | None = None,
190
+ ledger: EffectLedger | None = None,
191
+ read_only: Iterable[str] | str | None = None,
192
+ approval: Iterable[str] | str | None = None,
193
+ policy: ToolPolicy | None = None,
194
+ guard: RunGuard | None = None,
195
+ budget: Any = None,
196
+ tape: Any = None,
197
+ max_tool_calls: int | None = None,
198
+ max_repeats: int | None = None,
199
+ on_denied: str = "raise",
200
+ model: str | None = None,
201
+ ) -> None:
202
+ if on_denied not in ("raise", "retry"):
203
+ raise ValueError("on_denied must be 'raise' or 'retry'")
204
+ if ledger is not None and not isinstance(ledger, EffectLedger):
205
+ raise TypeError("ledger must be an EffectLedger")
206
+ if policy is not None and not isinstance(policy, ToolPolicy):
207
+ raise TypeError("policy must be a ToolPolicy")
208
+ if guard is not None and not isinstance(guard, RunGuard):
209
+ raise TypeError("guard must be a RunGuard")
210
+ self.timeout = timeout
211
+ self.retry = retry
212
+ self.ledger = ledger
213
+ self.policy = policy
214
+ self.guard = guard
215
+ self.budget = budget
216
+ self.tape = tape
217
+ self.on_denied = on_denied
218
+ self.model = model
219
+ self.counter = CallCounter(max_tool_calls, max_repeats)
220
+ self.bridge = UsageBridge(budget, model)
221
+ self._read_only = _matcher(read_only)
222
+ self._approval = _matcher(approval)
223
+ self._tools: dict[str, Callable[..., Any]] = {}
224
+
225
+ # -- tool functions ---------------------------------------------------------
226
+ def _python_wrap_tool(self, func: Callable[..., Any], name: str) -> Callable[..., Any]:
227
+ decorate = tool(
228
+ name=name,
229
+ read_only=self._read_only(name),
230
+ requires_approval=self._approval(name),
231
+ ledger=self.ledger,
232
+ idempotent_key=None if self.ledger is not None else False,
233
+ )
234
+ return decorate(compose(func, timeout=self.timeout, retry=self.retry))
235
+
236
+ def tool(self, func: F | None = None, /, *, name: str | None = None) -> Any:
237
+ """Wrap one tool function for ``agent.tool`` / ``agent.tool_plain``.
238
+
239
+ The signature, annotations and docstring are kept, so pydantic-ai builds the
240
+ same schema. A first ``ctx: RunContext`` parameter supplies the
241
+ ``tool_call_id`` and the running usage; it is left out of the argument digest.
242
+ """
243
+ if func is None:
244
+ return functools.partial(self.tool, name=name)
245
+ label = name or func.__name__
246
+ guarded = self._python_wrap_tool(func, label)
247
+
248
+ def admit(args: tuple[Any, ...], kwargs: dict[str, Any]) -> tuple[Any, str | None]:
249
+ ctx = args[0] if args and hasattr(args[0], "tool_call_id") else None
250
+ shown = dict(kwargs) or list(args[1 if ctx else 0 :])
251
+ self.counter.admit(label, shown)
252
+ if ctx is not None:
253
+ self.bridge.sync(getattr(ctx, "usage", None))
254
+ self.bridge.check(label)
255
+ return shown, None if ctx is None else getattr(ctx, "tool_call_id", None)
256
+
257
+ if _core.is_async(func):
258
+
259
+ @functools.wraps(func)
260
+ async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
261
+ shown, call_id = admit(args, kwargs)
262
+ started = _core.monotonic()
263
+ try:
264
+ with with_call_id(call_id or None):
265
+ result = await self._denied_as_retry(guarded(*args, **kwargs))
266
+ except BaseException as exc:
267
+ self._record(label, shown, None, exc, started, call_id)
268
+ raise
269
+ self._record(label, shown, result, None, started, call_id)
270
+ return result
271
+
272
+ wrapper: Callable[..., Any] = async_wrapper
273
+ else:
274
+
275
+ @functools.wraps(func)
276
+ def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
277
+ shown, call_id = admit(args, kwargs)
278
+ started = _core.monotonic()
279
+ try:
280
+ with with_call_id(call_id or None), self._denials():
281
+ result = guarded(*args, **kwargs)
282
+ except BaseException as exc:
283
+ self._record(label, shown, None, exc, started, call_id)
284
+ raise
285
+ self._record(label, shown, result, None, started, call_id)
286
+ return result
287
+
288
+ wrapper = sync_wrapper
289
+ setattr(wrapper, _LAYER_ATTR, self._layer(label))
290
+ return wrapper
291
+
292
+ def _layer(self, name: str) -> tuple[str, dict[str, Any]]:
293
+ return (
294
+ "framework_tool",
295
+ {"framework": FRAMEWORK, "name": name, "timeout": self.timeout},
296
+ )
297
+
298
+ def _record(
299
+ self,
300
+ name: str,
301
+ arguments: Any,
302
+ result: Any,
303
+ error: BaseException | None,
304
+ started: float,
305
+ call_id: str | None,
306
+ ) -> None:
307
+ record_tool(
308
+ self.tape,
309
+ framework=FRAMEWORK,
310
+ name=name,
311
+ arguments=arguments,
312
+ result=result,
313
+ error=error,
314
+ started=started,
315
+ call_id=call_id,
316
+ )
317
+
318
+ @contextlib.contextmanager
319
+ def _denials(self) -> Iterator[None]:
320
+ try:
321
+ yield
322
+ except ToolNotAllowed as exc:
323
+ if self.on_denied == "retry":
324
+ raise _model_retry(str(exc)) from exc
325
+ raise
326
+
327
+ async def _denied_as_retry(self, awaitable: Awaitable[Any]) -> Any:
328
+ with self._denials():
329
+ return await awaitable
330
+
331
+ # -- toolsets ----------------------------------------------------------------
332
+ async def call(
333
+ self,
334
+ name: str,
335
+ arguments: dict[str, Any],
336
+ ctx: Any,
337
+ call_next: Callable[[], Awaitable[Any]],
338
+ ) -> Any:
339
+ """Run one tool call through the capability (used by the wrapped toolset)."""
340
+ call_id = getattr(ctx, "tool_call_id", None)
341
+ self.counter.admit(name, arguments)
342
+ self.bridge.sync(getattr(ctx, "usage", None))
343
+ self.bridge.check(name)
344
+ guarded = self._tools.get(name)
345
+ if guarded is None:
346
+
347
+ async def invoke(arguments: dict[str, Any]) -> Any:
348
+ follow = _NEXT.get()
349
+ assert follow is not None
350
+ return await follow()
351
+
352
+ guarded = self._tools.setdefault(name, self._python_wrap_tool(invoke, name))
353
+ started = _core.monotonic()
354
+ reset = _NEXT.set(call_next)
355
+ try:
356
+ with with_call_id(call_id or None):
357
+ result = await self._denied_as_retry(guarded(arguments=arguments))
358
+ except BaseException as exc:
359
+ self._record(name, arguments, None, exc, started, call_id)
360
+ raise
361
+ finally:
362
+ _NEXT.reset(reset)
363
+ self._record(name, arguments, result, None, started, call_id)
364
+ return result
365
+
366
+ def wrap(self, toolset: Any) -> Any:
367
+ """A pydantic-ai ``WrapperToolset`` around ``toolset`` whose calls go through this.
368
+
369
+ Raises:
370
+ ImportError: pydantic-ai is not installed.
371
+ """
372
+ return _wrapper_class()(toolset, capability=self)
373
+
374
+ def toolset(self, *functions: Callable[..., Any]) -> Any:
375
+ """A guarded ``FunctionToolset`` of plain tool functions (pydantic-ai required)."""
376
+ toolsets = importlib.import_module("pydantic_ai.toolsets")
377
+ return self.wrap(toolsets.FunctionToolset(list(functions)))
378
+
379
+ # -- runs ---------------------------------------------------------------------
380
+ def reset(self) -> None:
381
+ """Start a new run: zero the call counters and the usage reading."""
382
+ self.counter.reset()
383
+ self.bridge.reset()
384
+
385
+ def finish(self, result: Any) -> Any:
386
+ """Feed a run result's final usage to the budget and the tape; returns the spend."""
387
+ model = None
388
+ response = getattr(result, "response", None)
389
+ if response is not None:
390
+ found = getattr(response, "model_name", None)
391
+ model = found if isinstance(found, str) else None
392
+ spend = self.bridge.sync(result, model)
393
+ record_llm(self.tape, framework=FRAMEWORK, model=model, tokens=usage_totals(result))
394
+ return spend
395
+
396
+ @contextlib.contextmanager
397
+ def _scope(self) -> Iterator[None]:
398
+ self.reset()
399
+ with contextlib.ExitStack() as stack:
400
+ if self.guard is not None and current_run() is None:
401
+ stack.enter_context(self.guard)
402
+ if self.budget is not None and getattr(self.budget, "per", None) == "run":
403
+ try:
404
+ self.budget.spent()
405
+ except RuntimeError:
406
+ stack.enter_context(self.budget.run())
407
+ self.bridge.check(FRAMEWORK)
408
+ yield
409
+
410
+ def run_sync(self, agent: Any, prompt: Any, /, **options: Any) -> Any:
411
+ """``agent.run_sync(prompt, **options)`` inside this capability's run scope."""
412
+ with self._scope():
413
+ result = agent.run_sync(prompt, **options)
414
+ self.finish(result)
415
+ return result
416
+
417
+ async def run(self, agent: Any, prompt: Any, /, **options: Any) -> Any:
418
+ """``await agent.run(prompt, **options)`` inside this capability's run scope."""
419
+ with self._scope():
420
+ result = await agent.run(prompt, **options)
421
+ self.finish(result)
422
+ return result
423
+
424
+
425
+ def guard_tool(func: F | None = None, /, **options: Any) -> Any:
426
+ """Shorthand for ``PythonWrapCapability(**options).tool(func)``."""
427
+ name = options.pop("name", None)
428
+ capability = PythonWrapCapability(**options)
429
+ if func is None:
430
+ return functools.partial(capability.tool, name=name)
431
+ return capability.tool(func, name=name)
432
+
433
+
434
+ def _model_retry(message: str) -> Exception:
435
+ model_retry = importlib.import_module("pydantic_ai").ModelRetry
436
+ return cast(Exception, model_retry(message))
437
+
438
+
439
+ @functools.lru_cache(maxsize=1)
440
+ def _wrapper_class() -> Any:
441
+ import dataclasses
442
+
443
+ base: Any = importlib.import_module("pydantic_ai.toolsets").WrapperToolset
444
+
445
+ @dataclasses.dataclass
446
+ class PythonWrapToolset(base): # type: ignore[misc]
447
+ """A toolset whose every call goes through a `PythonWrapCapability`."""
448
+
449
+ capability: Any = None
450
+
451
+ async def call_tool(self, name: str, tool_args: dict[str, Any], ctx: Any, tool: Any) -> Any:
452
+ parent = super().call_tool
453
+
454
+ def follow() -> Awaitable[Any]:
455
+ return cast(Awaitable[Any], parent(name, tool_args, ctx, tool))
456
+
457
+ return await self.capability.call(name, tool_args, ctx, follow)
458
+
459
+ return PythonWrapToolset