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
python_wrap/_fork.py ADDED
@@ -0,0 +1,113 @@
1
+ """Weakly registered child resets; no application work is started at fork time."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import threading
7
+ import weakref
8
+ from collections.abc import Callable
9
+ from types import TracebackType
10
+ from typing import Any
11
+
12
+ __all__ = ["ForkSafeLock", "ForkSafeRLock", "register", "register_reset", "unregister"]
13
+ _registry: weakref.WeakSet[Any] = weakref.WeakSet()
14
+ _registry_lock = threading.Lock()
15
+ _installed = False
16
+
17
+
18
+ def register(obj: Any) -> None:
19
+ """Weakly register an object's `_reset_after_fork` method on POSIX."""
20
+ if not hasattr(os, "register_at_fork"):
21
+ return
22
+ global _installed
23
+ with _registry_lock:
24
+ if not _installed:
25
+ os.register_at_fork(after_in_child=_after_fork)
26
+ _installed = True
27
+ _registry.add(obj)
28
+
29
+
30
+ def unregister(obj: Any) -> None:
31
+ """Remove an object from the reset registry."""
32
+ with _registry_lock:
33
+ _registry.discard(obj)
34
+
35
+
36
+ def _after_fork() -> None:
37
+ global _registry_lock
38
+ _registry_lock = threading.Lock()
39
+ objects = list(_registry)
40
+ # Callbacks may acquire their component's lock: reset every lock first.
41
+ for obj in objects:
42
+ if isinstance(obj, (ForkSafeLock, ForkSafeRLock)):
43
+ obj._reset_after_fork()
44
+ for obj in objects:
45
+ if not isinstance(obj, (ForkSafeLock, ForkSafeRLock)):
46
+ obj._reset_after_fork()
47
+
48
+
49
+ class ForkSafeLock:
50
+ """Lock with the acquire/release/context API, reset in a forked child."""
51
+
52
+ def __init__(self) -> None:
53
+ self._lock = threading.Lock()
54
+ register(self)
55
+
56
+ def _reset_after_fork(self) -> None:
57
+ self._lock = threading.Lock()
58
+
59
+ def acquire(self, blocking: bool = True, timeout: float = -1) -> bool:
60
+ return self._lock.acquire(blocking, timeout)
61
+
62
+ def release(self) -> None:
63
+ self._lock.release()
64
+
65
+ def locked(self) -> bool:
66
+ return self._lock.locked()
67
+
68
+ def __enter__(self) -> bool:
69
+ return self.acquire()
70
+
71
+ def __exit__(
72
+ self, typ: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None
73
+ ) -> None:
74
+ self.release()
75
+
76
+
77
+ class ForkSafeRLock:
78
+ """Reentrant counterpart of `ForkSafeLock`."""
79
+
80
+ def __init__(self) -> None:
81
+ self._lock = threading.RLock()
82
+ register(self)
83
+
84
+ def _reset_after_fork(self) -> None:
85
+ self._lock = threading.RLock()
86
+
87
+ def acquire(self, blocking: bool = True, timeout: float = -1) -> bool:
88
+ return self._lock.acquire(blocking, timeout)
89
+
90
+ def release(self) -> None:
91
+ self._lock.release()
92
+
93
+ def __enter__(self) -> bool:
94
+ return self.acquire()
95
+
96
+ def __exit__(
97
+ self, typ: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None
98
+ ) -> None:
99
+ self.release()
100
+
101
+
102
+ class _Reset:
103
+ def __init__(self, reset: Callable[[], None]) -> None:
104
+ self.reset = reset
105
+ register(self)
106
+
107
+ def _reset_after_fork(self) -> None:
108
+ self.reset()
109
+
110
+
111
+ def register_reset(reset: Callable[[], None]) -> _Reset:
112
+ """Return a weakly registered handle; its owner must keep the handle alive."""
113
+ return _Reset(reset)
@@ -0,0 +1,29 @@
1
+ """Shared request/task context plumbing for optional framework adapters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import re
7
+ import uuid
8
+ from typing import Any
9
+
10
+ from python_wrap._runtime import seconds
11
+ from python_wrap.deadline import deadline
12
+ from python_wrap.logs import log_context
13
+
14
+
15
+ def request_id(value: Any) -> str:
16
+ text = str(value or "")
17
+ return text if re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", text) else uuid.uuid4().hex
18
+
19
+
20
+ def scope(fields: dict[str, Any], budget: float | None = None) -> contextlib.ExitStack:
21
+ stack = contextlib.ExitStack()
22
+ try:
23
+ stack.enter_context(log_context(**fields))
24
+ if budget is not None:
25
+ stack.enter_context(deadline(seconds(budget, positive=False)))
26
+ except BaseException:
27
+ stack.close()
28
+ raise
29
+ return stack
@@ -0,0 +1,157 @@
1
+ """Small shared helpers for optional integrations and backend-based decorators."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import dataclasses
7
+ import enum
8
+ import functools
9
+ import hashlib
10
+ import inspect
11
+ import math
12
+ import pickle
13
+ import re
14
+ from collections.abc import Callable
15
+ from pathlib import PurePath
16
+ from typing import Any, ParamSpec, TypeVar
17
+
18
+
19
+ def seconds(value: float | str, *, positive: bool = True) -> float:
20
+ """Parse a finite duration, optionally suffixed by ms/s/m/h/d."""
21
+ if isinstance(value, str):
22
+ match = re.fullmatch(r"\s*(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?\s*", value)
23
+ if not match:
24
+ raise ValueError(f"invalid duration: {value!r}")
25
+ result = (
26
+ float(match[1])
27
+ * {None: 1, "ms": 0.001, "s": 1, "m": 60, "h": 3600, "d": 86400}[match[2]]
28
+ )
29
+ else:
30
+ result = float(value)
31
+ if not math.isfinite(result) or result < 0 or (positive and result == 0):
32
+ raise ValueError(
33
+ "duration must be finite and positive"
34
+ if positive
35
+ else "duration must be finite and non-negative"
36
+ )
37
+ return result
38
+
39
+
40
+ def digest(value: Any) -> str:
41
+ """Pickle digest for names and other values that are stable by construction."""
42
+ return hashlib.sha256(pickle.dumps(value, protocol=4)).hexdigest()
43
+
44
+
45
+ def _enc(value: Any, out: list[bytes]) -> None:
46
+ kind = type(value)
47
+ if value is None:
48
+ out.append(b"N")
49
+ elif kind is bool:
50
+ out.append(b"T" if value else b"F")
51
+ elif kind is int:
52
+ out.append(b"i%d;" % value)
53
+ elif kind is float:
54
+ out.append(b"f" + value.hex().encode() + b";")
55
+ elif kind is str:
56
+ raw = value.encode("utf-8", "surrogatepass")
57
+ out.append(b"s%d:" % len(raw) + raw)
58
+ elif kind in (bytes, bytearray):
59
+ out.append(b"b%d:" % len(value) + bytes(value))
60
+ elif kind in (tuple, list):
61
+ out.append((b"t%d[" if kind is tuple else b"l%d[") % len(value))
62
+ for item in value:
63
+ _enc(item, out)
64
+ elif kind is dict:
65
+ items = []
66
+ for k, v in value.items():
67
+ part: list[bytes] = []
68
+ _enc(k, part)
69
+ _enc(v, part)
70
+ items.append(b"".join(part))
71
+ out.append(b"d%d{" % len(items) + b"".join(sorted(items)))
72
+ elif kind in (set, frozenset):
73
+ members = []
74
+ for item in value:
75
+ part = []
76
+ _enc(item, part)
77
+ members.append(b"".join(part))
78
+ out.append(b"S%d{" % len(members) + b"".join(sorted(members)))
79
+ elif kind.__name__ == "_Tag": # caching's list/dict/set markers
80
+ out.append(b"g" + value.name.encode() + b";")
81
+ elif isinstance(value, enum.Enum):
82
+ out.append(f"E{kind.__module__}.{kind.__qualname__}:".encode())
83
+ _enc(value.value, out)
84
+ elif kind.__module__ in ("datetime", "decimal", "uuid") or isinstance(value, PurePath):
85
+ out.append(f"O{kind.__qualname__}:{value}".encode() + b";")
86
+ elif dataclasses.is_dataclass(value) and not isinstance(value, type):
87
+ out.append(f"C{kind.__module__}.{kind.__qualname__}:".encode())
88
+ _enc({f.name: getattr(value, f.name) for f in dataclasses.fields(value)}, out)
89
+ else:
90
+ raise TypeError(
91
+ f"a value of type {kind.__qualname__!r} has no stable cache key across "
92
+ "processes; pass key=<callable> that returns a str or tuple of plain values"
93
+ )
94
+
95
+
96
+ def stable_digest(value: Any) -> str:
97
+ """A digest that is equal in every process for equal plain values.
98
+
99
+ Dict items and set members are sorted by their encoding, so insertion order and the
100
+ per-process hash seed never change the result. Unsupported objects raise `TypeError`.
101
+ """
102
+ out: list[bytes] = []
103
+ _enc(value, out)
104
+ return hashlib.sha256(b"".join(out)).hexdigest()
105
+
106
+
107
+ def call_key(
108
+ func: Callable[..., Any],
109
+ key: str | Callable[..., Any] | None,
110
+ args: tuple[Any, ...],
111
+ kwargs: dict[str, Any],
112
+ ) -> str:
113
+ if isinstance(key, str):
114
+ return key
115
+ if key is not None:
116
+ return str(key(*args, **kwargs))
117
+ bound = inspect.signature(func).bind(*args, **kwargs)
118
+ bound.apply_defaults()
119
+ for name, value in bound.arguments.items():
120
+ try:
121
+ _enc(value, [])
122
+ except TypeError as exc:
123
+ raise TypeError(f"argument {name!r}: {exc}") from None
124
+ return f"{func.__module__}.{func.__qualname__}:{stable_digest(tuple(bound.arguments.items()))}"
125
+
126
+
127
+ def preserve(func: Callable[..., Any], wrapper: Callable[..., Any]) -> Any:
128
+ return functools.update_wrapper(wrapper, func)
129
+
130
+
131
+ P = ParamSpec("P")
132
+ T = TypeVar("T")
133
+
134
+
135
+ async def offload_settled(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T:
136
+ """Run synchronous side effects in a thread, settling them before cancellation exits.
137
+
138
+ Callers must set I/O timeouts on their clients: a Python task cannot stop a thread.
139
+ This prevents a cancelled batch from releasing its outer lease while a checkpoint
140
+ write or synchronous handler is still running.
141
+ """
142
+ import asyncio
143
+
144
+ task = asyncio.create_task(asyncio.to_thread(func, *args, **kwargs))
145
+ cancelled: asyncio.CancelledError | None = None
146
+ while not task.done():
147
+ try:
148
+ await asyncio.shield(task)
149
+ except asyncio.CancelledError as exc:
150
+ cancelled = exc
151
+ except BaseException:
152
+ break
153
+ if cancelled is not None:
154
+ with contextlib.suppress(BaseException):
155
+ task.result()
156
+ raise cancelled
157
+ return task.result()
@@ -0,0 +1,101 @@
1
+ """Adapters for provider SDKs and agent frameworks.
2
+
3
+ Each adapter is a plain python-wrap module that reads its SDK by shape: none of them
4
+ imports the SDK, so ``python-wrap`` keeps zero runtime dependencies and importing
5
+ ``python_wrap.adapters`` costs nothing until a name is used (exports load lazily).
6
+
7
+ - `guard_openai` / `guard_anthropic`: proxies around the OpenAI and Anthropic Python
8
+ SDK clients with one retry loop, a `Budget`, a token limit fed by the provider's
9
+ rate-limit headers, and resume-safe streams.
10
+ - `no_sdk_retries`, `sdk_max_retries`: switch the SDK's own retries off.
11
+ - `resume_safe`, `ResumableStream`, `StreamInterrupted`, `StreamedToolCall`: reopen
12
+ a stream only while no output has been handed out.
13
+ - `CacheGuard`, `CacheStats`, `PromptCacheWarning`: watch prompt-cache hit rates.
14
+ - `guard_chat_model`, `PythonWrapCallback`: the same rules for LangChain chat models.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import importlib
20
+ from typing import TYPE_CHECKING, Any
21
+
22
+ if TYPE_CHECKING:
23
+ from python_wrap.adapters._sdk import (
24
+ CacheGuard,
25
+ CacheStats,
26
+ GuardedClient,
27
+ PromptCacheWarning,
28
+ ResumableStream,
29
+ StreamedToolCall,
30
+ StreamInterrupted,
31
+ no_sdk_retries,
32
+ resume_safe,
33
+ sdk_max_retries,
34
+ seed_limiter,
35
+ stream_transient,
36
+ )
37
+ from python_wrap.adapters.anthropic import GuardedAnthropic, guard_anthropic
38
+ from python_wrap.adapters.langchain import (
39
+ GuardedChatModel,
40
+ PythonWrapCallback,
41
+ guard_chat_model,
42
+ )
43
+ from python_wrap.adapters.openai import GuardedOpenAI, guard_openai
44
+
45
+ #: Public name -> submodule that defines it (imported on first access).
46
+ _EXPORTS: dict[str, str] = {
47
+ "CacheGuard": "_sdk",
48
+ "CacheStats": "_sdk",
49
+ "GuardedClient": "_sdk",
50
+ "PromptCacheWarning": "_sdk",
51
+ "ResumableStream": "_sdk",
52
+ "StreamInterrupted": "_sdk",
53
+ "StreamedToolCall": "_sdk",
54
+ "no_sdk_retries": "_sdk",
55
+ "resume_safe": "_sdk",
56
+ "sdk_max_retries": "_sdk",
57
+ "seed_limiter": "_sdk",
58
+ "stream_transient": "_sdk",
59
+ "GuardedOpenAI": "openai",
60
+ "guard_openai": "openai",
61
+ "GuardedAnthropic": "anthropic",
62
+ "guard_anthropic": "anthropic",
63
+ "GuardedChatModel": "langchain",
64
+ "PythonWrapCallback": "langchain",
65
+ "guard_chat_model": "langchain",
66
+ }
67
+
68
+ __all__ = [
69
+ "CacheGuard",
70
+ "CacheStats",
71
+ "GuardedAnthropic",
72
+ "GuardedChatModel",
73
+ "GuardedClient",
74
+ "GuardedOpenAI",
75
+ "PromptCacheWarning",
76
+ "PythonWrapCallback",
77
+ "ResumableStream",
78
+ "StreamInterrupted",
79
+ "StreamedToolCall",
80
+ "guard_anthropic",
81
+ "guard_chat_model",
82
+ "guard_openai",
83
+ "no_sdk_retries",
84
+ "resume_safe",
85
+ "sdk_max_retries",
86
+ "seed_limiter",
87
+ "stream_transient",
88
+ ]
89
+
90
+
91
+ def __getattr__(name: str) -> Any:
92
+ module = _EXPORTS.get(name)
93
+ if module is None:
94
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
95
+ value = getattr(importlib.import_module(f"{__name__}.{module}"), name)
96
+ globals()[name] = value
97
+ return value
98
+
99
+
100
+ def __dir__() -> list[str]:
101
+ return sorted({*globals(), *_EXPORTS})
@@ -0,0 +1,251 @@
1
+ """Shared pieces of the agent-framework adapters (no framework is imported here)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ import time
7
+ from collections.abc import Mapping
8
+ from typing import Any
9
+
10
+ from python_wrap import _core
11
+ from python_wrap.agents import (
12
+ EffectConflict,
13
+ EffectUnknown,
14
+ LoopDetected,
15
+ RunBudgetExceeded,
16
+ RunCancelled,
17
+ RunTimeout,
18
+ StepLimitExceeded,
19
+ canonical,
20
+ run_id_var,
21
+ )
22
+ from python_wrap.llm import BudgetExceeded, Usage
23
+
24
+ _LAYER_ATTR = "__python_wrap_layer__"
25
+
26
+ #: Errors that end the agent run instead of being reported to the model as a tool error.
27
+ FATAL: tuple[type[BaseException], ...] = (
28
+ StepLimitExceeded,
29
+ LoopDetected,
30
+ RunTimeout,
31
+ RunCancelled,
32
+ RunBudgetExceeded,
33
+ BudgetExceeded,
34
+ EffectUnknown,
35
+ EffectConflict,
36
+ )
37
+
38
+
39
+ def is_model_retry(exc: BaseException) -> bool:
40
+ """True for pydantic-ai's ``ModelRetry`` (matched by class name, never imported)."""
41
+ return any(cls.__name__ == "ModelRetry" for cls in type(exc).__mro__)
42
+
43
+
44
+ class PassThrough(BaseException):
45
+ """Carries an exception through a retry layer that must not retry it."""
46
+
47
+ def __init__(self, error: BaseException) -> None:
48
+ super().__init__(repr(error))
49
+ self.error = error
50
+
51
+
52
+ def _int(value: Any) -> int:
53
+ return value if isinstance(value, int) and not isinstance(value, bool) else 0
54
+
55
+
56
+ def _field(source: Any, name: str) -> Any:
57
+ if isinstance(source, Mapping):
58
+ return source.get(name)
59
+ return getattr(source, name, None)
60
+
61
+
62
+ def usage_totals(source: Any) -> tuple[int, int] | None:
63
+ """``(input, output)`` tokens of a framework usage object, result or response.
64
+
65
+ Reads ``input_tokens`` / ``output_tokens`` (pydantic-ai 1.x, OpenAI Agents SDK),
66
+ ``request_tokens`` / ``response_tokens`` (older pydantic-ai) or ``prompt_tokens`` /
67
+ ``completion_tokens``; a ``usage`` attribute or a ``usage()`` method is followed.
68
+ """
69
+ usage = source
70
+ found = _field(source, "usage")
71
+ if found is not None:
72
+ has_fields = any(
73
+ _field(found, name) is not None
74
+ for name in ("input_tokens", "request_tokens", "prompt_tokens")
75
+ )
76
+ # pydantic-ai 2 made ``usage`` a property that still accepts a (deprecated) call.
77
+ usage = found() if callable(found) and not has_fields else found
78
+ names = (
79
+ ("input_tokens", "output_tokens"),
80
+ ("request_tokens", "response_tokens"),
81
+ ("prompt_tokens", "completion_tokens"),
82
+ )
83
+ for inputs, outputs in names:
84
+ tin, tout = _field(usage, inputs), _field(usage, outputs)
85
+ if tin is not None or tout is not None:
86
+ return _int(tin), _int(tout)
87
+ return None
88
+
89
+
90
+ class UsageBridge:
91
+ """Feed cumulative framework usage into a python-wrap `Budget`, counting each token once.
92
+
93
+ Framework usage objects are running totals for one run. `sync` adds only the growth
94
+ since the last reading; a total that went down means a new run started.
95
+ """
96
+
97
+ def __init__(self, budget: Any, model: str | None = None) -> None:
98
+ self.budget = budget
99
+ self.model = model
100
+ self._last = (0, 0)
101
+ self._lock = threading.Lock()
102
+
103
+ def add(self, tokens_in: int, tokens_out: int, model: str | None = None) -> Any:
104
+ """Add a known amount (one model response)."""
105
+ if self.budget is None or (tokens_in <= 0 and tokens_out <= 0):
106
+ return None
107
+ return self.budget.record(Usage(max(tokens_in, 0), max(tokens_out, 0), model or self.model))
108
+
109
+ def sync(self, source: Any, model: str | None = None) -> Any:
110
+ """Add the growth of a running total; returns the budget's spend (or None)."""
111
+ totals = usage_totals(source)
112
+ if totals is None or self.budget is None:
113
+ return None
114
+ with self._lock:
115
+ last = self._last
116
+ if totals[0] < last[0] or totals[1] < last[1]:
117
+ last = (0, 0)
118
+ delta = (totals[0] - last[0], totals[1] - last[1])
119
+ self._last = totals
120
+ return self.add(delta[0], delta[1], model)
121
+
122
+ def reset(self) -> None:
123
+ """Forget the last reading (call between runs that reuse the bridge)."""
124
+ with self._lock:
125
+ self._last = (0, 0)
126
+
127
+ def check(self, label: str) -> None:
128
+ """Raise `BudgetExceeded` if the budget's current scope is used up."""
129
+ budget = self.budget
130
+ if budget is None:
131
+ return
132
+ try:
133
+ exhausted = budget.exhausted()
134
+ except (RuntimeError, ValueError):
135
+ return # a run/key budget used outside its scope: the decorated calls check it
136
+ if exhausted:
137
+ raise budget._refuse(label, budget.spent())
138
+
139
+
140
+ def record_tool(
141
+ tape: Any,
142
+ *,
143
+ framework: str,
144
+ name: str,
145
+ arguments: Any,
146
+ result: Any,
147
+ error: BaseException | None,
148
+ started: float,
149
+ call_id: str | None,
150
+ ) -> None:
151
+ """Append one tool call to an `AuditTape`; never raises."""
152
+ if tape is None:
153
+ return
154
+ try:
155
+ from python_wrap.genai import Redactor
156
+
157
+ scrub = tape.redactor or Redactor()
158
+ tape.record(
159
+ timestamp=time.time(),
160
+ kind="tool",
161
+ name=name,
162
+ function=f"{framework}:{name}",
163
+ run_id=run_id_var.get(),
164
+ tool=name,
165
+ status="ok" if error is None else "error",
166
+ input=scrub({"arguments": arguments, "call_id": call_id}),
167
+ output=None if error is not None else scrub(result),
168
+ error=None
169
+ if error is None
170
+ else {"type": type(error).__name__, "message": scrub(str(error))},
171
+ latency=max(0.0, _core.monotonic() - started),
172
+ content=True,
173
+ )
174
+ except Exception:
175
+ _core.get_logger(None).exception("could not record %s tool call to the tape", framework)
176
+
177
+
178
+ def record_llm(
179
+ tape: Any, *, framework: str, model: str | None, tokens: tuple[int, int] | None
180
+ ) -> None:
181
+ """Append one model response (metadata only) to an `AuditTape`; never raises."""
182
+ if tape is None:
183
+ return
184
+ try:
185
+ tape.record(
186
+ timestamp=time.time(),
187
+ kind="llm",
188
+ name=model or framework,
189
+ function=f"{framework}:model",
190
+ run_id=run_id_var.get(),
191
+ model=model,
192
+ input_tokens=None if tokens is None else tokens[0],
193
+ output_tokens=None if tokens is None else tokens[1],
194
+ )
195
+ except Exception:
196
+ _core.get_logger(None).exception("could not record %s model call to the tape", framework)
197
+
198
+
199
+ class CallCounter:
200
+ """Tool-call and identical-call limits for frameworks without their own.
201
+
202
+ Thread-safe. ``max_tool_calls`` caps every tool call that passes through (sub-agents
203
+ included); ``max_repeats`` caps identical calls (same tool and arguments).
204
+ """
205
+
206
+ def __init__(self, max_tool_calls: int | None, max_repeats: int | None) -> None:
207
+ for label, value in (("max_tool_calls", max_tool_calls), ("max_repeats", max_repeats)):
208
+ if value is not None and (
209
+ isinstance(value, bool) or not isinstance(value, int) or value < 1
210
+ ):
211
+ raise ValueError(f"{label} must be a positive integer or None")
212
+ self.max_tool_calls = max_tool_calls
213
+ self.max_repeats = max_repeats
214
+ self._lock = threading.Lock()
215
+ self.calls = 0
216
+ self._seen: dict[tuple[str, str | None], int] = {}
217
+
218
+ def admit(self, name: str, arguments: Any) -> None:
219
+ """Count one call or raise `StepLimitExceeded` / `LoopDetected`."""
220
+ if isinstance(arguments, str):
221
+ signature = canonical({"json": arguments})
222
+ elif isinstance(arguments, Mapping):
223
+ signature = canonical(arguments)
224
+ else:
225
+ signature = canonical({"value": arguments}) if arguments is not None else None
226
+ run_id = run_id_var.get() or "-"
227
+ with self._lock:
228
+ if self.max_tool_calls is not None and self.calls >= self.max_tool_calls:
229
+ raise StepLimitExceeded(
230
+ f"reached max_tool_calls={self.max_tool_calls}; refused tool {name!r}",
231
+ run_id=run_id,
232
+ limit=self.max_tool_calls,
233
+ )
234
+ key = (name, signature)
235
+ seen = self._seen.get(key, 0)
236
+ if signature is not None and self.max_repeats is not None and seen >= self.max_repeats:
237
+ raise LoopDetected(
238
+ f"tool {name!r} was already called {seen} time(s) with the same "
239
+ f"arguments (max_repeats={self.max_repeats})",
240
+ run_id=run_id,
241
+ name=name,
242
+ repeats=seen,
243
+ )
244
+ self.calls += 1
245
+ self._seen[key] = seen + 1
246
+
247
+ def reset(self) -> None:
248
+ """Start counting from zero (a new run)."""
249
+ with self._lock:
250
+ self.calls = 0
251
+ self._seen.clear()