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.
- python_wrap/__init__.py +348 -1
- python_wrap/__main__.py +57 -0
- python_wrap/_backend.py +133 -0
- python_wrap/_buckets.py +162 -0
- python_wrap/_core.py +12 -3
- python_wrap/_data/agent_guide.md +103 -0
- python_wrap/_data/recipes.json +703 -0
- python_wrap/_fork.py +113 -0
- python_wrap/_integration.py +29 -0
- python_wrap/_runtime.py +157 -0
- python_wrap/adapters/__init__.py +101 -0
- python_wrap/adapters/_frameworks.py +251 -0
- python_wrap/adapters/_sdk.py +1978 -0
- python_wrap/adapters/anthropic.py +139 -0
- python_wrap/adapters/langchain.py +288 -0
- python_wrap/adapters/openai.py +169 -0
- python_wrap/adapters/openai_agents.py +468 -0
- python_wrap/adapters/pydantic_ai.py +459 -0
- python_wrap/adaptive.py +605 -0
- python_wrap/agents.py +2503 -0
- python_wrap/alerts.py +293 -0
- python_wrap/async_cache.py +745 -0
- python_wrap/batching.py +17 -4
- python_wrap/buffering.py +952 -0
- python_wrap/bulkhead.py +58 -6
- python_wrap/caching.py +425 -56
- python_wrap/celery.py +528 -0
- python_wrap/chaos.py +519 -0
- python_wrap/circuit.py +454 -23
- python_wrap/compat.py +267 -0
- python_wrap/concurrency.py +82 -1746
- python_wrap/config.py +25 -4
- python_wrap/coordination.py +638 -0
- python_wrap/credentials.py +126 -0
- python_wrap/dashboard.py +358 -0
- python_wrap/debounce.py +538 -0
- python_wrap/django.py +100 -0
- python_wrap/doctor.py +599 -0
- python_wrap/events.py +145 -4
- python_wrap/exporters.py +663 -0
- python_wrap/fastapi.py +81 -0
- python_wrap/flask.py +61 -0
- python_wrap/genai.py +1101 -0
- python_wrap/health.py +187 -0
- python_wrap/http.py +940 -0
- python_wrap/idempotency.py +446 -0
- python_wrap/introspect.py +738 -0
- python_wrap/lifecycle.py +620 -0
- python_wrap/llm.py +2574 -0
- python_wrap/llm_cassette.py +948 -0
- python_wrap/llm_http_chaos.py +326 -0
- python_wrap/llm_shared.py +772 -0
- python_wrap/llm_testing.py +990 -0
- python_wrap/llm_validate.py +383 -0
- python_wrap/local_state.py +395 -0
- python_wrap/logs.py +82 -26
- python_wrap/mcp.py +490 -0
- python_wrap/mcp_guard.py +357 -0
- python_wrap/metrics.py +6 -3
- python_wrap/migrate.py +1452 -0
- python_wrap/observability.py +484 -0
- python_wrap/periodic.py +24 -2
- python_wrap/policies.py +396 -0
- python_wrap/policy.py +14 -0
- python_wrap/predicates.py +276 -0
- python_wrap/presets.py +378 -0
- python_wrap/processing.py +227 -0
- python_wrap/propagation.py +62 -0
- python_wrap/pytest_plugin.py +85 -0
- python_wrap/quotas.py +319 -0
- python_wrap/ratelimit.py +560 -0
- python_wrap/redaction.py +228 -0
- python_wrap/retry.py +448 -70
- python_wrap/shared.py +653 -0
- python_wrap/singleflight.py +255 -0
- python_wrap/slow.py +72 -0
- python_wrap/stores.py +168 -0
- python_wrap/switches.py +164 -0
- python_wrap/testing.py +34 -8
- python_wrap/timeouts.py +874 -0
- python_wrap/timing.py +239 -17
- python_wrap/validation.py +187 -12
- python_wrap/web.py +723 -0
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/METADATA +117 -7
- python_wrap-0.4.0.dist-info/RECORD +95 -0
- python_wrap-0.2.1.dist-info/RECORD +0 -29
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/WHEEL +0 -0
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/licenses/LICENSE +0 -0
python_wrap/agents.py
ADDED
|
@@ -0,0 +1,2503 @@
|
|
|
1
|
+
"""Make agent tool use safe: idempotent tools, run guards, permissions and approvals.
|
|
2
|
+
|
|
3
|
+
An LLM agent calls tools in a loop the model drives. Four things go wrong in practice:
|
|
4
|
+
a retried or replayed "send email" runs twice, the loop never ends (the model calls the
|
|
5
|
+
same tool with the same arguments again and again), a tool with side effects runs when it
|
|
6
|
+
should only have been planned, and an irreversible action runs without a human saying
|
|
7
|
+
yes. This module covers each one without depending on any agent framework or provider SDK:
|
|
8
|
+
|
|
9
|
+
* `tool` marks a function as an agent tool. Tools with side effects get an idempotency
|
|
10
|
+
key derived from the tool name, the canonical arguments and the current run id, so a
|
|
11
|
+
replayed call returns the stored result instead of running again.
|
|
12
|
+
* `RunGuard` / `agent_run` bound one agent run: steps, wall time, identical repeated
|
|
13
|
+
calls and an optional budget. The run is visible through `current_run` and the
|
|
14
|
+
`run_id_var` context variable, nests, works with ``with`` and ``async with``, and
|
|
15
|
+
installs a `CancelToken` so `python_wrap.checkpoint` stops long tool code cooperatively.
|
|
16
|
+
* `ToolPolicy` enforces read-only runs, dry runs and allow/deny globs per run;
|
|
17
|
+
`ToolRegistry` dispatches tool calls by name (as a model emits them).
|
|
18
|
+
* ``requires_approval=True`` asks a user-supplied approver; no answer, a timeout or an
|
|
19
|
+
error denies.
|
|
20
|
+
* `EffectLedger` records every side effect as started / succeeded / failed, keyed on the
|
|
21
|
+
provider's tool-call id (`with_call_id`) when there is one: replays return the stored
|
|
22
|
+
result, concurrent duplicates run once, and a crash between the effect and the record
|
|
23
|
+
is detected (`EffectUnknown`) and handed to a decision hook.
|
|
24
|
+
|
|
25
|
+
Everything publishes events (``agent.run.*``, ``tool.*``) through `python_wrap.events`.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import asyncio
|
|
31
|
+
import contextlib
|
|
32
|
+
import contextvars
|
|
33
|
+
import dataclasses
|
|
34
|
+
import fnmatch
|
|
35
|
+
import functools
|
|
36
|
+
import hashlib
|
|
37
|
+
import inspect
|
|
38
|
+
import json
|
|
39
|
+
import math
|
|
40
|
+
import threading
|
|
41
|
+
import uuid
|
|
42
|
+
from collections.abc import Awaitable, Callable, Iterable, Iterator, Mapping
|
|
43
|
+
from contextlib import ExitStack
|
|
44
|
+
from dataclasses import dataclass, field
|
|
45
|
+
from types import MappingProxyType, TracebackType
|
|
46
|
+
from typing import Any, ParamSpec, Protocol, TypeVar, cast, overload
|
|
47
|
+
|
|
48
|
+
from python_wrap import _core
|
|
49
|
+
from python_wrap._runtime import seconds as _parse_seconds
|
|
50
|
+
from python_wrap.errors import PythonWrapError, TimeoutExpired
|
|
51
|
+
from python_wrap.timeouts import CancelToken, _current_token
|
|
52
|
+
|
|
53
|
+
__all__ = [
|
|
54
|
+
"AgentError",
|
|
55
|
+
"AgentRun",
|
|
56
|
+
"ApprovalDenied",
|
|
57
|
+
"ApprovalTimeout",
|
|
58
|
+
"DryRun",
|
|
59
|
+
"EffectConflict",
|
|
60
|
+
"EffectLedger",
|
|
61
|
+
"EffectRecord",
|
|
62
|
+
"EffectResolved",
|
|
63
|
+
"EffectStore",
|
|
64
|
+
"EffectUnknown",
|
|
65
|
+
"LoopDetected",
|
|
66
|
+
"MemoryEffectStore",
|
|
67
|
+
"RedisEffectStore",
|
|
68
|
+
"RunBudgetExceeded",
|
|
69
|
+
"RunCancelled",
|
|
70
|
+
"RunGuard",
|
|
71
|
+
"RunTimeout",
|
|
72
|
+
"SQLiteEffectStore",
|
|
73
|
+
"Step",
|
|
74
|
+
"StepLimitExceeded",
|
|
75
|
+
"ToolCall",
|
|
76
|
+
"ToolNotAllowed",
|
|
77
|
+
"ToolPolicy",
|
|
78
|
+
"ToolRegistry",
|
|
79
|
+
"ToolSpec",
|
|
80
|
+
"agent_run",
|
|
81
|
+
"current_run",
|
|
82
|
+
"record_step",
|
|
83
|
+
"run_id_var",
|
|
84
|
+
"tool",
|
|
85
|
+
"tool_call_id",
|
|
86
|
+
"tool_spec",
|
|
87
|
+
"with_call_id",
|
|
88
|
+
]
|
|
89
|
+
|
|
90
|
+
P = ParamSpec("P")
|
|
91
|
+
R = TypeVar("R")
|
|
92
|
+
|
|
93
|
+
_LAYER_ATTR = "__python_wrap_layer__"
|
|
94
|
+
_SPEC_ATTR = "__python_wrap_tool__"
|
|
95
|
+
_HISTORY_LIMIT = 1000
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# --------------------------------------------------------------------------- errors
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class AgentError(PythonWrapError):
|
|
102
|
+
"""Base class for the errors this module raises.
|
|
103
|
+
|
|
104
|
+
Attributes:
|
|
105
|
+
run_id: The run the error belongs to, or None outside a run.
|
|
106
|
+
"""
|
|
107
|
+
|
|
108
|
+
run_id: str | None = None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class StepLimitExceeded(AgentError):
|
|
112
|
+
"""The run already made ``max_steps`` steps; this one was refused.
|
|
113
|
+
|
|
114
|
+
Attributes:
|
|
115
|
+
limit: The ``max_steps`` that was reached.
|
|
116
|
+
"""
|
|
117
|
+
|
|
118
|
+
def __init__(self, message: str, *, run_id: str, limit: int) -> None:
|
|
119
|
+
super().__init__(message)
|
|
120
|
+
self.run_id = run_id
|
|
121
|
+
self.limit = limit
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class LoopDetected(AgentError):
|
|
125
|
+
"""The same call (same kind, name and arguments) was made too many times in one run.
|
|
126
|
+
|
|
127
|
+
Attributes:
|
|
128
|
+
name: The tool (or step) name that repeats.
|
|
129
|
+
repeats: How many identical calls had already been made.
|
|
130
|
+
"""
|
|
131
|
+
|
|
132
|
+
def __init__(self, message: str, *, run_id: str, name: str, repeats: int) -> None:
|
|
133
|
+
super().__init__(message)
|
|
134
|
+
self.run_id = run_id
|
|
135
|
+
self.name = name
|
|
136
|
+
self.repeats = repeats
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class RunTimeout(AgentError, TimeoutExpired):
|
|
140
|
+
"""The run is older than ``max_seconds``. Also a `TimeoutExpired` (and ``TimeoutError``)."""
|
|
141
|
+
|
|
142
|
+
def __init__(self, message: str, *, run_id: str, seconds: float) -> None:
|
|
143
|
+
super().__init__(message, seconds=seconds)
|
|
144
|
+
self.run_id = run_id
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class RunCancelled(AgentError):
|
|
148
|
+
"""`AgentRun.cancel` was called; no further step is admitted."""
|
|
149
|
+
|
|
150
|
+
def __init__(self, message: str, *, run_id: str) -> None:
|
|
151
|
+
super().__init__(message)
|
|
152
|
+
self.run_id = run_id
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class RunBudgetExceeded(AgentError):
|
|
156
|
+
"""The run's ``budget`` reports ``exhausted``."""
|
|
157
|
+
|
|
158
|
+
def __init__(self, message: str, *, run_id: str) -> None:
|
|
159
|
+
super().__init__(message)
|
|
160
|
+
self.run_id = run_id
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class ToolNotAllowed(AgentError):
|
|
164
|
+
"""A `ToolPolicy` (or a missing tool) refused the call.
|
|
165
|
+
|
|
166
|
+
Attributes:
|
|
167
|
+
tool: The tool name.
|
|
168
|
+
reason: ``"unknown"``, ``"denied"`` (deny glob / not in the allow list),
|
|
169
|
+
``"read_only"`` (a write tool in a run with ``allow_write=False``),
|
|
170
|
+
``"approval_denied"`` or ``"approval_timeout"``.
|
|
171
|
+
"""
|
|
172
|
+
|
|
173
|
+
def __init__(self, message: str, *, tool: str, reason: str, run_id: str | None = None) -> None:
|
|
174
|
+
super().__init__(message)
|
|
175
|
+
self.tool = tool
|
|
176
|
+
self.reason = reason
|
|
177
|
+
self.run_id = run_id
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
class ApprovalDenied(ToolNotAllowed):
|
|
181
|
+
"""The approver said no, raised, returned something other than True, or none is set."""
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
class ApprovalTimeout(ApprovalDenied):
|
|
185
|
+
"""The approver did not answer within ``approval_timeout`` seconds (denied)."""
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
# --------------------------------------------------------------------------- data
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
@dataclass(frozen=True)
|
|
192
|
+
class Step:
|
|
193
|
+
"""One step of an agent run (a tool call, an LLM call, or a custom kind).
|
|
194
|
+
|
|
195
|
+
Attributes:
|
|
196
|
+
index: 1-based position in the run.
|
|
197
|
+
kind: ``"tool"``, ``"llm"`` or any label passed to `record_step`.
|
|
198
|
+
name: Tool or model name.
|
|
199
|
+
signature: A digest of the canonical arguments (None when none were given);
|
|
200
|
+
identical calls share it.
|
|
201
|
+
at: Seconds since the run started.
|
|
202
|
+
"""
|
|
203
|
+
|
|
204
|
+
index: int
|
|
205
|
+
kind: str
|
|
206
|
+
name: str
|
|
207
|
+
signature: str | None
|
|
208
|
+
at: float
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
@dataclass(frozen=True)
|
|
212
|
+
class ToolCall:
|
|
213
|
+
"""What an approver (and `DryRun`) is told about a pending tool call.
|
|
214
|
+
|
|
215
|
+
Attributes:
|
|
216
|
+
tool: The tool name.
|
|
217
|
+
arguments: The bound arguments, defaults applied (read-only mapping).
|
|
218
|
+
run_id: The current run id, or None outside a run.
|
|
219
|
+
read_only: Whether the tool declared itself read-only.
|
|
220
|
+
description: The tool's description (first docstring line by default).
|
|
221
|
+
"""
|
|
222
|
+
|
|
223
|
+
tool: str
|
|
224
|
+
arguments: Mapping[str, Any]
|
|
225
|
+
run_id: str | None
|
|
226
|
+
read_only: bool
|
|
227
|
+
description: str = ""
|
|
228
|
+
call_id: str | None = None
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
@dataclass(frozen=True)
|
|
232
|
+
class DryRun:
|
|
233
|
+
"""Returned instead of running a write tool in a dry run without a ``dry_result``.
|
|
234
|
+
|
|
235
|
+
Attributes:
|
|
236
|
+
tool: The tool that would have run.
|
|
237
|
+
arguments: The arguments it would have received.
|
|
238
|
+
"""
|
|
239
|
+
|
|
240
|
+
tool: str
|
|
241
|
+
arguments: Mapping[str, Any]
|
|
242
|
+
|
|
243
|
+
def __bool__(self) -> bool:
|
|
244
|
+
return False
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
@dataclass(frozen=True)
|
|
248
|
+
class ToolSpec:
|
|
249
|
+
"""What `tool` recorded about a function; returned by `tool_spec`.
|
|
250
|
+
|
|
251
|
+
Attributes:
|
|
252
|
+
name: The tool name the model uses.
|
|
253
|
+
description: First docstring line unless given.
|
|
254
|
+
read_only: True for tools without side effects.
|
|
255
|
+
idempotent: True when replays are deduplicated with an idempotency key.
|
|
256
|
+
requires_approval: True when every call needs the approver's yes.
|
|
257
|
+
timeout: Per-call time limit in seconds, or None.
|
|
258
|
+
retried: True when the tool was given ``retry=``.
|
|
259
|
+
is_async: True for ``async def`` tools.
|
|
260
|
+
"""
|
|
261
|
+
|
|
262
|
+
name: str
|
|
263
|
+
description: str
|
|
264
|
+
read_only: bool
|
|
265
|
+
idempotent: bool
|
|
266
|
+
requires_approval: bool
|
|
267
|
+
timeout: float | None
|
|
268
|
+
retried: bool
|
|
269
|
+
is_async: bool
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
Approver = Callable[[ToolCall], "bool | Awaitable[bool]"]
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _globs(value: Iterable[str] | str | None) -> tuple[str, ...] | None:
|
|
276
|
+
if value is None:
|
|
277
|
+
return None
|
|
278
|
+
if isinstance(value, str):
|
|
279
|
+
return (value,)
|
|
280
|
+
return tuple(value)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
@dataclass(frozen=True)
|
|
284
|
+
class ToolPolicy:
|
|
285
|
+
"""Which tools a run may call, and how.
|
|
286
|
+
|
|
287
|
+
Policies are attached to a run (``agent_run(policy=...)``) or a `ToolRegistry`. Every
|
|
288
|
+
policy in effect must agree: nested runs and the registry combine, and the strictest
|
|
289
|
+
answer wins (any deny, any ``allow_write=False``, any ``dry_run=True``).
|
|
290
|
+
|
|
291
|
+
Args:
|
|
292
|
+
allow: Glob patterns (``fnmatch``, case-sensitive) of tool names that may run;
|
|
293
|
+
None allows every name.
|
|
294
|
+
deny: Glob patterns that may never run; deny wins over allow.
|
|
295
|
+
allow_write: False refuses every tool not declared ``read_only=True``
|
|
296
|
+
(`ToolNotAllowed` with reason ``"read_only"``).
|
|
297
|
+
dry_run: True returns each write tool's ``dry_result`` (or a `DryRun` marker)
|
|
298
|
+
instead of running it. Read-only tools still run, so the agent can plan with
|
|
299
|
+
real data.
|
|
300
|
+
approver: Called with a `ToolCall` for tools with ``requires_approval=True``;
|
|
301
|
+
sync or async, it must return exactly True to approve.
|
|
302
|
+
approval_timeout: Seconds to wait for the approver before denying.
|
|
303
|
+
|
|
304
|
+
Example:
|
|
305
|
+
>>> policy = ToolPolicy(deny=["delete_*"], allow_write=False)
|
|
306
|
+
>>> policy.permits("search_docs"), policy.permits("delete_user")
|
|
307
|
+
(True, False)
|
|
308
|
+
"""
|
|
309
|
+
|
|
310
|
+
allow: tuple[str, ...] | None = None
|
|
311
|
+
deny: tuple[str, ...] = ()
|
|
312
|
+
allow_write: bool = True
|
|
313
|
+
dry_run: bool = False
|
|
314
|
+
approver: Approver | None = None
|
|
315
|
+
approval_timeout: float = 60.0
|
|
316
|
+
|
|
317
|
+
def __post_init__(self) -> None:
|
|
318
|
+
object.__setattr__(self, "allow", _globs(self.allow))
|
|
319
|
+
object.__setattr__(self, "deny", _globs(self.deny) or ())
|
|
320
|
+
object.__setattr__(self, "approval_timeout", _parse_seconds(self.approval_timeout))
|
|
321
|
+
if self.approver is not None and not callable(self.approver):
|
|
322
|
+
raise TypeError("approver must be callable")
|
|
323
|
+
|
|
324
|
+
def permits(self, name: str) -> bool:
|
|
325
|
+
"""True if ``name`` passes the allow and deny globs."""
|
|
326
|
+
if any(fnmatch.fnmatchcase(name, pattern) for pattern in self.deny):
|
|
327
|
+
return False
|
|
328
|
+
return self.allow is None or any(
|
|
329
|
+
fnmatch.fnmatchcase(name, pattern) for pattern in self.allow
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
# --------------------------------------------------------------------------- runs
|
|
334
|
+
|
|
335
|
+
#: The id of the innermost agent run in this context, or None. Tracing integrations can
|
|
336
|
+
#: read it without importing anything else from this module.
|
|
337
|
+
run_id_var: contextvars.ContextVar[str | None] = contextvars.ContextVar(
|
|
338
|
+
"python_wrap_agent_run_id", default=None
|
|
339
|
+
)
|
|
340
|
+
_run_var: contextvars.ContextVar[AgentRun | None] = contextvars.ContextVar(
|
|
341
|
+
"python_wrap_agent_run", default=None
|
|
342
|
+
)
|
|
343
|
+
# A registry's policy, in effect while `ToolRegistry.call` runs a tool.
|
|
344
|
+
_registry_policy: contextvars.ContextVar[ToolPolicy | None] = contextvars.ContextVar(
|
|
345
|
+
"python_wrap_agent_registry_policy", default=None
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def canonical(arguments: Mapping[str, Any] | None) -> str | None:
|
|
350
|
+
"""A stable digest of call arguments: equal arguments give equal digests.
|
|
351
|
+
|
|
352
|
+
Keys are sorted and values serialised as JSON (sets sorted, unknown objects by
|
|
353
|
+
``repr``), so ``f(a=1, b=2)`` and ``f(b=2, a=1)`` match.
|
|
354
|
+
"""
|
|
355
|
+
if arguments is None:
|
|
356
|
+
return None
|
|
357
|
+
|
|
358
|
+
def fallback(obj: Any) -> Any:
|
|
359
|
+
if isinstance(obj, (set, frozenset)):
|
|
360
|
+
return sorted(obj, key=repr)
|
|
361
|
+
if isinstance(obj, (bytes, bytearray)):
|
|
362
|
+
return obj.hex()
|
|
363
|
+
return repr(obj)
|
|
364
|
+
|
|
365
|
+
try:
|
|
366
|
+
text = json.dumps(
|
|
367
|
+
dict(arguments),
|
|
368
|
+
sort_keys=True,
|
|
369
|
+
default=fallback,
|
|
370
|
+
separators=(",", ":"),
|
|
371
|
+
ensure_ascii=False,
|
|
372
|
+
)
|
|
373
|
+
except (TypeError, ValueError):
|
|
374
|
+
text = repr(sorted((repr(k), repr(v)) for k, v in arguments.items()))
|
|
375
|
+
return hashlib.sha256(text.encode()).hexdigest()[:32]
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _positive_int(name: str, value: int | None) -> int | None:
|
|
379
|
+
if value is None:
|
|
380
|
+
return None
|
|
381
|
+
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
|
|
382
|
+
raise ValueError(f"{name} must be a positive integer or None")
|
|
383
|
+
return value
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
class AgentRun:
|
|
387
|
+
"""The live state of one agent run; get it from `current_run` or ``with guard as run``.
|
|
388
|
+
|
|
389
|
+
Thread-safe: parallel tool calls (threads or tasks started inside the run) share it.
|
|
390
|
+
|
|
391
|
+
Attributes:
|
|
392
|
+
run_id: This run's id (``uuid4().hex`` unless the guard was given ``run_id=``).
|
|
393
|
+
parent: The enclosing run, or None.
|
|
394
|
+
guard: The `RunGuard` that started it.
|
|
395
|
+
token: The run's `CancelToken`, installed as the current token, so
|
|
396
|
+
`python_wrap.checkpoint` inside the run raises once the run is cancelled or
|
|
397
|
+
its ``max_seconds`` pass.
|
|
398
|
+
"""
|
|
399
|
+
|
|
400
|
+
def __init__(self, guard: RunGuard, run_id: str, parent: AgentRun | None) -> None:
|
|
401
|
+
self.guard = guard
|
|
402
|
+
self.run_id = run_id
|
|
403
|
+
self.parent = parent
|
|
404
|
+
self.token = CancelToken(
|
|
405
|
+
f"agent run {run_id}", guard.max_seconds or 0.0, _current_token.get()
|
|
406
|
+
)
|
|
407
|
+
self._lock = threading.Lock()
|
|
408
|
+
self._steps = 0
|
|
409
|
+
self._history: list[Step] = []
|
|
410
|
+
self._counts: dict[tuple[str, str, str], int] = {}
|
|
411
|
+
self._started = _core.monotonic()
|
|
412
|
+
self._timed_out = False
|
|
413
|
+
self._user_cancelled = False
|
|
414
|
+
self._resets: tuple[Any, ...] = ()
|
|
415
|
+
self._timer: Any = None
|
|
416
|
+
self._scope: Any = None
|
|
417
|
+
|
|
418
|
+
@property
|
|
419
|
+
def steps(self) -> int:
|
|
420
|
+
"""Steps admitted so far (tool calls, LLM calls, custom steps)."""
|
|
421
|
+
with self._lock:
|
|
422
|
+
return self._steps
|
|
423
|
+
|
|
424
|
+
@property
|
|
425
|
+
def history(self) -> tuple[Step, ...]:
|
|
426
|
+
"""The admitted steps, oldest first (the last 1000 are kept)."""
|
|
427
|
+
with self._lock:
|
|
428
|
+
return tuple(self._history)
|
|
429
|
+
|
|
430
|
+
@property
|
|
431
|
+
def elapsed(self) -> float:
|
|
432
|
+
"""Seconds since the run started."""
|
|
433
|
+
return _core.monotonic() - self._started
|
|
434
|
+
|
|
435
|
+
@property
|
|
436
|
+
def remaining(self) -> float | None:
|
|
437
|
+
"""Seconds left before ``max_seconds`` (never negative), or None without a limit."""
|
|
438
|
+
limit = self.guard.max_seconds
|
|
439
|
+
return None if limit is None else max(0.0, limit - self.elapsed)
|
|
440
|
+
|
|
441
|
+
@property
|
|
442
|
+
def cancelled(self) -> bool:
|
|
443
|
+
"""True once the run was cancelled, timed out, or an enclosing token fired."""
|
|
444
|
+
return self.token.cancelled or self._over_time()
|
|
445
|
+
|
|
446
|
+
def cancel(self) -> None:
|
|
447
|
+
"""Stop the run: the next step raises `RunCancelled` and `checkpoint` raises."""
|
|
448
|
+
self._user_cancelled = True
|
|
449
|
+
self.token.cancel()
|
|
450
|
+
|
|
451
|
+
def _expire(self) -> None:
|
|
452
|
+
self._timed_out = True
|
|
453
|
+
self.token.cancel()
|
|
454
|
+
|
|
455
|
+
def _over_time(self) -> bool:
|
|
456
|
+
limit = self.guard.max_seconds
|
|
457
|
+
return limit is not None and self.elapsed >= limit
|
|
458
|
+
|
|
459
|
+
def check(self) -> None:
|
|
460
|
+
"""Raise if this run (or an enclosing one) may not continue; else do nothing.
|
|
461
|
+
|
|
462
|
+
Raises:
|
|
463
|
+
RunTimeout: ``max_seconds`` passed.
|
|
464
|
+
RunCancelled: `cancel` was called.
|
|
465
|
+
RunBudgetExceeded: the budget is exhausted.
|
|
466
|
+
TimeoutExpired: an enclosing `timeout` fired.
|
|
467
|
+
"""
|
|
468
|
+
for run in self._chain():
|
|
469
|
+
run._check_own()
|
|
470
|
+
self.token.raise_if_cancelled()
|
|
471
|
+
|
|
472
|
+
def _check_own(self) -> None:
|
|
473
|
+
if self._timed_out or self._over_time():
|
|
474
|
+
self._expire()
|
|
475
|
+
limit = self.guard.max_seconds or 0.0
|
|
476
|
+
raise RunTimeout(
|
|
477
|
+
f"agent run {self.run_id} exceeded max_seconds={limit:g}",
|
|
478
|
+
run_id=self.run_id,
|
|
479
|
+
seconds=limit,
|
|
480
|
+
)
|
|
481
|
+
if self._user_cancelled:
|
|
482
|
+
raise RunCancelled(f"agent run {self.run_id} was cancelled", run_id=self.run_id)
|
|
483
|
+
budget = self.guard.budget
|
|
484
|
+
if _is_llm_budget(budget):
|
|
485
|
+
if self._scope is not None:
|
|
486
|
+
over = budget._over(self._scope.spent)
|
|
487
|
+
else:
|
|
488
|
+
over = budget.per == "total" and budget.exhausted()
|
|
489
|
+
if over:
|
|
490
|
+
raise RunBudgetExceeded(
|
|
491
|
+
f"agent run {self.run_id}: budget {budget.name!r} exhausted",
|
|
492
|
+
run_id=self.run_id,
|
|
493
|
+
)
|
|
494
|
+
elif budget is not None:
|
|
495
|
+
checker = getattr(budget, "check", None)
|
|
496
|
+
if callable(checker):
|
|
497
|
+
checker()
|
|
498
|
+
if getattr(budget, "exhausted", False) is True:
|
|
499
|
+
raise RunBudgetExceeded(
|
|
500
|
+
f"agent run {self.run_id}: budget exhausted", run_id=self.run_id
|
|
501
|
+
)
|
|
502
|
+
|
|
503
|
+
def _chain(self) -> list[AgentRun]:
|
|
504
|
+
"""This run and its ancestors, outermost first."""
|
|
505
|
+
chain: list[AgentRun] = []
|
|
506
|
+
run: AgentRun | None = self
|
|
507
|
+
while run is not None:
|
|
508
|
+
chain.append(run)
|
|
509
|
+
run = run.parent
|
|
510
|
+
chain.reverse()
|
|
511
|
+
return chain
|
|
512
|
+
|
|
513
|
+
def step(self, kind: str, name: str, arguments: Mapping[str, Any] | None = None) -> Step:
|
|
514
|
+
"""Admit and record one step; see `record_step`."""
|
|
515
|
+
return self._record(kind, name, canonical(arguments))
|
|
516
|
+
|
|
517
|
+
def _record(self, kind: str, name: str, signature: str | None) -> Step:
|
|
518
|
+
chain = self._chain()
|
|
519
|
+
self.check()
|
|
520
|
+
key = (kind, name, signature) if signature is not None else None
|
|
521
|
+
with ExitStack() as stack:
|
|
522
|
+
for run in chain:
|
|
523
|
+
stack.enter_context(run._lock)
|
|
524
|
+
for run in chain:
|
|
525
|
+
limit, repeats = run.guard.max_steps, run.guard.max_repeats
|
|
526
|
+
if limit is not None and run._steps >= limit:
|
|
527
|
+
raise StepLimitExceeded(
|
|
528
|
+
f"agent run {run.run_id} reached max_steps={limit}; "
|
|
529
|
+
f"refused {kind} step {name!r}",
|
|
530
|
+
run_id=run.run_id,
|
|
531
|
+
limit=limit,
|
|
532
|
+
)
|
|
533
|
+
if key is not None and repeats is not None:
|
|
534
|
+
seen = run._counts.get(key, 0)
|
|
535
|
+
if seen >= repeats:
|
|
536
|
+
raise LoopDetected(
|
|
537
|
+
f"agent run {run.run_id}: {kind} {name!r} was already called "
|
|
538
|
+
f"{seen} time(s) with the same arguments (max_repeats={repeats})",
|
|
539
|
+
run_id=run.run_id,
|
|
540
|
+
name=name,
|
|
541
|
+
repeats=seen,
|
|
542
|
+
)
|
|
543
|
+
mine: Step | None = None
|
|
544
|
+
for run in chain:
|
|
545
|
+
run._steps += 1
|
|
546
|
+
if key is not None:
|
|
547
|
+
run._counts[key] = run._counts.get(key, 0) + 1
|
|
548
|
+
entry = Step(run._steps, kind, name, signature, run.elapsed)
|
|
549
|
+
run._history.append(entry)
|
|
550
|
+
if len(run._history) > _HISTORY_LIMIT:
|
|
551
|
+
del run._history[0]
|
|
552
|
+
mine = entry
|
|
553
|
+
assert mine is not None
|
|
554
|
+
_core.emit(
|
|
555
|
+
"agent.run.step",
|
|
556
|
+
self.guard.name,
|
|
557
|
+
run_id=self.run_id,
|
|
558
|
+
step=mine.index,
|
|
559
|
+
kind=kind,
|
|
560
|
+
tool=name,
|
|
561
|
+
)
|
|
562
|
+
return mine
|
|
563
|
+
|
|
564
|
+
def __repr__(self) -> str:
|
|
565
|
+
return f"AgentRun(run_id={self.run_id!r}, steps={self.steps})"
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def current_run() -> AgentRun | None:
|
|
569
|
+
"""The innermost `AgentRun` active in this context, or None.
|
|
570
|
+
|
|
571
|
+
Example:
|
|
572
|
+
>>> with agent_run(max_steps=5, run_id="demo") as run:
|
|
573
|
+
... current_run() is run, current_run().run_id
|
|
574
|
+
(True, 'demo')
|
|
575
|
+
>>> current_run() is None
|
|
576
|
+
True
|
|
577
|
+
"""
|
|
578
|
+
return _run_var.get()
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def record_step(kind: str, name: str, arguments: Mapping[str, Any] | None = None) -> Step | None:
|
|
582
|
+
"""Count one step (an LLM call, say) against the current run's limits.
|
|
583
|
+
|
|
584
|
+
`tool` records tool calls itself; call this for the other steps of the loop.
|
|
585
|
+
Outside a run it does nothing and returns None.
|
|
586
|
+
|
|
587
|
+
Args:
|
|
588
|
+
kind: ``"llm"`` or any label.
|
|
589
|
+
name: Model or step name.
|
|
590
|
+
arguments: When given, identical calls count towards ``max_repeats``.
|
|
591
|
+
|
|
592
|
+
Returns:
|
|
593
|
+
The recorded `Step`, or None outside a run.
|
|
594
|
+
|
|
595
|
+
Raises:
|
|
596
|
+
StepLimitExceeded, LoopDetected, RunTimeout, RunCancelled, RunBudgetExceeded: The
|
|
597
|
+
step is refused (it is not recorded).
|
|
598
|
+
"""
|
|
599
|
+
run = _run_var.get()
|
|
600
|
+
return None if run is None else run.step(kind, name, arguments)
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def _is_llm_budget(budget: Any) -> bool:
|
|
604
|
+
from python_wrap.llm import Budget
|
|
605
|
+
|
|
606
|
+
return isinstance(budget, Budget)
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
class RunGuard:
|
|
610
|
+
"""Limits for an agent run; enter it (``with`` / ``async with``) or decorate a loop.
|
|
611
|
+
|
|
612
|
+
Each entry starts a new `AgentRun`, so one guard can be reused. Runs nest: steps of an
|
|
613
|
+
inner run count against the enclosing run's limits too, so a sub-agent cannot get
|
|
614
|
+
around them. The run id is published through `current_run` and `run_id_var`, and
|
|
615
|
+
the run's `CancelToken` becomes the current token, so `python_wrap.checkpoint` stops
|
|
616
|
+
tool code once ``max_seconds`` pass or the run is cancelled.
|
|
617
|
+
|
|
618
|
+
Args:
|
|
619
|
+
max_steps: Most steps (tool + LLM + custom) per run; the next raises
|
|
620
|
+
`StepLimitExceeded`.
|
|
621
|
+
max_seconds: Wall-time limit (seconds or ``"5m"``); the next step raises
|
|
622
|
+
`RunTimeout` and the token is cancelled when it passes.
|
|
623
|
+
max_repeats: Most identical calls (same kind, name and arguments) per run; the
|
|
624
|
+
next raises `LoopDetected`.
|
|
625
|
+
budget: Optional spend tracker checked before every step: its ``check()`` is
|
|
626
|
+
called when it has one (it may raise), and ``exhausted`` being True raises
|
|
627
|
+
`RunBudgetExceeded`.
|
|
628
|
+
policy: A `ToolPolicy` in effect for the run.
|
|
629
|
+
run_id: Fixed run id (resume a run so its tool replays are deduplicated);
|
|
630
|
+
a fresh ``uuid4().hex`` per run by default.
|
|
631
|
+
name: Reported as ``Event.function`` of the ``agent.run.*`` events.
|
|
632
|
+
|
|
633
|
+
Example:
|
|
634
|
+
>>> guard = RunGuard(max_steps=2)
|
|
635
|
+
>>> with guard as run:
|
|
636
|
+
... _ = record_step("llm", "model")
|
|
637
|
+
... _ = record_step("llm", "model")
|
|
638
|
+
... try:
|
|
639
|
+
... record_step("llm", "model")
|
|
640
|
+
... except StepLimitExceeded:
|
|
641
|
+
... print("stopped after", run.steps)
|
|
642
|
+
stopped after 2
|
|
643
|
+
"""
|
|
644
|
+
|
|
645
|
+
def __init__(
|
|
646
|
+
self,
|
|
647
|
+
*,
|
|
648
|
+
max_steps: int | None = None,
|
|
649
|
+
max_seconds: float | str | None = None,
|
|
650
|
+
max_repeats: int | None = None,
|
|
651
|
+
budget: Any = None,
|
|
652
|
+
policy: ToolPolicy | None = None,
|
|
653
|
+
run_id: str | None = None,
|
|
654
|
+
name: str = "agent_run",
|
|
655
|
+
) -> None:
|
|
656
|
+
self.max_steps = _positive_int("max_steps", max_steps)
|
|
657
|
+
self.max_repeats = _positive_int("max_repeats", max_repeats)
|
|
658
|
+
self.max_seconds = None if max_seconds is None else _parse_seconds(max_seconds)
|
|
659
|
+
if policy is not None and not isinstance(policy, ToolPolicy):
|
|
660
|
+
raise TypeError("policy must be a ToolPolicy")
|
|
661
|
+
if run_id is not None and (not isinstance(run_id, str) or not run_id):
|
|
662
|
+
raise ValueError("run_id must be a non-empty string")
|
|
663
|
+
self.budget = budget
|
|
664
|
+
self.policy = policy
|
|
665
|
+
self.run_id = run_id
|
|
666
|
+
self.name = name
|
|
667
|
+
|
|
668
|
+
@property
|
|
669
|
+
def limited(self) -> bool:
|
|
670
|
+
"""True if at least one of max_steps, max_seconds, max_repeats is set."""
|
|
671
|
+
return any(v is not None for v in (self.max_steps, self.max_seconds, self.max_repeats))
|
|
672
|
+
|
|
673
|
+
def settings(self) -> dict[str, Any]:
|
|
674
|
+
"""The limits, as `python_wrap.doctor` reports them."""
|
|
675
|
+
return {
|
|
676
|
+
"max_steps": self.max_steps,
|
|
677
|
+
"max_seconds": self.max_seconds,
|
|
678
|
+
"max_repeats": self.max_repeats,
|
|
679
|
+
"budget": self.budget is not None,
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
def _open(self) -> AgentRun:
|
|
683
|
+
parent = _run_var.get()
|
|
684
|
+
run = AgentRun(self, self.run_id or uuid.uuid4().hex, parent)
|
|
685
|
+
run._resets = (
|
|
686
|
+
_run_var.set(run),
|
|
687
|
+
run_id_var.set(run.run_id),
|
|
688
|
+
_current_token.set(run.token),
|
|
689
|
+
)
|
|
690
|
+
if _is_llm_budget(self.budget) and self.budget.per in ("run", "chain"):
|
|
691
|
+
run._scope = self.budget.run()
|
|
692
|
+
run._scope.__enter__()
|
|
693
|
+
_core.emit(
|
|
694
|
+
"agent.run.start",
|
|
695
|
+
self.name,
|
|
696
|
+
run_id=run.run_id,
|
|
697
|
+
parent_id=None if parent is None else parent.run_id,
|
|
698
|
+
)
|
|
699
|
+
return run
|
|
700
|
+
|
|
701
|
+
def _close(self, exc: BaseException | None) -> None:
|
|
702
|
+
run = _run_var.get()
|
|
703
|
+
if run is None or run.guard is not self:
|
|
704
|
+
raise RuntimeError("RunGuard exited out of order")
|
|
705
|
+
timer, run._timer = run._timer, None
|
|
706
|
+
if timer is not None:
|
|
707
|
+
timer.cancel()
|
|
708
|
+
scope, run._scope = run._scope, None
|
|
709
|
+
if scope is not None:
|
|
710
|
+
scope.__exit__(None, None, None)
|
|
711
|
+
run_token, id_token, cancel_token = run._resets
|
|
712
|
+
_current_token.reset(cancel_token)
|
|
713
|
+
run_id_var.reset(id_token)
|
|
714
|
+
_run_var.reset(run_token)
|
|
715
|
+
_core.emit(
|
|
716
|
+
"agent.run.end",
|
|
717
|
+
self.name,
|
|
718
|
+
run_id=run.run_id,
|
|
719
|
+
steps=run._steps,
|
|
720
|
+
seconds=run.elapsed,
|
|
721
|
+
error=None if exc is None else type(exc).__name__,
|
|
722
|
+
)
|
|
723
|
+
|
|
724
|
+
def __enter__(self) -> AgentRun:
|
|
725
|
+
run = self._open()
|
|
726
|
+
if self.max_seconds is not None:
|
|
727
|
+
timer = threading.Timer(self.max_seconds, run._expire)
|
|
728
|
+
timer.daemon = True
|
|
729
|
+
timer.start()
|
|
730
|
+
run._timer = timer
|
|
731
|
+
return run
|
|
732
|
+
|
|
733
|
+
def __exit__(
|
|
734
|
+
self,
|
|
735
|
+
typ: type[BaseException] | None,
|
|
736
|
+
exc: BaseException | None,
|
|
737
|
+
tb: TracebackType | None,
|
|
738
|
+
) -> None:
|
|
739
|
+
self._close(exc)
|
|
740
|
+
|
|
741
|
+
async def __aenter__(self) -> AgentRun:
|
|
742
|
+
run = self._open()
|
|
743
|
+
if self.max_seconds is not None:
|
|
744
|
+
run._timer = asyncio.get_running_loop().call_later(self.max_seconds, run._expire)
|
|
745
|
+
return run
|
|
746
|
+
|
|
747
|
+
async def __aexit__(
|
|
748
|
+
self,
|
|
749
|
+
typ: type[BaseException] | None,
|
|
750
|
+
exc: BaseException | None,
|
|
751
|
+
tb: TracebackType | None,
|
|
752
|
+
) -> None:
|
|
753
|
+
self._close(exc)
|
|
754
|
+
|
|
755
|
+
def __call__(self, func: Callable[P, R]) -> Callable[P, R]:
|
|
756
|
+
"""Run every call of ``func`` (sync or async) inside a fresh run of this guard."""
|
|
757
|
+
if _core.is_async(func):
|
|
758
|
+
|
|
759
|
+
@functools.wraps(func)
|
|
760
|
+
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
761
|
+
async with self:
|
|
762
|
+
return await cast(Callable[..., Awaitable[Any]], func)(*args, **kwargs)
|
|
763
|
+
|
|
764
|
+
setattr(async_wrapper, _LAYER_ATTR, ("agent_run", self.settings()))
|
|
765
|
+
return cast(Callable[P, R], async_wrapper)
|
|
766
|
+
|
|
767
|
+
@functools.wraps(func)
|
|
768
|
+
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
|
|
769
|
+
with self:
|
|
770
|
+
return func(*args, **kwargs)
|
|
771
|
+
|
|
772
|
+
setattr(wrapper, _LAYER_ATTR, ("agent_run", self.settings()))
|
|
773
|
+
return wrapper
|
|
774
|
+
|
|
775
|
+
def _with_policy(self, policy: ToolPolicy | None) -> RunGuard:
|
|
776
|
+
clone = RunGuard(
|
|
777
|
+
max_steps=self.max_steps,
|
|
778
|
+
max_seconds=self.max_seconds,
|
|
779
|
+
max_repeats=self.max_repeats,
|
|
780
|
+
budget=self.budget,
|
|
781
|
+
policy=self.policy,
|
|
782
|
+
run_id=self.run_id,
|
|
783
|
+
name=self.name,
|
|
784
|
+
)
|
|
785
|
+
clone._extra_policy = policy
|
|
786
|
+
return clone
|
|
787
|
+
|
|
788
|
+
_extra_policy: ToolPolicy | None = None
|
|
789
|
+
|
|
790
|
+
def _explain(self, *, idempotent: bool = True, multiprocess: bool = False) -> Any:
|
|
791
|
+
from python_wrap.doctor import Layer, Report, _check
|
|
792
|
+
|
|
793
|
+
layers = (Layer("agent_run", self.settings()),)
|
|
794
|
+
return Report(self.name, layers, _check(layers, idempotent, multiprocess))
|
|
795
|
+
|
|
796
|
+
def __repr__(self) -> str:
|
|
797
|
+
shown = ", ".join(f"{k}={v!r}" for k, v in self.settings().items() if v)
|
|
798
|
+
return f"RunGuard({shown})"
|
|
799
|
+
|
|
800
|
+
|
|
801
|
+
def agent_run(
|
|
802
|
+
*,
|
|
803
|
+
max_steps: int | None = None,
|
|
804
|
+
max_seconds: float | str | None = None,
|
|
805
|
+
max_repeats: int | None = None,
|
|
806
|
+
budget: Any = None,
|
|
807
|
+
policy: ToolPolicy | None = None,
|
|
808
|
+
run_id: str | None = None,
|
|
809
|
+
name: str = "agent_run",
|
|
810
|
+
) -> RunGuard:
|
|
811
|
+
"""Shorthand for `RunGuard`: ``with agent_run(max_steps=20) as run: ...``.
|
|
812
|
+
|
|
813
|
+
Example:
|
|
814
|
+
```python
|
|
815
|
+
from python_wrap.agents import agent_run, tool, LoopDetected
|
|
816
|
+
|
|
817
|
+
@tool(read_only=True)
|
|
818
|
+
def search(query: str) -> list[str]:
|
|
819
|
+
return [query.upper()]
|
|
820
|
+
|
|
821
|
+
with agent_run(max_steps=10, max_repeats=2) as run:
|
|
822
|
+
search("python")
|
|
823
|
+
search("python")
|
|
824
|
+
try:
|
|
825
|
+
search("python")
|
|
826
|
+
except LoopDetected:
|
|
827
|
+
pass
|
|
828
|
+
assert run.steps == 2
|
|
829
|
+
```
|
|
830
|
+
"""
|
|
831
|
+
return RunGuard(
|
|
832
|
+
max_steps=max_steps,
|
|
833
|
+
max_seconds=max_seconds,
|
|
834
|
+
max_repeats=max_repeats,
|
|
835
|
+
budget=budget,
|
|
836
|
+
policy=policy,
|
|
837
|
+
run_id=run_id,
|
|
838
|
+
name=name,
|
|
839
|
+
)
|
|
840
|
+
|
|
841
|
+
|
|
842
|
+
# --------------------------------------------------------------------------- effect ledger
|
|
843
|
+
|
|
844
|
+
#: The provider's id for the tool call being executed (OpenAI ``tool_call.id``, Anthropic
|
|
845
|
+
#: ``tool_use.id``, pydantic-ai ``tool_call_id``), or None. Adapters set it with
|
|
846
|
+
#: `with_call_id`; an `EffectLedger` keys side effects on it.
|
|
847
|
+
tool_call_id: contextvars.ContextVar[str | None] = contextvars.ContextVar(
|
|
848
|
+
"python_wrap_tool_call_id", default=None
|
|
849
|
+
)
|
|
850
|
+
|
|
851
|
+
|
|
852
|
+
@contextlib.contextmanager
|
|
853
|
+
def with_call_id(call_id: str | None) -> Iterator[str | None]:
|
|
854
|
+
"""Make ``call_id`` the current `tool_call_id` for a ``with`` block.
|
|
855
|
+
|
|
856
|
+
Framework adapters do this for you; call it yourself when you dispatch the model's
|
|
857
|
+
tool calls by hand (``with with_call_id(block.id): tools.call(...)``).
|
|
858
|
+
|
|
859
|
+
Example:
|
|
860
|
+
>>> with with_call_id("call_1"):
|
|
861
|
+
... tool_call_id.get()
|
|
862
|
+
'call_1'
|
|
863
|
+
>>> tool_call_id.get() is None
|
|
864
|
+
True
|
|
865
|
+
"""
|
|
866
|
+
if call_id is not None and (not isinstance(call_id, str) or not call_id):
|
|
867
|
+
raise ValueError("call_id must be a non-empty string or None")
|
|
868
|
+
reset = tool_call_id.set(call_id)
|
|
869
|
+
try:
|
|
870
|
+
yield call_id
|
|
871
|
+
finally:
|
|
872
|
+
tool_call_id.reset(reset)
|
|
873
|
+
|
|
874
|
+
|
|
875
|
+
@dataclass(frozen=True)
|
|
876
|
+
class EffectRecord:
|
|
877
|
+
"""What an `EffectLedger` knows about one side effect.
|
|
878
|
+
|
|
879
|
+
Attributes:
|
|
880
|
+
key: The ledger key (tool name plus call id, business key or argument digest).
|
|
881
|
+
tool: The tool name.
|
|
882
|
+
state: ``"started"`` (claimed, no outcome recorded yet), ``"succeeded"`` or
|
|
883
|
+
``"failed"``.
|
|
884
|
+
owner: A unique id of the attempt that holds (or held) the record.
|
|
885
|
+
call_id: The provider's tool-call id, when one was current.
|
|
886
|
+
arguments: Digest of the canonical arguments.
|
|
887
|
+
run_id: The agent run the call belonged to.
|
|
888
|
+
started_at: Wall-clock time the attempt was claimed.
|
|
889
|
+
lease_until: Wall-clock time after which a ``"started"`` record whose owner never
|
|
890
|
+
reported back is treated as crashed.
|
|
891
|
+
finished_at: Wall-clock time the outcome was recorded, or None.
|
|
892
|
+
result: The stored result of a succeeded call (when ``has_result``).
|
|
893
|
+
has_result: False when the result could not be stored (not serialisable).
|
|
894
|
+
error: ``{"type": ..., "message": ...}`` of a failed call.
|
|
895
|
+
uncertain: True for a failure that may have left the effect half done (a timeout,
|
|
896
|
+
a cancellation): such a record is handled like a crash.
|
|
897
|
+
attempts: How many attempts claimed this key.
|
|
898
|
+
"""
|
|
899
|
+
|
|
900
|
+
key: str
|
|
901
|
+
tool: str
|
|
902
|
+
state: str
|
|
903
|
+
owner: str
|
|
904
|
+
call_id: str | None = None
|
|
905
|
+
arguments: str | None = None
|
|
906
|
+
run_id: str | None = None
|
|
907
|
+
started_at: float = 0.0
|
|
908
|
+
lease_until: float = 0.0
|
|
909
|
+
finished_at: float | None = None
|
|
910
|
+
result: Any = None
|
|
911
|
+
has_result: bool = False
|
|
912
|
+
error: dict[str, str] | None = None
|
|
913
|
+
uncertain: bool = False
|
|
914
|
+
attempts: int = 1
|
|
915
|
+
|
|
916
|
+
def to_dict(self) -> dict[str, Any]:
|
|
917
|
+
"""A plain dict (JSON-serialisable when the result is)."""
|
|
918
|
+
data = {f: getattr(self, f) for f in _RECORD_FIELDS}
|
|
919
|
+
return data
|
|
920
|
+
|
|
921
|
+
@classmethod
|
|
922
|
+
def from_dict(cls, data: Mapping[str, Any]) -> EffectRecord:
|
|
923
|
+
"""Rebuild a record from `to_dict` output; unknown keys are ignored."""
|
|
924
|
+
return cls(**{k: v for k, v in data.items() if k in _RECORD_FIELDS})
|
|
925
|
+
|
|
926
|
+
|
|
927
|
+
_RECORD_FIELDS = (
|
|
928
|
+
"key", "tool", "state", "owner", "call_id", "arguments", "run_id", "started_at",
|
|
929
|
+
"lease_until", "finished_at", "result", "has_result", "error", "uncertain", "attempts",
|
|
930
|
+
) # fmt: skip
|
|
931
|
+
|
|
932
|
+
|
|
933
|
+
@dataclass(frozen=True)
|
|
934
|
+
class EffectResolved:
|
|
935
|
+
"""Returned by an ``on_unknown`` hook: the effect did happen and this is its result.
|
|
936
|
+
|
|
937
|
+
The ledger records ``value`` as the call's result and returns it, without running
|
|
938
|
+
the tool again.
|
|
939
|
+
"""
|
|
940
|
+
|
|
941
|
+
value: Any = None
|
|
942
|
+
|
|
943
|
+
|
|
944
|
+
class EffectUnknown(AgentError):
|
|
945
|
+
"""A side effect may or may not have happened, and no hook decided what to do.
|
|
946
|
+
|
|
947
|
+
Raised when a previous attempt claimed the key but never recorded an outcome (the
|
|
948
|
+
process crashed, or the ledger store failed between the effect and the record), when
|
|
949
|
+
it failed in a way that may have left the effect half done (a timeout or a
|
|
950
|
+
cancellation), or when it succeeded but its result could not be stored.
|
|
951
|
+
|
|
952
|
+
Attributes:
|
|
953
|
+
record: The ledger's `EffectRecord`.
|
|
954
|
+
reason: ``"crashed"``, ``"uncertain"`` or ``"result_lost"``.
|
|
955
|
+
"""
|
|
956
|
+
|
|
957
|
+
def __init__(self, message: str, *, record: EffectRecord, reason: str) -> None:
|
|
958
|
+
super().__init__(message)
|
|
959
|
+
self.record = record
|
|
960
|
+
self.reason = reason
|
|
961
|
+
self.run_id = record.run_id
|
|
962
|
+
|
|
963
|
+
|
|
964
|
+
class EffectConflict(AgentError):
|
|
965
|
+
"""A tool-call id was reused with different arguments: a bug in the caller.
|
|
966
|
+
|
|
967
|
+
Attributes:
|
|
968
|
+
record: The record stored for the first use of the id.
|
|
969
|
+
"""
|
|
970
|
+
|
|
971
|
+
def __init__(self, message: str, *, record: EffectRecord) -> None:
|
|
972
|
+
super().__init__(message)
|
|
973
|
+
self.record = record
|
|
974
|
+
self.run_id = record.run_id
|
|
975
|
+
|
|
976
|
+
|
|
977
|
+
class EffectStore(Protocol):
|
|
978
|
+
"""Where an `EffectLedger` keeps its records; implement it for another backend.
|
|
979
|
+
|
|
980
|
+
``claim`` and ``settle`` must be atomic with respect to every other process sharing
|
|
981
|
+
the store.
|
|
982
|
+
"""
|
|
983
|
+
|
|
984
|
+
def get(self, key: str, /) -> EffectRecord | None:
|
|
985
|
+
"""The live record for ``key``, or None."""
|
|
986
|
+
|
|
987
|
+
def claim(self, record: EffectRecord, ttl: float, expect: str | None, /) -> EffectRecord | None:
|
|
988
|
+
"""Write ``record`` if no live record exists or the live one's owner is ``expect``.
|
|
989
|
+
|
|
990
|
+
Returns None when written, otherwise the live record that blocked the write.
|
|
991
|
+
"""
|
|
992
|
+
|
|
993
|
+
def settle(self, record: EffectRecord, ttl: float, /) -> bool:
|
|
994
|
+
"""Overwrite the live record only if its owner is ``record.owner``; True if written."""
|
|
995
|
+
|
|
996
|
+
def delete(self, key: str, /) -> bool:
|
|
997
|
+
"""Forget ``key``; True if something was deleted."""
|
|
998
|
+
|
|
999
|
+
|
|
1000
|
+
class MemoryEffectStore:
|
|
1001
|
+
"""An in-process `EffectStore`: thread-safe, bounded, expiring.
|
|
1002
|
+
|
|
1003
|
+
Use it for a single process. Records survive a crash only in a shared store
|
|
1004
|
+
(`SQLiteEffectStore`, `RedisEffectStore`).
|
|
1005
|
+
|
|
1006
|
+
Args:
|
|
1007
|
+
max_entries: Most records kept; when full the record closest to expiry goes first.
|
|
1008
|
+
"""
|
|
1009
|
+
|
|
1010
|
+
def __init__(self, max_entries: int = 10_000) -> None:
|
|
1011
|
+
if isinstance(max_entries, bool) or not isinstance(max_entries, int) or max_entries < 1:
|
|
1012
|
+
raise ValueError("max_entries must be a positive integer")
|
|
1013
|
+
self.max_entries = max_entries
|
|
1014
|
+
self._data: dict[str, tuple[EffectRecord, float]] = {}
|
|
1015
|
+
self._lock = threading.Lock()
|
|
1016
|
+
|
|
1017
|
+
def __len__(self) -> int:
|
|
1018
|
+
with self._lock:
|
|
1019
|
+
return len(self._data)
|
|
1020
|
+
|
|
1021
|
+
def _live(self, key: str) -> EffectRecord | None:
|
|
1022
|
+
entry = self._data.get(key)
|
|
1023
|
+
if entry is None:
|
|
1024
|
+
return None
|
|
1025
|
+
if entry[1] <= _core.wall_time():
|
|
1026
|
+
del self._data[key]
|
|
1027
|
+
return None
|
|
1028
|
+
return entry[0]
|
|
1029
|
+
|
|
1030
|
+
def _put(self, record: EffectRecord, ttl: float) -> None:
|
|
1031
|
+
now = _core.wall_time()
|
|
1032
|
+
self._data.pop(record.key, None)
|
|
1033
|
+
if len(self._data) >= self.max_entries:
|
|
1034
|
+
for old in [k for k, (_, expires) in self._data.items() if expires <= now]:
|
|
1035
|
+
del self._data[old]
|
|
1036
|
+
while len(self._data) >= self.max_entries:
|
|
1037
|
+
del self._data[min(self._data, key=lambda k: self._data[k][1])]
|
|
1038
|
+
self._data[record.key] = (record, now + ttl)
|
|
1039
|
+
|
|
1040
|
+
def get(self, key: str, /) -> EffectRecord | None:
|
|
1041
|
+
with self._lock:
|
|
1042
|
+
return self._live(key)
|
|
1043
|
+
|
|
1044
|
+
def claim(self, record: EffectRecord, ttl: float, expect: str | None, /) -> EffectRecord | None:
|
|
1045
|
+
with self._lock:
|
|
1046
|
+
current = self._live(record.key)
|
|
1047
|
+
if current is not None and current.owner != expect:
|
|
1048
|
+
return current
|
|
1049
|
+
self._put(record, ttl)
|
|
1050
|
+
return None
|
|
1051
|
+
|
|
1052
|
+
def settle(self, record: EffectRecord, ttl: float, /) -> bool:
|
|
1053
|
+
with self._lock:
|
|
1054
|
+
current = self._live(record.key)
|
|
1055
|
+
if current is None or current.owner != record.owner:
|
|
1056
|
+
return False
|
|
1057
|
+
self._put(record, ttl)
|
|
1058
|
+
return True
|
|
1059
|
+
|
|
1060
|
+
def delete(self, key: str, /) -> bool:
|
|
1061
|
+
with self._lock:
|
|
1062
|
+
return self._data.pop(key, None) is not None
|
|
1063
|
+
|
|
1064
|
+
|
|
1065
|
+
def _json_dumps(data: Any) -> bytes:
|
|
1066
|
+
return json.dumps(data, separators=(",", ":"), ensure_ascii=False).encode()
|
|
1067
|
+
|
|
1068
|
+
|
|
1069
|
+
def _json_loads(data: bytes | str) -> Any:
|
|
1070
|
+
return json.loads(data)
|
|
1071
|
+
|
|
1072
|
+
|
|
1073
|
+
class SQLiteEffectStore:
|
|
1074
|
+
"""An `EffectStore` in a local SQLite file, shared by every process that opens it.
|
|
1075
|
+
|
|
1076
|
+
Records survive a crash and a restart, so a replayed run finds them. Results are
|
|
1077
|
+
serialised with ``dumps`` (JSON by default: a result JSON cannot encode is not
|
|
1078
|
+
stored, and replaying it raises `EffectUnknown` with reason ``"result_lost"``
|
|
1079
|
+
unless the ``on_unknown`` hook resolves it).
|
|
1080
|
+
|
|
1081
|
+
Args:
|
|
1082
|
+
path: The database file (created if missing).
|
|
1083
|
+
dumps: Serialiser for a record dict (bytes or str).
|
|
1084
|
+
loads: Matching deserialiser.
|
|
1085
|
+
timeout: Seconds to wait for another process's write lock.
|
|
1086
|
+
"""
|
|
1087
|
+
|
|
1088
|
+
def __init__(
|
|
1089
|
+
self,
|
|
1090
|
+
path: str | Any,
|
|
1091
|
+
*,
|
|
1092
|
+
dumps: Callable[[Any], bytes | str] = _json_dumps,
|
|
1093
|
+
loads: Callable[[Any], Any] = _json_loads,
|
|
1094
|
+
timeout: float = 30.0,
|
|
1095
|
+
) -> None:
|
|
1096
|
+
import os
|
|
1097
|
+
|
|
1098
|
+
self.path = os.fspath(path)
|
|
1099
|
+
self.dumps, self.loads, self.timeout = dumps, loads, timeout
|
|
1100
|
+
self._lock = threading.Lock()
|
|
1101
|
+
self._conn: Any = None
|
|
1102
|
+
self._pid = 0
|
|
1103
|
+
with self._lock:
|
|
1104
|
+
self._connection()
|
|
1105
|
+
|
|
1106
|
+
def _connection(self) -> Any:
|
|
1107
|
+
import os
|
|
1108
|
+
import sqlite3
|
|
1109
|
+
|
|
1110
|
+
if self._conn is None or self._pid != os.getpid():
|
|
1111
|
+
conn = sqlite3.connect(
|
|
1112
|
+
self.path, timeout=self.timeout, check_same_thread=False, isolation_level=None
|
|
1113
|
+
)
|
|
1114
|
+
conn.execute(
|
|
1115
|
+
"CREATE TABLE IF NOT EXISTS python_wrap_effects (key TEXT PRIMARY KEY, "
|
|
1116
|
+
"owner TEXT NOT NULL, expires REAL NOT NULL, data BLOB NOT NULL)"
|
|
1117
|
+
)
|
|
1118
|
+
self._conn, self._pid = conn, os.getpid()
|
|
1119
|
+
return self._conn
|
|
1120
|
+
|
|
1121
|
+
def _decode(self, row: Any) -> EffectRecord | None:
|
|
1122
|
+
if row is None or row[1] <= _core.wall_time():
|
|
1123
|
+
return None
|
|
1124
|
+
return EffectRecord.from_dict(self.loads(row[0]))
|
|
1125
|
+
|
|
1126
|
+
def get(self, key: str, /) -> EffectRecord | None:
|
|
1127
|
+
with self._lock:
|
|
1128
|
+
row = (
|
|
1129
|
+
self._connection()
|
|
1130
|
+
.execute("SELECT data, expires FROM python_wrap_effects WHERE key = ?", (key,))
|
|
1131
|
+
.fetchone()
|
|
1132
|
+
)
|
|
1133
|
+
return self._decode(row)
|
|
1134
|
+
|
|
1135
|
+
def claim(self, record: EffectRecord, ttl: float, expect: str | None, /) -> EffectRecord | None:
|
|
1136
|
+
data = self.dumps(record.to_dict())
|
|
1137
|
+
with self._lock:
|
|
1138
|
+
conn = self._connection()
|
|
1139
|
+
conn.execute("BEGIN IMMEDIATE")
|
|
1140
|
+
try:
|
|
1141
|
+
row = conn.execute(
|
|
1142
|
+
"SELECT data, expires, owner FROM python_wrap_effects WHERE key = ?",
|
|
1143
|
+
(record.key,),
|
|
1144
|
+
).fetchone()
|
|
1145
|
+
current = self._decode(row)
|
|
1146
|
+
if current is not None and row[2] != expect:
|
|
1147
|
+
conn.execute("COMMIT")
|
|
1148
|
+
return current
|
|
1149
|
+
conn.execute(
|
|
1150
|
+
"INSERT OR REPLACE INTO python_wrap_effects (key, owner, expires, data) "
|
|
1151
|
+
"VALUES (?, ?, ?, ?)",
|
|
1152
|
+
(record.key, record.owner, _core.wall_time() + ttl, data),
|
|
1153
|
+
)
|
|
1154
|
+
conn.execute("COMMIT")
|
|
1155
|
+
return None
|
|
1156
|
+
except BaseException:
|
|
1157
|
+
conn.execute("ROLLBACK")
|
|
1158
|
+
raise
|
|
1159
|
+
|
|
1160
|
+
def settle(self, record: EffectRecord, ttl: float, /) -> bool:
|
|
1161
|
+
data = self.dumps(record.to_dict())
|
|
1162
|
+
with self._lock:
|
|
1163
|
+
cursor = self._connection().execute(
|
|
1164
|
+
"UPDATE python_wrap_effects SET data = ?, expires = ? "
|
|
1165
|
+
"WHERE key = ? AND owner = ? AND expires > ?",
|
|
1166
|
+
(data, _core.wall_time() + ttl, record.key, record.owner, _core.wall_time()),
|
|
1167
|
+
)
|
|
1168
|
+
return bool(cursor.rowcount == 1)
|
|
1169
|
+
|
|
1170
|
+
def delete(self, key: str, /) -> bool:
|
|
1171
|
+
with self._lock:
|
|
1172
|
+
cursor = self._connection().execute(
|
|
1173
|
+
"DELETE FROM python_wrap_effects WHERE key = ?", (key,)
|
|
1174
|
+
)
|
|
1175
|
+
return bool(cursor.rowcount == 1)
|
|
1176
|
+
|
|
1177
|
+
def close(self) -> None:
|
|
1178
|
+
"""Close this process's connection (reopened on next use)."""
|
|
1179
|
+
with self._lock:
|
|
1180
|
+
if self._conn is not None:
|
|
1181
|
+
self._conn.close()
|
|
1182
|
+
self._conn = None
|
|
1183
|
+
|
|
1184
|
+
|
|
1185
|
+
_REDIS_CLAIM = """
|
|
1186
|
+
local o=redis.call('HGET',KEYS[1],'owner')
|
|
1187
|
+
if (not o) or (ARGV[1]~='' and o==ARGV[1]) then
|
|
1188
|
+
redis.call('DEL',KEYS[1])
|
|
1189
|
+
redis.call('HSET',KEYS[1],'owner',ARGV[2],'data',ARGV[3])
|
|
1190
|
+
redis.call('PEXPIRE',KEYS[1],ARGV[4])
|
|
1191
|
+
return false
|
|
1192
|
+
end
|
|
1193
|
+
return redis.call('HGET',KEYS[1],'data')
|
|
1194
|
+
"""
|
|
1195
|
+
|
|
1196
|
+
_REDIS_SETTLE = """
|
|
1197
|
+
if redis.call('HGET',KEYS[1],'owner')==ARGV[1] then
|
|
1198
|
+
redis.call('HSET',KEYS[1],'data',ARGV[2])
|
|
1199
|
+
redis.call('PEXPIRE',KEYS[1],ARGV[3])
|
|
1200
|
+
return 1
|
|
1201
|
+
end
|
|
1202
|
+
return 0
|
|
1203
|
+
"""
|
|
1204
|
+
|
|
1205
|
+
|
|
1206
|
+
class RedisEffectStore:
|
|
1207
|
+
"""An `EffectStore` on Redis, shared by every worker; redis is never imported.
|
|
1208
|
+
|
|
1209
|
+
Each record is one hash updated by a Lua script, so a claim and an outcome are
|
|
1210
|
+
atomic and an outcome is only written by the attempt that owns the record (a stale
|
|
1211
|
+
owner whose lease was taken over cannot overwrite the new one).
|
|
1212
|
+
|
|
1213
|
+
Args:
|
|
1214
|
+
client: A synchronous ``redis.Redis``-compatible client (``eval``, ``hget``,
|
|
1215
|
+
``delete``).
|
|
1216
|
+
prefix: Namespace for the keys.
|
|
1217
|
+
dumps: Serialiser for a record dict (JSON by default).
|
|
1218
|
+
loads: Matching deserialiser.
|
|
1219
|
+
"""
|
|
1220
|
+
|
|
1221
|
+
def __init__(
|
|
1222
|
+
self,
|
|
1223
|
+
client: Any,
|
|
1224
|
+
prefix: str = "python-wrap:effects:",
|
|
1225
|
+
*,
|
|
1226
|
+
dumps: Callable[[Any], bytes | str] = _json_dumps,
|
|
1227
|
+
loads: Callable[[Any], Any] = _json_loads,
|
|
1228
|
+
) -> None:
|
|
1229
|
+
if not prefix:
|
|
1230
|
+
raise ValueError("RedisEffectStore needs a nonempty prefix")
|
|
1231
|
+
self.client, self.prefix, self.dumps, self.loads = client, prefix, dumps, loads
|
|
1232
|
+
|
|
1233
|
+
@classmethod
|
|
1234
|
+
def from_store(cls, store: Any) -> RedisEffectStore:
|
|
1235
|
+
"""Reuse a `python_wrap.stores.RedisStore`'s client, prefix and serialisers."""
|
|
1236
|
+
if getattr(store, "fail_open", False):
|
|
1237
|
+
raise ValueError("an effect ledger requires a RedisStore with fail_open=False")
|
|
1238
|
+
return cls(store.client, store.prefix + "effects:", dumps=store.dumps, loads=store.loads)
|
|
1239
|
+
|
|
1240
|
+
def _key(self, key: str) -> str:
|
|
1241
|
+
return self.prefix + key
|
|
1242
|
+
|
|
1243
|
+
def _decode(self, data: Any) -> EffectRecord | None:
|
|
1244
|
+
return None if data is None else EffectRecord.from_dict(self.loads(data))
|
|
1245
|
+
|
|
1246
|
+
def get(self, key: str, /) -> EffectRecord | None:
|
|
1247
|
+
return self._decode(self.client.hget(self._key(key), "data"))
|
|
1248
|
+
|
|
1249
|
+
def claim(self, record: EffectRecord, ttl: float, expect: str | None, /) -> EffectRecord | None:
|
|
1250
|
+
found = self.client.eval(
|
|
1251
|
+
_REDIS_CLAIM,
|
|
1252
|
+
1,
|
|
1253
|
+
self._key(record.key),
|
|
1254
|
+
expect or "",
|
|
1255
|
+
record.owner,
|
|
1256
|
+
self.dumps(record.to_dict()),
|
|
1257
|
+
max(1, math.ceil(ttl * 1000)),
|
|
1258
|
+
)
|
|
1259
|
+
return None if found is None or found is False else self._decode(found)
|
|
1260
|
+
|
|
1261
|
+
def settle(self, record: EffectRecord, ttl: float, /) -> bool:
|
|
1262
|
+
done = self.client.eval(
|
|
1263
|
+
_REDIS_SETTLE,
|
|
1264
|
+
1,
|
|
1265
|
+
self._key(record.key),
|
|
1266
|
+
record.owner,
|
|
1267
|
+
self.dumps(record.to_dict()),
|
|
1268
|
+
max(1, math.ceil(ttl * 1000)),
|
|
1269
|
+
)
|
|
1270
|
+
return bool(int(done or 0))
|
|
1271
|
+
|
|
1272
|
+
def delete(self, key: str, /) -> bool:
|
|
1273
|
+
return bool(self.client.delete(self._key(key)))
|
|
1274
|
+
|
|
1275
|
+
|
|
1276
|
+
def _effect_store(store: Any) -> EffectStore:
|
|
1277
|
+
if store is None:
|
|
1278
|
+
return MemoryEffectStore()
|
|
1279
|
+
if all(callable(getattr(store, name, None)) for name in ("get", "claim", "settle", "delete")):
|
|
1280
|
+
return cast(EffectStore, store)
|
|
1281
|
+
from python_wrap.stores import RedisStore
|
|
1282
|
+
|
|
1283
|
+
if isinstance(store, RedisStore):
|
|
1284
|
+
return RedisEffectStore.from_store(store)
|
|
1285
|
+
if isinstance(store, str) or hasattr(store, "__fspath__"):
|
|
1286
|
+
return SQLiteEffectStore(store)
|
|
1287
|
+
raise TypeError(
|
|
1288
|
+
"store must be an EffectStore, a RedisStore(fail_open=False), a SQLite file path or None"
|
|
1289
|
+
)
|
|
1290
|
+
|
|
1291
|
+
|
|
1292
|
+
UnknownHook = Callable[[EffectUnknown], Any]
|
|
1293
|
+
|
|
1294
|
+
|
|
1295
|
+
class EffectLedger:
|
|
1296
|
+
"""Exactly-once bookkeeping for agent tool side effects, keyed on the tool-call id.
|
|
1297
|
+
|
|
1298
|
+
Every call claims a record (``started``) before the tool runs and records the
|
|
1299
|
+
outcome (``succeeded`` with the result, or ``failed``) after. So:
|
|
1300
|
+
|
|
1301
|
+
* A replay of the same call (the provider's ``call_id`` when one is current, see
|
|
1302
|
+
`with_call_id`; otherwise the tool name, run id and argument digest) returns the
|
|
1303
|
+
stored result without running the tool.
|
|
1304
|
+
* Concurrent identical calls run the tool once; the others wait and get its result.
|
|
1305
|
+
* A ``started`` record nobody finished (the process died between the side effect
|
|
1306
|
+
and the record, or the store failed while recording) is detected once its lease
|
|
1307
|
+
runs out, or at once in the process that saw the store fail. The ``on_unknown``
|
|
1308
|
+
hook then decides: return ``"retry"`` to run again, an `EffectResolved` to record
|
|
1309
|
+
the outcome you looked up yourself, or ``"raise"`` / None to raise `EffectUnknown`.
|
|
1310
|
+
* A failure that may have left the effect half done (``TimeoutError``, cancellation)
|
|
1311
|
+
goes through the same hook; any other failure lets the next call run again.
|
|
1312
|
+
|
|
1313
|
+
Args:
|
|
1314
|
+
store: `MemoryEffectStore` (default), `SQLiteEffectStore`, `RedisEffectStore`, a
|
|
1315
|
+
`python_wrap.stores.RedisStore` with ``fail_open=False``, or a file path
|
|
1316
|
+
(SQLite). Anything implementing `EffectStore` works.
|
|
1317
|
+
ttl: How long records (and replayable results) are kept (``"1d"``).
|
|
1318
|
+
lease: How long a ``started`` record is trusted before it counts as crashed;
|
|
1319
|
+
make it longer than the tool's slowest call (``"5m"``).
|
|
1320
|
+
on_unknown: The decision hook (sync or async), called with the `EffectUnknown`.
|
|
1321
|
+
wait_timeout: Most seconds a duplicate waits for an in-flight call before
|
|
1322
|
+
raising `TimeoutExpired`; None waits until the lease runs out.
|
|
1323
|
+
uncertain: Exception types treated as "the effect may be half done";
|
|
1324
|
+
exceptions that are not ``Exception`` subclasses always are.
|
|
1325
|
+
poll: Seconds between store reads while waiting for another process.
|
|
1326
|
+
|
|
1327
|
+
Example:
|
|
1328
|
+
```python
|
|
1329
|
+
from python_wrap.agents import EffectLedger, agent_run, tool, with_call_id
|
|
1330
|
+
|
|
1331
|
+
ledger = EffectLedger()
|
|
1332
|
+
charges = []
|
|
1333
|
+
|
|
1334
|
+
@tool(ledger=ledger)
|
|
1335
|
+
def charge(order: str, cents: int) -> str:
|
|
1336
|
+
charges.append(order)
|
|
1337
|
+
return f"charged {order}"
|
|
1338
|
+
|
|
1339
|
+
with agent_run():
|
|
1340
|
+
with with_call_id("call_1"):
|
|
1341
|
+
charge("A-1", 500)
|
|
1342
|
+
charge("A-1", 500) # a replay of call_1: stored result
|
|
1343
|
+
with with_call_id("call_2"):
|
|
1344
|
+
charge("A-1", 500) # a new call from the model: runs
|
|
1345
|
+
assert charges == ["A-1", "A-1"]
|
|
1346
|
+
```
|
|
1347
|
+
"""
|
|
1348
|
+
|
|
1349
|
+
def __init__(
|
|
1350
|
+
self,
|
|
1351
|
+
store: Any = None,
|
|
1352
|
+
*,
|
|
1353
|
+
ttl: float | str = "1d",
|
|
1354
|
+
lease: float | str = "5m",
|
|
1355
|
+
on_unknown: UnknownHook | None = None,
|
|
1356
|
+
wait_timeout: float | str | None = None,
|
|
1357
|
+
uncertain: tuple[type[BaseException], ...] = (TimeoutError,),
|
|
1358
|
+
poll: float = 0.05,
|
|
1359
|
+
name: str = "effects",
|
|
1360
|
+
) -> None:
|
|
1361
|
+
self.store = _effect_store(store)
|
|
1362
|
+
self.ttl = _parse_seconds(ttl)
|
|
1363
|
+
self.lease = _parse_seconds(lease)
|
|
1364
|
+
if self.ttl <= 0 or self.lease <= 0:
|
|
1365
|
+
raise ValueError("ttl and lease must be positive")
|
|
1366
|
+
if self.lease > self.ttl:
|
|
1367
|
+
raise ValueError("lease must not be longer than ttl")
|
|
1368
|
+
if on_unknown is not None and not callable(on_unknown):
|
|
1369
|
+
raise TypeError("on_unknown must be callable")
|
|
1370
|
+
self.on_unknown = on_unknown
|
|
1371
|
+
self.wait_timeout = None if wait_timeout is None else _parse_seconds(wait_timeout)
|
|
1372
|
+
self.uncertain = uncertain
|
|
1373
|
+
if poll <= 0:
|
|
1374
|
+
raise ValueError("poll must be positive")
|
|
1375
|
+
self.poll = poll
|
|
1376
|
+
self.name = name
|
|
1377
|
+
self._lock = threading.Lock()
|
|
1378
|
+
self._events: dict[str, threading.Event] = {}
|
|
1379
|
+
self._orphans: set[str] = set()
|
|
1380
|
+
self._local_store = isinstance(self.store, MemoryEffectStore)
|
|
1381
|
+
|
|
1382
|
+
# -- keys -----------------------------------------------------------------
|
|
1383
|
+
def key(
|
|
1384
|
+
self,
|
|
1385
|
+
tool: str,
|
|
1386
|
+
*,
|
|
1387
|
+
call_id: str | None = None,
|
|
1388
|
+
arguments: Mapping[str, Any] | None = None,
|
|
1389
|
+
run_id: str | None = None,
|
|
1390
|
+
business_key: Any = None,
|
|
1391
|
+
) -> str:
|
|
1392
|
+
"""The ledger key for a call: business key, else call id, else run and digest."""
|
|
1393
|
+
return _effect_key(tool, call_id, canonical(arguments), run_id, business_key)
|
|
1394
|
+
|
|
1395
|
+
def lookup(self, key: str) -> EffectRecord | None:
|
|
1396
|
+
"""The live record for ``key`` (see `key`), or None."""
|
|
1397
|
+
return self.store.get(key)
|
|
1398
|
+
|
|
1399
|
+
def forget(self, key: str) -> bool:
|
|
1400
|
+
"""Delete the record for ``key`` so the next call runs again."""
|
|
1401
|
+
with self._lock:
|
|
1402
|
+
self._orphans.discard(key)
|
|
1403
|
+
return self.store.delete(key)
|
|
1404
|
+
|
|
1405
|
+
# -- helpers --------------------------------------------------------------
|
|
1406
|
+
def _new(
|
|
1407
|
+
self, key: str, tool: str, digest: str | None, call_id: str | None, attempts: int
|
|
1408
|
+
) -> EffectRecord:
|
|
1409
|
+
now = _core.wall_time()
|
|
1410
|
+
return EffectRecord(
|
|
1411
|
+
key=key,
|
|
1412
|
+
tool=tool,
|
|
1413
|
+
state="started",
|
|
1414
|
+
owner=uuid.uuid4().hex,
|
|
1415
|
+
call_id=call_id,
|
|
1416
|
+
arguments=digest,
|
|
1417
|
+
run_id=run_id_var.get(),
|
|
1418
|
+
started_at=now,
|
|
1419
|
+
lease_until=now + self.lease,
|
|
1420
|
+
attempts=attempts,
|
|
1421
|
+
)
|
|
1422
|
+
|
|
1423
|
+
def _is_uncertain(self, exc: BaseException) -> bool:
|
|
1424
|
+
if _is_model_retry(exc):
|
|
1425
|
+
return False
|
|
1426
|
+
return not isinstance(exc, Exception) or isinstance(exc, self.uncertain)
|
|
1427
|
+
|
|
1428
|
+
def _verdict(self, current: EffectRecord, digest: str | None) -> tuple[str, str | None]:
|
|
1429
|
+
"""What to do about a live record: (action, unknown_reason)."""
|
|
1430
|
+
if (
|
|
1431
|
+
current.call_id is not None
|
|
1432
|
+
and digest is not None
|
|
1433
|
+
and current.arguments is not None
|
|
1434
|
+
and current.arguments != digest
|
|
1435
|
+
):
|
|
1436
|
+
raise EffectConflict(
|
|
1437
|
+
f"tool call id {current.call_id!r} was reused with different arguments "
|
|
1438
|
+
f"for tool {current.tool!r}",
|
|
1439
|
+
record=current,
|
|
1440
|
+
)
|
|
1441
|
+
if current.state == "succeeded":
|
|
1442
|
+
return ("replay", None) if current.has_result else ("unknown", "result_lost")
|
|
1443
|
+
if current.state == "failed":
|
|
1444
|
+
return ("unknown", "uncertain") if current.uncertain else ("rerun", None)
|
|
1445
|
+
with self._lock:
|
|
1446
|
+
orphan = current.key in self._orphans and current.key not in self._events
|
|
1447
|
+
if orphan or current.lease_until <= _core.wall_time():
|
|
1448
|
+
return "unknown", "crashed"
|
|
1449
|
+
return "wait", None
|
|
1450
|
+
|
|
1451
|
+
def _unknown(self, current: EffectRecord, reason: str) -> EffectUnknown:
|
|
1452
|
+
what = {
|
|
1453
|
+
"crashed": "started but never recorded an outcome (crash or store failure)",
|
|
1454
|
+
"uncertain": "failed in a way that may have left the effect half done",
|
|
1455
|
+
"result_lost": "succeeded but its result could not be stored",
|
|
1456
|
+
}[reason]
|
|
1457
|
+
_core.emit("tool.effect_unknown", current.tool, run_id=current.run_id, reason=reason)
|
|
1458
|
+
return EffectUnknown(
|
|
1459
|
+
f"tool {current.tool!r} ({current.key}): a previous attempt {what}; "
|
|
1460
|
+
"pass EffectLedger(on_unknown=...) to decide",
|
|
1461
|
+
record=current,
|
|
1462
|
+
reason=reason,
|
|
1463
|
+
)
|
|
1464
|
+
|
|
1465
|
+
def _finished(
|
|
1466
|
+
self, owned: EffectRecord, value: Any, exc: BaseException | None
|
|
1467
|
+
) -> list[EffectRecord]:
|
|
1468
|
+
"""Outcome records to try, in order (the second drops an unstorable result)."""
|
|
1469
|
+
now = _core.wall_time()
|
|
1470
|
+
if exc is not None:
|
|
1471
|
+
return [
|
|
1472
|
+
dataclasses.replace(
|
|
1473
|
+
owned,
|
|
1474
|
+
state="failed",
|
|
1475
|
+
finished_at=now,
|
|
1476
|
+
error={"type": type(exc).__name__, "message": str(exc)[:500]},
|
|
1477
|
+
uncertain=self._is_uncertain(exc),
|
|
1478
|
+
)
|
|
1479
|
+
]
|
|
1480
|
+
done = dataclasses.replace(
|
|
1481
|
+
owned, state="succeeded", finished_at=now, result=value, has_result=True
|
|
1482
|
+
)
|
|
1483
|
+
return [done, dataclasses.replace(done, result=None, has_result=False)]
|
|
1484
|
+
|
|
1485
|
+
def _settle(self, owned: EffectRecord, value: Any, exc: BaseException | None) -> None:
|
|
1486
|
+
*first, last = self._finished(owned, value, exc)
|
|
1487
|
+
written: bool | None = None
|
|
1488
|
+
for record in first:
|
|
1489
|
+
try:
|
|
1490
|
+
written = self.store.settle(record, self.ttl)
|
|
1491
|
+
break
|
|
1492
|
+
except (TypeError, ValueError):
|
|
1493
|
+
continue # the result is not serialisable: store the outcome without it
|
|
1494
|
+
if written is None:
|
|
1495
|
+
written = self.store.settle(last, self.ttl)
|
|
1496
|
+
if not written:
|
|
1497
|
+
_core.get_logger(None).warning(
|
|
1498
|
+
"effect ledger: the record of %s (%s) was taken over after its lease ran "
|
|
1499
|
+
"out; this outcome was not stored",
|
|
1500
|
+
owned.tool,
|
|
1501
|
+
owned.key,
|
|
1502
|
+
)
|
|
1503
|
+
|
|
1504
|
+
def _begin_local(self, key: str) -> threading.Event:
|
|
1505
|
+
event = threading.Event()
|
|
1506
|
+
with self._lock:
|
|
1507
|
+
self._events[key] = event
|
|
1508
|
+
self._orphans.discard(key)
|
|
1509
|
+
return event
|
|
1510
|
+
|
|
1511
|
+
def _end_local(self, key: str, event: threading.Event, orphaned: bool) -> None:
|
|
1512
|
+
with self._lock:
|
|
1513
|
+
if self._events.get(key) is event:
|
|
1514
|
+
del self._events[key]
|
|
1515
|
+
if orphaned:
|
|
1516
|
+
self._orphans.add(key)
|
|
1517
|
+
event.set()
|
|
1518
|
+
|
|
1519
|
+
def _local_event(self, key: str) -> threading.Event | None:
|
|
1520
|
+
with self._lock:
|
|
1521
|
+
return self._events.get(key)
|
|
1522
|
+
|
|
1523
|
+
def _decide(self, error: EffectUnknown, answer: Any) -> Any:
|
|
1524
|
+
if answer == "retry" or isinstance(answer, EffectResolved):
|
|
1525
|
+
return answer
|
|
1526
|
+
if answer is None or answer == "raise":
|
|
1527
|
+
raise error
|
|
1528
|
+
raise TypeError(
|
|
1529
|
+
"on_unknown must return 'retry', 'raise', None or EffectResolved(value); "
|
|
1530
|
+
f"got {answer!r}"
|
|
1531
|
+
)
|
|
1532
|
+
|
|
1533
|
+
# -- sync -----------------------------------------------------------------
|
|
1534
|
+
def execute(
|
|
1535
|
+
self,
|
|
1536
|
+
tool: str,
|
|
1537
|
+
func: Callable[..., R],
|
|
1538
|
+
args: tuple[Any, ...] = (),
|
|
1539
|
+
kwargs: Mapping[str, Any] | None = None,
|
|
1540
|
+
*,
|
|
1541
|
+
key: str,
|
|
1542
|
+
digest: str | None = None,
|
|
1543
|
+
call_id: str | None = None,
|
|
1544
|
+
) -> R:
|
|
1545
|
+
"""Run ``func(*args, **kwargs)`` at most once per ``key``; see the class docs."""
|
|
1546
|
+
kwargs = dict(kwargs or {})
|
|
1547
|
+
attempts = 1
|
|
1548
|
+
expect: str | None = None
|
|
1549
|
+
deadline = None if self.wait_timeout is None else _core.monotonic() + self.wait_timeout
|
|
1550
|
+
while True:
|
|
1551
|
+
mine = self._new(key, tool, digest, call_id, attempts)
|
|
1552
|
+
current = self.store.claim(mine, self.ttl, expect)
|
|
1553
|
+
if current is None:
|
|
1554
|
+
return self._run_sync(mine, func, args, kwargs)
|
|
1555
|
+
expect = None
|
|
1556
|
+
action, reason = self._verdict(current, digest)
|
|
1557
|
+
if action == "replay":
|
|
1558
|
+
return cast(R, current.result)
|
|
1559
|
+
if action == "rerun":
|
|
1560
|
+
expect, attempts = current.owner, current.attempts + 1
|
|
1561
|
+
continue
|
|
1562
|
+
if action == "wait":
|
|
1563
|
+
self._wait_sync(current, deadline)
|
|
1564
|
+
continue
|
|
1565
|
+
assert reason is not None
|
|
1566
|
+
error = self._unknown(current, reason)
|
|
1567
|
+
answer = self.on_unknown(error) if self.on_unknown is not None else None
|
|
1568
|
+
if inspect.isawaitable(answer):
|
|
1569
|
+
answer = _run_awaitable(answer)
|
|
1570
|
+
decision = self._decide(error, answer)
|
|
1571
|
+
if decision == "retry":
|
|
1572
|
+
expect, attempts = current.owner, current.attempts + 1
|
|
1573
|
+
continue
|
|
1574
|
+
return cast(R, self._resolve_sync(current, decision.value, attempts))
|
|
1575
|
+
|
|
1576
|
+
def _resolve_sync(self, current: EffectRecord, value: Any, attempts: int) -> Any:
|
|
1577
|
+
mine = self._new(current.key, current.tool, current.arguments, current.call_id, attempts)
|
|
1578
|
+
blocked = self.store.claim(mine, self.ttl, current.owner)
|
|
1579
|
+
if blocked is not None:
|
|
1580
|
+
raise self._unknown(blocked, "crashed")
|
|
1581
|
+
self._settle(mine, value, None)
|
|
1582
|
+
with self._lock:
|
|
1583
|
+
self._orphans.discard(current.key)
|
|
1584
|
+
_core.emit("tool.effect_resolved", current.tool, run_id=current.run_id)
|
|
1585
|
+
return value
|
|
1586
|
+
|
|
1587
|
+
def _run_sync(
|
|
1588
|
+
self,
|
|
1589
|
+
mine: EffectRecord,
|
|
1590
|
+
func: Callable[..., R],
|
|
1591
|
+
args: tuple[Any, ...],
|
|
1592
|
+
kwargs: dict[str, Any],
|
|
1593
|
+
) -> R:
|
|
1594
|
+
event = self._begin_local(mine.key)
|
|
1595
|
+
orphaned = True
|
|
1596
|
+
try:
|
|
1597
|
+
try:
|
|
1598
|
+
value = func(*args, **kwargs)
|
|
1599
|
+
except BaseException as exc:
|
|
1600
|
+
try:
|
|
1601
|
+
self._settle(mine, None, exc)
|
|
1602
|
+
orphaned = False
|
|
1603
|
+
except Exception:
|
|
1604
|
+
_core.get_logger(None).exception(
|
|
1605
|
+
"effect ledger could not record the failure of %s", mine.tool
|
|
1606
|
+
)
|
|
1607
|
+
raise
|
|
1608
|
+
self._settle(mine, value, None)
|
|
1609
|
+
orphaned = False
|
|
1610
|
+
return value
|
|
1611
|
+
finally:
|
|
1612
|
+
self._end_local(mine.key, event, orphaned)
|
|
1613
|
+
|
|
1614
|
+
def _wait_sync(self, current: EffectRecord, deadline: float | None) -> None:
|
|
1615
|
+
event = self._local_event(current.key)
|
|
1616
|
+
while True:
|
|
1617
|
+
now = _core.wall_time()
|
|
1618
|
+
pause = max(0.0, current.lease_until - now)
|
|
1619
|
+
if deadline is not None:
|
|
1620
|
+
left = deadline - _core.monotonic()
|
|
1621
|
+
if left <= 0:
|
|
1622
|
+
raise TimeoutExpired(
|
|
1623
|
+
f"tool {current.tool!r} is still running elsewhere ({current.key})",
|
|
1624
|
+
seconds=self.wait_timeout or 0.0,
|
|
1625
|
+
)
|
|
1626
|
+
pause = min(pause, left)
|
|
1627
|
+
if event is not None:
|
|
1628
|
+
event.wait(min(pause, 1.0) if pause else 0)
|
|
1629
|
+
if event.is_set():
|
|
1630
|
+
return
|
|
1631
|
+
else:
|
|
1632
|
+
_core.sleep(min(self.poll, pause) if pause else 0)
|
|
1633
|
+
latest = self.store.get(current.key)
|
|
1634
|
+
if latest is None or latest.owner != current.owner or latest.state != "started":
|
|
1635
|
+
return
|
|
1636
|
+
if latest.lease_until <= _core.wall_time() or self._orphaned(current.key):
|
|
1637
|
+
return
|
|
1638
|
+
|
|
1639
|
+
def _orphaned(self, key: str) -> bool:
|
|
1640
|
+
with self._lock:
|
|
1641
|
+
return key in self._orphans
|
|
1642
|
+
|
|
1643
|
+
# -- async ----------------------------------------------------------------
|
|
1644
|
+
async def _store(self, method: Callable[..., Any], *args: Any) -> Any:
|
|
1645
|
+
if self._local_store:
|
|
1646
|
+
return method(*args)
|
|
1647
|
+
return await asyncio.to_thread(method, *args)
|
|
1648
|
+
|
|
1649
|
+
async def aexecute(
|
|
1650
|
+
self,
|
|
1651
|
+
tool: str,
|
|
1652
|
+
func: Callable[..., Awaitable[R]],
|
|
1653
|
+
args: tuple[Any, ...] = (),
|
|
1654
|
+
kwargs: Mapping[str, Any] | None = None,
|
|
1655
|
+
*,
|
|
1656
|
+
key: str,
|
|
1657
|
+
digest: str | None = None,
|
|
1658
|
+
call_id: str | None = None,
|
|
1659
|
+
) -> R:
|
|
1660
|
+
"""The async form of `execute` for an ``async def`` ``func``."""
|
|
1661
|
+
kwargs = dict(kwargs or {})
|
|
1662
|
+
attempts = 1
|
|
1663
|
+
expect: str | None = None
|
|
1664
|
+
deadline = None if self.wait_timeout is None else _core.monotonic() + self.wait_timeout
|
|
1665
|
+
while True:
|
|
1666
|
+
mine = self._new(key, tool, digest, call_id, attempts)
|
|
1667
|
+
current = await self._store(self.store.claim, mine, self.ttl, expect)
|
|
1668
|
+
if current is None:
|
|
1669
|
+
return await self._run_async(mine, func, args, kwargs)
|
|
1670
|
+
expect = None
|
|
1671
|
+
action, reason = self._verdict(current, digest)
|
|
1672
|
+
if action == "replay":
|
|
1673
|
+
return cast(R, current.result)
|
|
1674
|
+
if action == "rerun":
|
|
1675
|
+
expect, attempts = current.owner, current.attempts + 1
|
|
1676
|
+
continue
|
|
1677
|
+
if action == "wait":
|
|
1678
|
+
await self._wait_async(current, deadline)
|
|
1679
|
+
continue
|
|
1680
|
+
assert reason is not None
|
|
1681
|
+
error = self._unknown(current, reason)
|
|
1682
|
+
answer = self.on_unknown(error) if self.on_unknown is not None else None
|
|
1683
|
+
if inspect.isawaitable(answer):
|
|
1684
|
+
answer = await answer
|
|
1685
|
+
decision = self._decide(error, answer)
|
|
1686
|
+
if decision == "retry":
|
|
1687
|
+
expect, attempts = current.owner, current.attempts + 1
|
|
1688
|
+
continue
|
|
1689
|
+
value = decision.value
|
|
1690
|
+
mine = self._new(key, tool, current.arguments, current.call_id, attempts)
|
|
1691
|
+
blocked = await self._store(self.store.claim, mine, self.ttl, current.owner)
|
|
1692
|
+
if blocked is not None:
|
|
1693
|
+
raise self._unknown(blocked, "crashed")
|
|
1694
|
+
await self._store(self._settle, mine, value, None)
|
|
1695
|
+
with self._lock:
|
|
1696
|
+
self._orphans.discard(key)
|
|
1697
|
+
_core.emit("tool.effect_resolved", tool, run_id=current.run_id)
|
|
1698
|
+
return cast(R, value)
|
|
1699
|
+
|
|
1700
|
+
async def _run_async(
|
|
1701
|
+
self,
|
|
1702
|
+
mine: EffectRecord,
|
|
1703
|
+
func: Callable[..., Awaitable[R]],
|
|
1704
|
+
args: tuple[Any, ...],
|
|
1705
|
+
kwargs: dict[str, Any],
|
|
1706
|
+
) -> R:
|
|
1707
|
+
event = self._begin_local(mine.key)
|
|
1708
|
+
orphaned = True
|
|
1709
|
+
try:
|
|
1710
|
+
try:
|
|
1711
|
+
value = await func(*args, **kwargs)
|
|
1712
|
+
except BaseException as exc:
|
|
1713
|
+
try:
|
|
1714
|
+
await self._store(self._settle, mine, None, exc)
|
|
1715
|
+
orphaned = False
|
|
1716
|
+
except Exception:
|
|
1717
|
+
_core.get_logger(None).exception(
|
|
1718
|
+
"effect ledger could not record the failure of %s", mine.tool
|
|
1719
|
+
)
|
|
1720
|
+
raise
|
|
1721
|
+
await self._store(self._settle, mine, value, None)
|
|
1722
|
+
orphaned = False
|
|
1723
|
+
return value
|
|
1724
|
+
finally:
|
|
1725
|
+
self._end_local(mine.key, event, orphaned)
|
|
1726
|
+
|
|
1727
|
+
async def _wait_async(self, current: EffectRecord, deadline: float | None) -> None:
|
|
1728
|
+
while True:
|
|
1729
|
+
pause = max(0.0, current.lease_until - _core.wall_time())
|
|
1730
|
+
if deadline is not None:
|
|
1731
|
+
left = deadline - _core.monotonic()
|
|
1732
|
+
if left <= 0:
|
|
1733
|
+
raise TimeoutExpired(
|
|
1734
|
+
f"tool {current.tool!r} is still running elsewhere ({current.key})",
|
|
1735
|
+
seconds=self.wait_timeout or 0.0,
|
|
1736
|
+
)
|
|
1737
|
+
pause = min(pause, left)
|
|
1738
|
+
event = self._local_event(current.key)
|
|
1739
|
+
await asyncio.sleep(min(self.poll if event is None else 0.005, pause))
|
|
1740
|
+
if event is not None and event.is_set():
|
|
1741
|
+
return
|
|
1742
|
+
latest = await self._store(self.store.get, current.key)
|
|
1743
|
+
if latest is None or latest.owner != current.owner or latest.state != "started":
|
|
1744
|
+
return
|
|
1745
|
+
if latest.lease_until <= _core.wall_time() or self._orphaned(current.key):
|
|
1746
|
+
return
|
|
1747
|
+
|
|
1748
|
+
def __repr__(self) -> str:
|
|
1749
|
+
return f"EffectLedger({type(self.store).__name__}, lease={self.lease:g}s)"
|
|
1750
|
+
|
|
1751
|
+
|
|
1752
|
+
def _run_awaitable(awaitable: Awaitable[Any]) -> Any:
|
|
1753
|
+
"""Await from sync code, in a helper thread when an event loop is already running."""
|
|
1754
|
+
try:
|
|
1755
|
+
asyncio.get_running_loop()
|
|
1756
|
+
except RuntimeError:
|
|
1757
|
+
return asyncio.run(_await(awaitable))
|
|
1758
|
+
box: dict[str, Any] = {}
|
|
1759
|
+
|
|
1760
|
+
def run() -> None:
|
|
1761
|
+
try:
|
|
1762
|
+
box["value"] = asyncio.run(_await(awaitable))
|
|
1763
|
+
except BaseException as exc:
|
|
1764
|
+
box["error"] = exc
|
|
1765
|
+
|
|
1766
|
+
worker = threading.Thread(target=contextvars.copy_context().run, args=(run,), daemon=True)
|
|
1767
|
+
worker.start()
|
|
1768
|
+
worker.join()
|
|
1769
|
+
if "error" in box:
|
|
1770
|
+
raise box["error"]
|
|
1771
|
+
return box.get("value")
|
|
1772
|
+
|
|
1773
|
+
|
|
1774
|
+
def _effect_key(
|
|
1775
|
+
tool: str, call_id: str | None, digest: str | None, run_id: str | None, business_key: Any
|
|
1776
|
+
) -> str:
|
|
1777
|
+
if business_key is not None:
|
|
1778
|
+
return f"{tool}:key:{business_key}"
|
|
1779
|
+
if call_id is not None:
|
|
1780
|
+
return f"{tool}:call:{call_id}"
|
|
1781
|
+
return f"{tool}:{run_id or '-'}:{digest}"
|
|
1782
|
+
|
|
1783
|
+
|
|
1784
|
+
def _is_model_retry(exc: BaseException) -> bool:
|
|
1785
|
+
"""True for pydantic-ai's ``ModelRetry`` (matched by class name, never imported)."""
|
|
1786
|
+
return any(cls.__name__ == "ModelRetry" for cls in type(exc).__mro__)
|
|
1787
|
+
|
|
1788
|
+
|
|
1789
|
+
# --------------------------------------------------------------------------- tools
|
|
1790
|
+
|
|
1791
|
+
|
|
1792
|
+
@dataclass
|
|
1793
|
+
class _CallState:
|
|
1794
|
+
ran: bool = False
|
|
1795
|
+
|
|
1796
|
+
|
|
1797
|
+
_call_state: contextvars.ContextVar[_CallState | None] = contextvars.ContextVar(
|
|
1798
|
+
"python_wrap_tool_call_state", default=None
|
|
1799
|
+
)
|
|
1800
|
+
_call_key: contextvars.ContextVar[str] = contextvars.ContextVar(
|
|
1801
|
+
"python_wrap_tool_call_key", default=""
|
|
1802
|
+
)
|
|
1803
|
+
|
|
1804
|
+
|
|
1805
|
+
@dataclass
|
|
1806
|
+
class _Decision:
|
|
1807
|
+
dry_run: bool = False
|
|
1808
|
+
approver: Approver | None = None
|
|
1809
|
+
approval_timeout: float = 60.0
|
|
1810
|
+
policies: list[ToolPolicy] = field(default_factory=list)
|
|
1811
|
+
|
|
1812
|
+
|
|
1813
|
+
def _policies() -> list[ToolPolicy]:
|
|
1814
|
+
"""Policies in effect here, innermost first."""
|
|
1815
|
+
found: list[ToolPolicy] = []
|
|
1816
|
+
run = _run_var.get()
|
|
1817
|
+
while run is not None:
|
|
1818
|
+
for policy in (run.guard.policy, run.guard._extra_policy):
|
|
1819
|
+
if policy is not None:
|
|
1820
|
+
found.append(policy)
|
|
1821
|
+
run = run.parent
|
|
1822
|
+
extra = _registry_policy.get()
|
|
1823
|
+
if extra is not None:
|
|
1824
|
+
found.append(extra)
|
|
1825
|
+
return found
|
|
1826
|
+
|
|
1827
|
+
|
|
1828
|
+
def _deny(error: type[ToolNotAllowed], spec: ToolSpec, reason: str, message: str) -> ToolNotAllowed:
|
|
1829
|
+
run_id = run_id_var.get()
|
|
1830
|
+
_core.emit("tool.denied", spec.name, run_id=run_id, reason=reason)
|
|
1831
|
+
return error(message, tool=spec.name, reason=reason, run_id=run_id)
|
|
1832
|
+
|
|
1833
|
+
|
|
1834
|
+
def _authorize(spec: ToolSpec) -> _Decision:
|
|
1835
|
+
decision = _Decision(policies=_policies())
|
|
1836
|
+
for policy in decision.policies:
|
|
1837
|
+
if not policy.permits(spec.name):
|
|
1838
|
+
raise _deny(ToolNotAllowed, spec, "denied", f"tool {spec.name!r} is not allowed here")
|
|
1839
|
+
if not policy.allow_write and not spec.read_only:
|
|
1840
|
+
raise _deny(
|
|
1841
|
+
ToolNotAllowed,
|
|
1842
|
+
spec,
|
|
1843
|
+
"read_only",
|
|
1844
|
+
f"tool {spec.name!r} has side effects and this run is read-only "
|
|
1845
|
+
"(allow_write=False); declare it read_only=True if it has none",
|
|
1846
|
+
)
|
|
1847
|
+
if policy.dry_run and not spec.read_only:
|
|
1848
|
+
decision.dry_run = True
|
|
1849
|
+
if decision.approver is None and policy.approver is not None:
|
|
1850
|
+
decision.approver = policy.approver
|
|
1851
|
+
decision.approval_timeout = policy.approval_timeout
|
|
1852
|
+
return decision
|
|
1853
|
+
|
|
1854
|
+
|
|
1855
|
+
def _approval_result(spec: ToolSpec, ok: Any, error: BaseException | None) -> None:
|
|
1856
|
+
if error is not None:
|
|
1857
|
+
raise _deny(
|
|
1858
|
+
ApprovalDenied, spec, "approval_denied", f"approver failed for tool {spec.name!r}"
|
|
1859
|
+
) from error
|
|
1860
|
+
if ok is not True:
|
|
1861
|
+
raise _deny(
|
|
1862
|
+
ApprovalDenied, spec, "approval_denied", f"approval for tool {spec.name!r} was denied"
|
|
1863
|
+
)
|
|
1864
|
+
|
|
1865
|
+
|
|
1866
|
+
def _no_approver(spec: ToolSpec) -> ToolNotAllowed:
|
|
1867
|
+
return _deny(
|
|
1868
|
+
ApprovalDenied,
|
|
1869
|
+
spec,
|
|
1870
|
+
"approval_denied",
|
|
1871
|
+
f"tool {spec.name!r} requires approval but no approver is configured "
|
|
1872
|
+
"(set ToolPolicy(approver=...))",
|
|
1873
|
+
)
|
|
1874
|
+
|
|
1875
|
+
|
|
1876
|
+
def _timed_out(spec: ToolSpec, seconds: float) -> ToolNotAllowed:
|
|
1877
|
+
return _deny(
|
|
1878
|
+
ApprovalTimeout,
|
|
1879
|
+
spec,
|
|
1880
|
+
"approval_timeout",
|
|
1881
|
+
f"no approval for tool {spec.name!r} within {seconds:g}s",
|
|
1882
|
+
)
|
|
1883
|
+
|
|
1884
|
+
|
|
1885
|
+
def _approve_sync(spec: ToolSpec, decision: _Decision, call: ToolCall) -> None:
|
|
1886
|
+
approver = decision.approver
|
|
1887
|
+
if approver is None:
|
|
1888
|
+
raise _no_approver(spec)
|
|
1889
|
+
box: dict[str, Any] = {}
|
|
1890
|
+
done = threading.Event()
|
|
1891
|
+
|
|
1892
|
+
def ask() -> None:
|
|
1893
|
+
try:
|
|
1894
|
+
answer = approver(call)
|
|
1895
|
+
if inspect.isawaitable(answer):
|
|
1896
|
+
answer = asyncio.run(_await(answer))
|
|
1897
|
+
box["ok"] = answer
|
|
1898
|
+
except BaseException as error:
|
|
1899
|
+
box["error"] = error
|
|
1900
|
+
finally:
|
|
1901
|
+
done.set()
|
|
1902
|
+
|
|
1903
|
+
context = contextvars.copy_context()
|
|
1904
|
+
threading.Thread(
|
|
1905
|
+
target=context.run, args=(ask,), daemon=True, name="python-wrap-approval"
|
|
1906
|
+
).start()
|
|
1907
|
+
if not done.wait(decision.approval_timeout):
|
|
1908
|
+
raise _timed_out(spec, decision.approval_timeout)
|
|
1909
|
+
_approval_result(spec, box.get("ok"), box.get("error"))
|
|
1910
|
+
|
|
1911
|
+
|
|
1912
|
+
async def _await(awaitable: Awaitable[Any]) -> Any:
|
|
1913
|
+
return await awaitable
|
|
1914
|
+
|
|
1915
|
+
|
|
1916
|
+
async def _approve_async(spec: ToolSpec, decision: _Decision, call: ToolCall) -> None:
|
|
1917
|
+
approver = decision.approver
|
|
1918
|
+
if approver is None:
|
|
1919
|
+
raise _no_approver(spec)
|
|
1920
|
+
limit = decision.approval_timeout
|
|
1921
|
+
|
|
1922
|
+
async def ask() -> Any:
|
|
1923
|
+
if _core.is_async(approver):
|
|
1924
|
+
return await cast(Callable[[ToolCall], Awaitable[Any]], approver)(call)
|
|
1925
|
+
answer = await asyncio.to_thread(approver, call)
|
|
1926
|
+
if inspect.isawaitable(answer):
|
|
1927
|
+
answer = await answer
|
|
1928
|
+
return answer
|
|
1929
|
+
|
|
1930
|
+
ok: Any = None
|
|
1931
|
+
error: BaseException | None = None
|
|
1932
|
+
try:
|
|
1933
|
+
ok = await asyncio.wait_for(ask(), limit)
|
|
1934
|
+
except asyncio.TimeoutError:
|
|
1935
|
+
raise _timed_out(spec, limit) from None
|
|
1936
|
+
except Exception as exc:
|
|
1937
|
+
error = exc
|
|
1938
|
+
_approval_result(spec, ok, error)
|
|
1939
|
+
|
|
1940
|
+
|
|
1941
|
+
def _dry(
|
|
1942
|
+
spec: ToolSpec, dry_result: Any, arguments: Mapping[str, Any], args: Any, kwargs: Any
|
|
1943
|
+
) -> Any:
|
|
1944
|
+
_core.emit("tool.dry_run", spec.name, run_id=run_id_var.get())
|
|
1945
|
+
if dry_result is _MISSING:
|
|
1946
|
+
return DryRun(spec.name, arguments)
|
|
1947
|
+
if callable(dry_result):
|
|
1948
|
+
return dry_result(*args, **kwargs)
|
|
1949
|
+
return dry_result
|
|
1950
|
+
|
|
1951
|
+
|
|
1952
|
+
class _Missing:
|
|
1953
|
+
def __repr__(self) -> str:
|
|
1954
|
+
return "MISSING"
|
|
1955
|
+
|
|
1956
|
+
|
|
1957
|
+
_MISSING: Any = _Missing()
|
|
1958
|
+
|
|
1959
|
+
|
|
1960
|
+
def _description(func: Callable[..., Any], given: str | None) -> str:
|
|
1961
|
+
if given is not None:
|
|
1962
|
+
return given
|
|
1963
|
+
doc = inspect.getdoc(func) or ""
|
|
1964
|
+
return doc.strip().splitlines()[0] if doc.strip() else ""
|
|
1965
|
+
|
|
1966
|
+
|
|
1967
|
+
@overload
|
|
1968
|
+
def tool(func: Callable[P, R], /) -> Callable[P, R]: ...
|
|
1969
|
+
|
|
1970
|
+
|
|
1971
|
+
@overload
|
|
1972
|
+
def tool(
|
|
1973
|
+
func: None = None,
|
|
1974
|
+
/,
|
|
1975
|
+
*,
|
|
1976
|
+
name: str | None = None,
|
|
1977
|
+
description: str | None = None,
|
|
1978
|
+
read_only: bool = False,
|
|
1979
|
+
idempotent_key: bool | Callable[..., object] | None = None,
|
|
1980
|
+
requires_approval: bool = False,
|
|
1981
|
+
timeout: float | str | None = None,
|
|
1982
|
+
retry: Callable[[Any], Any] | None = None,
|
|
1983
|
+
dry_result: Any = _MISSING,
|
|
1984
|
+
store: Any = None,
|
|
1985
|
+
ttl: float | str = "1d",
|
|
1986
|
+
ledger: EffectLedger | None = None,
|
|
1987
|
+
) -> Callable[[Callable[P, R]], Callable[P, R]]: ...
|
|
1988
|
+
|
|
1989
|
+
|
|
1990
|
+
def tool(
|
|
1991
|
+
func: Callable[..., Any] | None = None,
|
|
1992
|
+
/,
|
|
1993
|
+
*,
|
|
1994
|
+
name: str | None = None,
|
|
1995
|
+
description: str | None = None,
|
|
1996
|
+
read_only: bool = False,
|
|
1997
|
+
idempotent_key: bool | Callable[..., object] | None = None,
|
|
1998
|
+
requires_approval: bool = False,
|
|
1999
|
+
timeout: float | str | None = None,
|
|
2000
|
+
retry: Callable[[Any], Any] | None = None,
|
|
2001
|
+
dry_result: Any = _MISSING,
|
|
2002
|
+
store: Any = None,
|
|
2003
|
+
ttl: float | str = "1d",
|
|
2004
|
+
ledger: EffectLedger | None = None,
|
|
2005
|
+
) -> Any:
|
|
2006
|
+
"""Mark a sync or async function as an agent tool with replay-safe side effects.
|
|
2007
|
+
|
|
2008
|
+
Every call, in this order: counts as a ``"tool"`` step of the current run (limits and
|
|
2009
|
+
loop detection), passes the `ToolPolicy` checks (allow/deny, read-only), returns the
|
|
2010
|
+
dry-run result in a dry run, asks the approver when ``requires_approval=True``, then
|
|
2011
|
+
runs, deduplicated by its idempotency key, under ``retry`` and ``timeout``.
|
|
2012
|
+
|
|
2013
|
+
Idempotency: a tool with side effects (``read_only=False``) gets a key from the tool
|
|
2014
|
+
name, the canonical arguments and the current run id. A second call with the same key
|
|
2015
|
+
within ``ttl`` (a retried step, a replayed run with the same ``run_id``, a model that
|
|
2016
|
+
asks twice) returns the stored result without running, and emits ``tool.replayed``.
|
|
2017
|
+
Only successful results are stored; a failing call runs again next time. A concurrent
|
|
2018
|
+
duplicate waits for the first call and returns its result.
|
|
2019
|
+
|
|
2020
|
+
Args:
|
|
2021
|
+
func: The tool function (for bare ``@tool``).
|
|
2022
|
+
name: Name the model uses; the function name by default.
|
|
2023
|
+
description: First docstring line by default.
|
|
2024
|
+
read_only: True for tools without side effects: they run in read-only and dry
|
|
2025
|
+
runs and are not deduplicated by default.
|
|
2026
|
+
idempotent_key: None derives a key for write tools only; True derives one for
|
|
2027
|
+
read-only tools too; False disables deduplication; a callable receives the
|
|
2028
|
+
tool's arguments and returns a key (used as is, prefixed by the tool name,
|
|
2029
|
+
not scoped to the run: use it for business keys such as an order id).
|
|
2030
|
+
requires_approval: Ask the run's approver before every call; denied without one.
|
|
2031
|
+
timeout: Per-call time limit (seconds or ``"30s"``), applied inside ``retry``.
|
|
2032
|
+
retry: A decorator such as ``retry(max_attempts=3, on=ConnectionError)``,
|
|
2033
|
+
applied inside the deduplication, so a replay never re-runs it.
|
|
2034
|
+
dry_result: Returned in a dry run instead of running (a callable is called with
|
|
2035
|
+
the tool's arguments); a `DryRun` marker by default.
|
|
2036
|
+
store: Result store for deduplication (shared across processes with
|
|
2037
|
+
``RedisStore(fail_open=False)``); in-process `MemoryResultStore` by default.
|
|
2038
|
+
ttl: How long a result is replayed (``"1d"`` by default).
|
|
2039
|
+
ledger: An `EffectLedger` to deduplicate with instead of ``store``: the key is
|
|
2040
|
+
the provider's tool-call id when one is current (`with_call_id`; adapters
|
|
2041
|
+
set it), so a replayed call returns the stored result while a new call from
|
|
2042
|
+
the model runs; without an id it is the run id and argument digest as above.
|
|
2043
|
+
Calls are recorded as started / succeeded / failed, so a crash between the
|
|
2044
|
+
side effect and the record is detected (`EffectUnknown`). A ledger turns
|
|
2045
|
+
deduplication on for read-only tools too, unless ``idempotent_key=False``.
|
|
2046
|
+
|
|
2047
|
+
Returns:
|
|
2048
|
+
The wrapped function, with the same signature. `tool_spec` reads its `ToolSpec`.
|
|
2049
|
+
|
|
2050
|
+
Example:
|
|
2051
|
+
```python
|
|
2052
|
+
from python_wrap.agents import agent_run, tool
|
|
2053
|
+
|
|
2054
|
+
sent = []
|
|
2055
|
+
|
|
2056
|
+
@tool
|
|
2057
|
+
def send_email(to: str, subject: str) -> str:
|
|
2058
|
+
sent.append(to)
|
|
2059
|
+
return f"queued for {to}"
|
|
2060
|
+
|
|
2061
|
+
with agent_run(run_id="run-1"):
|
|
2062
|
+
assert send_email("ada@example.com", "hi") == "queued for ada@example.com"
|
|
2063
|
+
send_email("ada@example.com", "hi") # replayed, not sent again
|
|
2064
|
+
assert sent == ["ada@example.com"]
|
|
2065
|
+
```
|
|
2066
|
+
"""
|
|
2067
|
+
if func is None:
|
|
2068
|
+
return functools.partial(
|
|
2069
|
+
tool,
|
|
2070
|
+
name=name,
|
|
2071
|
+
description=description,
|
|
2072
|
+
read_only=read_only,
|
|
2073
|
+
idempotent_key=idempotent_key,
|
|
2074
|
+
requires_approval=requires_approval,
|
|
2075
|
+
timeout=timeout,
|
|
2076
|
+
retry=retry,
|
|
2077
|
+
dry_result=dry_result,
|
|
2078
|
+
store=store,
|
|
2079
|
+
ttl=ttl,
|
|
2080
|
+
ledger=ledger,
|
|
2081
|
+
)
|
|
2082
|
+
if not callable(func):
|
|
2083
|
+
raise TypeError("tool() expects a function")
|
|
2084
|
+
if not (idempotent_key is None or isinstance(idempotent_key, bool) or callable(idempotent_key)):
|
|
2085
|
+
raise TypeError("idempotent_key must be None, a bool or a callable")
|
|
2086
|
+
limit = None if timeout is None else _parse_seconds(timeout)
|
|
2087
|
+
if ledger is not None and not isinstance(ledger, EffectLedger):
|
|
2088
|
+
raise TypeError("ledger must be an EffectLedger")
|
|
2089
|
+
dedupe = idempotent_key is not False and (
|
|
2090
|
+
idempotent_key is not None or not read_only or ledger is not None
|
|
2091
|
+
)
|
|
2092
|
+
is_async = _core.is_async(func)
|
|
2093
|
+
spec = ToolSpec(
|
|
2094
|
+
name=name or func.__name__,
|
|
2095
|
+
description=_description(func, description),
|
|
2096
|
+
read_only=bool(read_only),
|
|
2097
|
+
idempotent=dedupe,
|
|
2098
|
+
requires_approval=bool(requires_approval),
|
|
2099
|
+
timeout=limit,
|
|
2100
|
+
retried=retry is not None,
|
|
2101
|
+
is_async=is_async,
|
|
2102
|
+
)
|
|
2103
|
+
signature = inspect.signature(func)
|
|
2104
|
+
params = list(signature.parameters)
|
|
2105
|
+
skip_first = bool(params) and (
|
|
2106
|
+
params[0] in ("self", "cls") or _is_framework_context(signature.parameters[params[0]])
|
|
2107
|
+
)
|
|
2108
|
+
|
|
2109
|
+
core: Callable[..., Any] = func
|
|
2110
|
+
if limit is not None:
|
|
2111
|
+
from python_wrap.concurrency import timeout as _timeout
|
|
2112
|
+
|
|
2113
|
+
core = _timeout(limit)(core)
|
|
2114
|
+
if retry is not None:
|
|
2115
|
+
core = retry(core)
|
|
2116
|
+
|
|
2117
|
+
def bind(args: tuple[Any, ...], kwargs: dict[str, Any]) -> dict[str, Any]:
|
|
2118
|
+
bound = signature.bind(*args, **kwargs)
|
|
2119
|
+
bound.apply_defaults()
|
|
2120
|
+
arguments = dict(bound.arguments)
|
|
2121
|
+
if skip_first:
|
|
2122
|
+
arguments.pop(params[0], None)
|
|
2123
|
+
return arguments
|
|
2124
|
+
|
|
2125
|
+
def make_key(args: tuple[Any, ...], kwargs: dict[str, Any], digest: str | None) -> str:
|
|
2126
|
+
if callable(idempotent_key) and not isinstance(idempotent_key, bool):
|
|
2127
|
+
return f"tool:{spec.name}:key:{idempotent_key(*args, **kwargs)}"
|
|
2128
|
+
return f"tool:{spec.name}:{run_id_var.get() or '-'}:{digest}"
|
|
2129
|
+
|
|
2130
|
+
def ledger_key(args: tuple[Any, ...], kwargs: dict[str, Any], digest: str | None) -> str:
|
|
2131
|
+
business = None
|
|
2132
|
+
if callable(idempotent_key) and not isinstance(idempotent_key, bool):
|
|
2133
|
+
business = idempotent_key(*args, **kwargs)
|
|
2134
|
+
return _effect_key(spec.name, tool_call_id.get(), digest, run_id_var.get(), business)
|
|
2135
|
+
|
|
2136
|
+
runner: Callable[..., Any] = core
|
|
2137
|
+
if dedupe and ledger is not None:
|
|
2138
|
+
if is_async:
|
|
2139
|
+
|
|
2140
|
+
async def ledger_async(*args: Any, **kwargs: Any) -> Any:
|
|
2141
|
+
_mark_ran(spec)
|
|
2142
|
+
return await core(*args, **kwargs)
|
|
2143
|
+
|
|
2144
|
+
async def run_ledger_async(*args: Any, **kwargs: Any) -> Any:
|
|
2145
|
+
digest = _call_key.get()
|
|
2146
|
+
return await ledger.aexecute(
|
|
2147
|
+
spec.name,
|
|
2148
|
+
ledger_async,
|
|
2149
|
+
args,
|
|
2150
|
+
kwargs,
|
|
2151
|
+
key=ledger_key(args, kwargs, digest),
|
|
2152
|
+
digest=digest,
|
|
2153
|
+
call_id=tool_call_id.get(),
|
|
2154
|
+
)
|
|
2155
|
+
|
|
2156
|
+
runner = run_ledger_async
|
|
2157
|
+
else:
|
|
2158
|
+
|
|
2159
|
+
def ledger_sync(*args: Any, **kwargs: Any) -> Any:
|
|
2160
|
+
_mark_ran(spec)
|
|
2161
|
+
return core(*args, **kwargs)
|
|
2162
|
+
|
|
2163
|
+
def run_ledger(*args: Any, **kwargs: Any) -> Any:
|
|
2164
|
+
digest = _call_key.get()
|
|
2165
|
+
return ledger.execute(
|
|
2166
|
+
spec.name,
|
|
2167
|
+
ledger_sync,
|
|
2168
|
+
args,
|
|
2169
|
+
kwargs,
|
|
2170
|
+
key=ledger_key(args, kwargs, digest),
|
|
2171
|
+
digest=digest,
|
|
2172
|
+
call_id=tool_call_id.get(),
|
|
2173
|
+
)
|
|
2174
|
+
|
|
2175
|
+
runner = run_ledger
|
|
2176
|
+
elif dedupe:
|
|
2177
|
+
from python_wrap.idempotency import idempotent
|
|
2178
|
+
|
|
2179
|
+
def key_of(*args: Any, **kwargs: Any) -> str:
|
|
2180
|
+
return _call_key.get()
|
|
2181
|
+
|
|
2182
|
+
if is_async:
|
|
2183
|
+
|
|
2184
|
+
async def marked_async(*args: Any, **kwargs: Any) -> Any:
|
|
2185
|
+
_mark_ran(spec)
|
|
2186
|
+
return await core(*args, **kwargs)
|
|
2187
|
+
|
|
2188
|
+
runner = idempotent(key=key_of, ttl=ttl, store=store, in_progress="wait")(marked_async)
|
|
2189
|
+
else:
|
|
2190
|
+
|
|
2191
|
+
def marked(*args: Any, **kwargs: Any) -> Any:
|
|
2192
|
+
_mark_ran(spec)
|
|
2193
|
+
return core(*args, **kwargs)
|
|
2194
|
+
|
|
2195
|
+
runner = idempotent(key=key_of, ttl=ttl, store=store, in_progress="wait")(marked)
|
|
2196
|
+
|
|
2197
|
+
def call_key(args: tuple[Any, ...], kwargs: dict[str, Any], digest: str | None) -> str:
|
|
2198
|
+
# With a ledger the context carries the digest; the ledger builds its own key.
|
|
2199
|
+
return (digest or "") if ledger is not None else make_key(args, kwargs, digest)
|
|
2200
|
+
|
|
2201
|
+
def prepare(
|
|
2202
|
+
args: tuple[Any, ...], kwargs: dict[str, Any]
|
|
2203
|
+
) -> tuple[_Decision, ToolCall, str | None]:
|
|
2204
|
+
arguments = bind(args, kwargs)
|
|
2205
|
+
digest = canonical(arguments)
|
|
2206
|
+
run = _run_var.get()
|
|
2207
|
+
if run is not None:
|
|
2208
|
+
run._record("tool", spec.name, digest)
|
|
2209
|
+
decision = _authorize(spec)
|
|
2210
|
+
call = ToolCall(
|
|
2211
|
+
spec.name,
|
|
2212
|
+
MappingProxyType(arguments),
|
|
2213
|
+
run_id_var.get(),
|
|
2214
|
+
spec.read_only,
|
|
2215
|
+
spec.description,
|
|
2216
|
+
tool_call_id.get(),
|
|
2217
|
+
)
|
|
2218
|
+
return decision, call, digest
|
|
2219
|
+
|
|
2220
|
+
if is_async:
|
|
2221
|
+
|
|
2222
|
+
@functools.wraps(func)
|
|
2223
|
+
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
2224
|
+
decision, call, digest = prepare(args, kwargs)
|
|
2225
|
+
if decision.dry_run:
|
|
2226
|
+
return _dry(spec, dry_result, call.arguments, args, kwargs)
|
|
2227
|
+
if spec.requires_approval:
|
|
2228
|
+
await _approve_async(spec, decision, call)
|
|
2229
|
+
if not dedupe:
|
|
2230
|
+
_core.emit("tool.call", spec.name, run_id=call.run_id)
|
|
2231
|
+
return await runner(*args, **kwargs)
|
|
2232
|
+
state = _CallState()
|
|
2233
|
+
resets = (_call_state.set(state), _call_key.set(call_key(args, kwargs, digest)))
|
|
2234
|
+
try:
|
|
2235
|
+
result = await runner(*args, **kwargs)
|
|
2236
|
+
finally:
|
|
2237
|
+
_call_key.reset(resets[1])
|
|
2238
|
+
_call_state.reset(resets[0])
|
|
2239
|
+
if not state.ran:
|
|
2240
|
+
_core.emit("tool.replayed", spec.name, run_id=call.run_id)
|
|
2241
|
+
return result
|
|
2242
|
+
|
|
2243
|
+
wrapper: Callable[..., Any] = async_wrapper
|
|
2244
|
+
else:
|
|
2245
|
+
|
|
2246
|
+
@functools.wraps(func)
|
|
2247
|
+
def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
2248
|
+
decision, call, digest = prepare(args, kwargs)
|
|
2249
|
+
if decision.dry_run:
|
|
2250
|
+
return _dry(spec, dry_result, call.arguments, args, kwargs)
|
|
2251
|
+
if spec.requires_approval:
|
|
2252
|
+
_approve_sync(spec, decision, call)
|
|
2253
|
+
if not dedupe:
|
|
2254
|
+
_core.emit("tool.call", spec.name, run_id=call.run_id)
|
|
2255
|
+
return runner(*args, **kwargs)
|
|
2256
|
+
state = _CallState()
|
|
2257
|
+
resets = (_call_state.set(state), _call_key.set(call_key(args, kwargs, digest)))
|
|
2258
|
+
try:
|
|
2259
|
+
result = runner(*args, **kwargs)
|
|
2260
|
+
finally:
|
|
2261
|
+
_call_key.reset(resets[1])
|
|
2262
|
+
_call_state.reset(resets[0])
|
|
2263
|
+
if not state.ran:
|
|
2264
|
+
_core.emit("tool.replayed", spec.name, run_id=call.run_id)
|
|
2265
|
+
return result
|
|
2266
|
+
|
|
2267
|
+
wrapper = sync_wrapper
|
|
2268
|
+
|
|
2269
|
+
# Let `doctor` see the retry/timeout layers inside the tool.
|
|
2270
|
+
wrapper.__wrapped__ = core # type: ignore[attr-defined]
|
|
2271
|
+
setattr(wrapper, _SPEC_ATTR, spec)
|
|
2272
|
+
setattr(
|
|
2273
|
+
wrapper,
|
|
2274
|
+
_LAYER_ATTR,
|
|
2275
|
+
(
|
|
2276
|
+
"tool",
|
|
2277
|
+
{
|
|
2278
|
+
"name": spec.name,
|
|
2279
|
+
"read_only": spec.read_only,
|
|
2280
|
+
"idempotent": spec.idempotent,
|
|
2281
|
+
"requires_approval": spec.requires_approval,
|
|
2282
|
+
},
|
|
2283
|
+
),
|
|
2284
|
+
)
|
|
2285
|
+
return wrapper
|
|
2286
|
+
|
|
2287
|
+
|
|
2288
|
+
_CONTEXT_TYPES = ("RunContext", "ToolContext", "RunContextWrapper")
|
|
2289
|
+
|
|
2290
|
+
|
|
2291
|
+
def _is_framework_context(param: inspect.Parameter) -> bool:
|
|
2292
|
+
"""True for a first parameter that is an agent framework's run context.
|
|
2293
|
+
|
|
2294
|
+
pydantic-ai passes ``ctx: RunContext[...]`` and the OpenAI Agents SDK
|
|
2295
|
+
``ctx: RunContextWrapper[...]`` / ``ToolContext``; they differ on every call, so they
|
|
2296
|
+
are left out of the argument digest (like ``self``).
|
|
2297
|
+
"""
|
|
2298
|
+
annotation = param.annotation
|
|
2299
|
+
if annotation is inspect.Parameter.empty:
|
|
2300
|
+
return False
|
|
2301
|
+
text = annotation if isinstance(annotation, str) else repr(annotation)
|
|
2302
|
+
origin = getattr(annotation, "__origin__", annotation)
|
|
2303
|
+
name = getattr(origin, "__name__", "") if not isinstance(annotation, str) else ""
|
|
2304
|
+
return name in _CONTEXT_TYPES or any(
|
|
2305
|
+
text == kind or text.startswith(kind + "[") or f".{kind}" in text or f"{kind}[" in text
|
|
2306
|
+
for kind in _CONTEXT_TYPES
|
|
2307
|
+
)
|
|
2308
|
+
|
|
2309
|
+
|
|
2310
|
+
def _mark_ran(spec: ToolSpec) -> None:
|
|
2311
|
+
state = _call_state.get()
|
|
2312
|
+
if state is not None:
|
|
2313
|
+
state.ran = True
|
|
2314
|
+
_core.emit("tool.call", spec.name, run_id=run_id_var.get())
|
|
2315
|
+
|
|
2316
|
+
|
|
2317
|
+
def tool_spec(func: Callable[..., Any]) -> ToolSpec | None:
|
|
2318
|
+
"""The `ToolSpec` of a function decorated with `tool` (bound methods too), or None."""
|
|
2319
|
+
spec = getattr(getattr(func, "__func__", func), _SPEC_ATTR, None)
|
|
2320
|
+
return spec if isinstance(spec, ToolSpec) else None
|
|
2321
|
+
|
|
2322
|
+
|
|
2323
|
+
# --------------------------------------------------------------------------- registry
|
|
2324
|
+
|
|
2325
|
+
|
|
2326
|
+
class ToolRegistry:
|
|
2327
|
+
"""Tools by name, dispatched the way a model asks for them.
|
|
2328
|
+
|
|
2329
|
+
Args:
|
|
2330
|
+
tools: Functions to register (plain functions are wrapped with `tool` defaults,
|
|
2331
|
+
which treats them as having side effects).
|
|
2332
|
+
policy: A `ToolPolicy` applied to every `call`, and to every tool call inside
|
|
2333
|
+
`run`.
|
|
2334
|
+
guard: The `RunGuard` that `run` uses; ``doctor`` reports PW017 when it is
|
|
2335
|
+
missing or sets no limits.
|
|
2336
|
+
|
|
2337
|
+
Example:
|
|
2338
|
+
```python
|
|
2339
|
+
from python_wrap.agents import RunGuard, ToolNotAllowed, ToolPolicy, ToolRegistry
|
|
2340
|
+
|
|
2341
|
+
tools = ToolRegistry(policy=ToolPolicy(deny=["drop_*"]), guard=RunGuard(max_steps=8))
|
|
2342
|
+
|
|
2343
|
+
@tools.tool(read_only=True)
|
|
2344
|
+
def lookup(sku: str) -> int:
|
|
2345
|
+
return 3
|
|
2346
|
+
|
|
2347
|
+
@tools.tool
|
|
2348
|
+
def drop_table(name: str) -> None: ...
|
|
2349
|
+
|
|
2350
|
+
with tools.run():
|
|
2351
|
+
assert tools.call("lookup", '{"sku": "A-1"}') == 3
|
|
2352
|
+
try:
|
|
2353
|
+
tools.call("drop_table", {"name": "orders"})
|
|
2354
|
+
except ToolNotAllowed as error:
|
|
2355
|
+
assert error.reason == "denied"
|
|
2356
|
+
```
|
|
2357
|
+
"""
|
|
2358
|
+
|
|
2359
|
+
def __init__(
|
|
2360
|
+
self,
|
|
2361
|
+
tools: Iterable[Callable[..., Any]] = (),
|
|
2362
|
+
*,
|
|
2363
|
+
policy: ToolPolicy | None = None,
|
|
2364
|
+
guard: RunGuard | None = None,
|
|
2365
|
+
) -> None:
|
|
2366
|
+
if policy is not None and not isinstance(policy, ToolPolicy):
|
|
2367
|
+
raise TypeError("policy must be a ToolPolicy")
|
|
2368
|
+
if guard is not None and not isinstance(guard, RunGuard):
|
|
2369
|
+
raise TypeError("guard must be a RunGuard")
|
|
2370
|
+
self.policy = policy
|
|
2371
|
+
self.guard = guard
|
|
2372
|
+
self._tools: dict[str, Callable[..., Any]] = {}
|
|
2373
|
+
self._lock = threading.Lock()
|
|
2374
|
+
for func in tools:
|
|
2375
|
+
self.add(func)
|
|
2376
|
+
|
|
2377
|
+
def add(self, func: Callable[P, R]) -> Callable[P, R]:
|
|
2378
|
+
"""Register ``func`` (wrapping it with `tool` first if needed) and return it."""
|
|
2379
|
+
wrapped: Callable[..., Any] = func if tool_spec(func) is not None else tool(func)
|
|
2380
|
+
spec = tool_spec(wrapped)
|
|
2381
|
+
assert spec is not None
|
|
2382
|
+
with self._lock:
|
|
2383
|
+
if spec.name in self._tools:
|
|
2384
|
+
raise ValueError(f"a tool named {spec.name!r} is already registered")
|
|
2385
|
+
self._tools[spec.name] = wrapped
|
|
2386
|
+
return cast(Callable[P, R], wrapped)
|
|
2387
|
+
|
|
2388
|
+
@overload
|
|
2389
|
+
def tool(self, func: Callable[P, R], /) -> Callable[P, R]: ...
|
|
2390
|
+
|
|
2391
|
+
@overload
|
|
2392
|
+
def tool(
|
|
2393
|
+
self, func: None = None, /, **options: Any
|
|
2394
|
+
) -> Callable[[Callable[P, R]], Callable[P, R]]: ...
|
|
2395
|
+
|
|
2396
|
+
def tool(self, func: Callable[..., Any] | None = None, /, **options: Any) -> Any:
|
|
2397
|
+
"""`tool` that also registers the function: ``@registry.tool(read_only=True)``."""
|
|
2398
|
+
if func is None:
|
|
2399
|
+
return lambda f: self.add(tool(**options)(f))
|
|
2400
|
+
return self.add(tool(func))
|
|
2401
|
+
|
|
2402
|
+
def get(self, name: str) -> Callable[..., Any]:
|
|
2403
|
+
"""The registered tool called ``name``.
|
|
2404
|
+
|
|
2405
|
+
Raises:
|
|
2406
|
+
ToolNotAllowed: No such tool (reason ``"unknown"``).
|
|
2407
|
+
"""
|
|
2408
|
+
with self._lock:
|
|
2409
|
+
found = self._tools.get(name)
|
|
2410
|
+
if found is None:
|
|
2411
|
+
run_id = run_id_var.get()
|
|
2412
|
+
_core.emit("tool.denied", name, run_id=run_id, reason="unknown")
|
|
2413
|
+
raise ToolNotAllowed(
|
|
2414
|
+
f"unknown tool {name!r}", tool=name, reason="unknown", run_id=run_id
|
|
2415
|
+
)
|
|
2416
|
+
return found
|
|
2417
|
+
|
|
2418
|
+
def specs(self) -> list[ToolSpec]:
|
|
2419
|
+
"""The `ToolSpec` of every registered tool, in registration order."""
|
|
2420
|
+
with self._lock:
|
|
2421
|
+
funcs = list(self._tools.values())
|
|
2422
|
+
return [spec for spec in map(tool_spec, funcs) if spec is not None]
|
|
2423
|
+
|
|
2424
|
+
def __contains__(self, name: object) -> bool:
|
|
2425
|
+
with self._lock:
|
|
2426
|
+
return name in self._tools
|
|
2427
|
+
|
|
2428
|
+
def __iter__(self) -> Iterator[str]:
|
|
2429
|
+
with self._lock:
|
|
2430
|
+
return iter(list(self._tools))
|
|
2431
|
+
|
|
2432
|
+
def __len__(self) -> int:
|
|
2433
|
+
with self._lock:
|
|
2434
|
+
return len(self._tools)
|
|
2435
|
+
|
|
2436
|
+
def call(self, name: str, arguments: Mapping[str, Any] | str | None = None) -> Any:
|
|
2437
|
+
"""Call the tool ``name`` with keyword ``arguments`` (a mapping or a JSON object).
|
|
2438
|
+
|
|
2439
|
+
For an ``async def`` tool this returns a coroutine to await.
|
|
2440
|
+
|
|
2441
|
+
Raises:
|
|
2442
|
+
ToolNotAllowed: Unknown tool or refused by a policy.
|
|
2443
|
+
ValueError: ``arguments`` is not a JSON object.
|
|
2444
|
+
"""
|
|
2445
|
+
func = self.get(name)
|
|
2446
|
+
if arguments is None:
|
|
2447
|
+
kwargs: dict[str, Any] = {}
|
|
2448
|
+
else:
|
|
2449
|
+
parsed = json.loads(arguments) if isinstance(arguments, str) else arguments
|
|
2450
|
+
if not isinstance(parsed, Mapping):
|
|
2451
|
+
raise ValueError(f"arguments for tool {name!r} must be a JSON object")
|
|
2452
|
+
kwargs = dict(parsed)
|
|
2453
|
+
spec = tool_spec(func)
|
|
2454
|
+
if spec is not None and spec.is_async:
|
|
2455
|
+
return self._call_async(func, kwargs)
|
|
2456
|
+
reset = _registry_policy.set(self.policy)
|
|
2457
|
+
try:
|
|
2458
|
+
return func(**kwargs)
|
|
2459
|
+
finally:
|
|
2460
|
+
_registry_policy.reset(reset)
|
|
2461
|
+
|
|
2462
|
+
async def _call_async(self, func: Callable[..., Any], kwargs: dict[str, Any]) -> Any:
|
|
2463
|
+
reset = _registry_policy.set(self.policy)
|
|
2464
|
+
try:
|
|
2465
|
+
return await func(**kwargs)
|
|
2466
|
+
finally:
|
|
2467
|
+
_registry_policy.reset(reset)
|
|
2468
|
+
|
|
2469
|
+
def run(self, *, run_id: str | None = None) -> RunGuard:
|
|
2470
|
+
"""A run of ``guard`` (limitless when None) with this registry's policy in effect."""
|
|
2471
|
+
base = self.guard or RunGuard()
|
|
2472
|
+
if run_id is not None:
|
|
2473
|
+
base = RunGuard(
|
|
2474
|
+
max_steps=base.max_steps,
|
|
2475
|
+
max_seconds=base.max_seconds,
|
|
2476
|
+
max_repeats=base.max_repeats,
|
|
2477
|
+
budget=base.budget,
|
|
2478
|
+
policy=base.policy,
|
|
2479
|
+
run_id=run_id,
|
|
2480
|
+
name=base.name,
|
|
2481
|
+
)
|
|
2482
|
+
return base._with_policy(self.policy)
|
|
2483
|
+
|
|
2484
|
+
def _explain(self, *, idempotent: bool = True, multiprocess: bool = False) -> Any:
|
|
2485
|
+
from python_wrap.doctor import Finding, Layer, Report, _check, doctor
|
|
2486
|
+
|
|
2487
|
+
guard_layer = Layer(
|
|
2488
|
+
"agent_run",
|
|
2489
|
+
(self.guard or RunGuard()).settings(),
|
|
2490
|
+
)
|
|
2491
|
+
layers: list[Layer] = [guard_layer]
|
|
2492
|
+
findings: list[Finding] = list(_check([guard_layer], idempotent, multiprocess))
|
|
2493
|
+
with self._lock:
|
|
2494
|
+
funcs = list(self._tools.values())
|
|
2495
|
+
for func in funcs:
|
|
2496
|
+
report = doctor(func, idempotent=idempotent, multiprocess=multiprocess)
|
|
2497
|
+
layers += report.layers
|
|
2498
|
+
findings += [item for item in report.findings if item not in findings]
|
|
2499
|
+
findings.sort(key=lambda item: (item.severity != "error", item.code))
|
|
2500
|
+
return Report(f"ToolRegistry({len(funcs)} tools)", tuple(layers), tuple(findings))
|
|
2501
|
+
|
|
2502
|
+
def __repr__(self) -> str:
|
|
2503
|
+
return f"ToolRegistry({sorted(self)!r})"
|