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/genai.py
ADDED
|
@@ -0,0 +1,1101 @@
|
|
|
1
|
+
"""Observability and compliance for LLM and tool calls: enriched events, redaction, audit tape.
|
|
2
|
+
|
|
3
|
+
Three pieces, none of which imports a provider SDK or any other optional package:
|
|
4
|
+
|
|
5
|
+
* `traced_llm` / `traced_tool` wrap a function and publish a ``genai.llm_call`` /
|
|
6
|
+
``genai.tool_call`` event carrying run id, step, tool, model, token counts, cost and
|
|
7
|
+
latency. `instrument` turns on process-wide defaults (content capture, redaction,
|
|
8
|
+
price table, audit tape, OpenTelemetry GenAI spans).
|
|
9
|
+
* `Redactor` scrubs prompts, tool arguments and outputs (secrets, emails, card numbers,
|
|
10
|
+
your own patterns, sensitive key names) and truncates long text. Content capture is
|
|
11
|
+
**off** unless you ask for it: by default events carry metadata only.
|
|
12
|
+
* `AuditTape` records every call (redacted, ordered, timestamped) to memory, a JSONL file
|
|
13
|
+
or SQLite; `replay` turns a tape into fake callables that serve the recorded results in
|
|
14
|
+
tests and raise `ReplayMismatch` when the code under test diverges.
|
|
15
|
+
|
|
16
|
+
Run identity travels in the `run_context` context variable. Agent frameworks and your own
|
|
17
|
+
code set it with `context`; if `python_wrap.agents` is loaded, its ``run_id_var`` is read
|
|
18
|
+
as a fallback for the run id.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import contextlib
|
|
24
|
+
import contextvars
|
|
25
|
+
import copy
|
|
26
|
+
import dataclasses
|
|
27
|
+
import functools
|
|
28
|
+
import inspect
|
|
29
|
+
import json
|
|
30
|
+
import re
|
|
31
|
+
import sqlite3
|
|
32
|
+
import sys
|
|
33
|
+
from collections.abc import Awaitable, Callable, Iterable, Iterator, Mapping, Sequence
|
|
34
|
+
from contextlib import contextmanager
|
|
35
|
+
from pathlib import Path
|
|
36
|
+
from typing import Any, Literal, ParamSpec, TypeVar
|
|
37
|
+
|
|
38
|
+
from python_wrap import _core, _fork
|
|
39
|
+
from python_wrap.errors import PythonWrapError
|
|
40
|
+
from python_wrap.events import Event, subscribe
|
|
41
|
+
from python_wrap.redaction import MASK, is_sensitive
|
|
42
|
+
|
|
43
|
+
__all__ = [
|
|
44
|
+
"AuditTape",
|
|
45
|
+
"Instrumentation",
|
|
46
|
+
"Redactor",
|
|
47
|
+
"ReplayMismatch",
|
|
48
|
+
"ReplayProvider",
|
|
49
|
+
"ReplayedError",
|
|
50
|
+
"RunContext",
|
|
51
|
+
"TapeRecord",
|
|
52
|
+
"context",
|
|
53
|
+
"current_context",
|
|
54
|
+
"extract_usage",
|
|
55
|
+
"instrument",
|
|
56
|
+
"replay",
|
|
57
|
+
"run_context",
|
|
58
|
+
"traced_llm",
|
|
59
|
+
"traced_tool",
|
|
60
|
+
]
|
|
61
|
+
|
|
62
|
+
P = ParamSpec("P")
|
|
63
|
+
R = TypeVar("R")
|
|
64
|
+
|
|
65
|
+
Prices = Mapping[str, tuple[float, float]]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# --------------------------------------------------------------------------- run context
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclasses.dataclass(frozen=True)
|
|
72
|
+
class RunContext:
|
|
73
|
+
"""Who a call belongs to: the agent run, the step in it, the tool and the model.
|
|
74
|
+
|
|
75
|
+
Attributes:
|
|
76
|
+
run_id: Identifier of the run (any string), or None.
|
|
77
|
+
step: Step number within the run, or None.
|
|
78
|
+
tool: Name of the tool being executed, or None.
|
|
79
|
+
model: Name of the model being called, or None.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
run_id: str | None = None
|
|
83
|
+
step: int | None = None
|
|
84
|
+
tool: str | None = None
|
|
85
|
+
model: str | None = None
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
#: Current `RunContext`. Set it directly (``run_context.set(...)``) or use `context`.
|
|
89
|
+
run_context: contextvars.ContextVar[RunContext] = contextvars.ContextVar(
|
|
90
|
+
"python_wrap_genai_run_context",
|
|
91
|
+
default=RunContext(), # noqa: B039 - frozen dataclass
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
_UNSET: Any = object()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@contextmanager
|
|
98
|
+
def context(
|
|
99
|
+
*,
|
|
100
|
+
run_id: str | None = _UNSET,
|
|
101
|
+
step: int | None = _UNSET,
|
|
102
|
+
tool: str | None = _UNSET,
|
|
103
|
+
model: str | None = _UNSET,
|
|
104
|
+
) -> Iterator[RunContext]:
|
|
105
|
+
"""Set fields of the current `RunContext` for a ``with`` block.
|
|
106
|
+
|
|
107
|
+
Fields you do not pass keep their current value.
|
|
108
|
+
|
|
109
|
+
Example:
|
|
110
|
+
>>> with context(run_id="r1", step=2) as ctx:
|
|
111
|
+
... assert current_context().run_id == "r1"
|
|
112
|
+
"""
|
|
113
|
+
changes: dict[str, Any] = {
|
|
114
|
+
key: value
|
|
115
|
+
for key, value in (("run_id", run_id), ("step", step), ("tool", tool), ("model", model))
|
|
116
|
+
if value is not _UNSET
|
|
117
|
+
}
|
|
118
|
+
new = dataclasses.replace(run_context.get(), **changes)
|
|
119
|
+
token = run_context.set(new)
|
|
120
|
+
try:
|
|
121
|
+
yield new
|
|
122
|
+
finally:
|
|
123
|
+
run_context.reset(token)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def current_context() -> RunContext:
|
|
127
|
+
"""The active `RunContext`; the run id falls back to ``python_wrap.agents.run_id_var``.
|
|
128
|
+
|
|
129
|
+
That module is only consulted if something else already imported it.
|
|
130
|
+
"""
|
|
131
|
+
ctx = run_context.get()
|
|
132
|
+
if ctx.run_id is None:
|
|
133
|
+
module = sys.modules.get("python_wrap.agents")
|
|
134
|
+
var = getattr(module, "run_id_var", None)
|
|
135
|
+
if var is not None:
|
|
136
|
+
with contextlib.suppress(Exception):
|
|
137
|
+
found = var.get(None)
|
|
138
|
+
if found is not None:
|
|
139
|
+
return dataclasses.replace(ctx, run_id=str(found))
|
|
140
|
+
return ctx
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
# --------------------------------------------------------------------------- redaction
|
|
144
|
+
|
|
145
|
+
_EMAIL = re.compile(r"\b[\w.+-]+@[\w-]+(?:\.[\w-]+)+\b")
|
|
146
|
+
_CARD = re.compile(r"(?<![\w-])(?:\d[ -]?){12,18}\d(?![\w-])")
|
|
147
|
+
_BUILTIN_SECRETS: tuple[re.Pattern[str], ...] = (
|
|
148
|
+
re.compile(
|
|
149
|
+
r"-----BEGIN [A-Z ]*PRIVATE KEY-----.*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)", re.S
|
|
150
|
+
),
|
|
151
|
+
re.compile(r"\beyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]{4,}"),
|
|
152
|
+
re.compile(r"\b(?:sk|pk|rk)[-_][A-Za-z0-9_-]{16,}"),
|
|
153
|
+
re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
|
|
154
|
+
re.compile(r"\bgh[pousr]_[A-Za-z0-9]{20,}"),
|
|
155
|
+
re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{10,}"),
|
|
156
|
+
)
|
|
157
|
+
_BEARER = re.compile(r"(?i)\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]{8,}")
|
|
158
|
+
_ASSIGNMENT = re.compile(
|
|
159
|
+
r"(?i)\b(password|passwd|secret|api[_-]?key|token|authorization)(\s*[=:]\s*)(?!\*\*\*|bearer\b|basic\b|\[redacted)[^\s,;'\"}]+"
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _luhn(digits: str) -> bool:
|
|
164
|
+
total = 0
|
|
165
|
+
for index, char in enumerate(reversed(digits)):
|
|
166
|
+
number = int(char)
|
|
167
|
+
if index % 2:
|
|
168
|
+
number *= 2
|
|
169
|
+
if number > 9:
|
|
170
|
+
number -= 9
|
|
171
|
+
total += number
|
|
172
|
+
return total % 10 == 0
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class Redactor:
|
|
176
|
+
"""Scrub values before they reach logs, traces or an audit tape.
|
|
177
|
+
|
|
178
|
+
Strings are scanned for secrets (private keys, JWTs, provider key shapes, bearer
|
|
179
|
+
tokens, ``password=...`` assignments), email addresses and card numbers (Luhn
|
|
180
|
+
checked), plus your own ``patterns``. Mappings mask the value of any sensitive key
|
|
181
|
+
(see `python_wrap.redaction.is_sensitive`). Anything that is not JSON-shaped is
|
|
182
|
+
converted first (dataclasses, ``model_dump()``/``to_dict()`` objects, else ``repr``),
|
|
183
|
+
and strings longer than ``max_chars`` are cut after scrubbing.
|
|
184
|
+
|
|
185
|
+
Args:
|
|
186
|
+
fragments: Sensitive key-name fragments; defaults to `DEFAULT_REDACT`.
|
|
187
|
+
patterns: Extra regular expressions (strings or compiled); matches are masked.
|
|
188
|
+
max_chars: Longest string kept (>= 1).
|
|
189
|
+
max_items: Longest list/tuple/set kept (>= 1); the rest is dropped with a marker.
|
|
190
|
+
max_depth: Container levels walked; deeper values are masked.
|
|
191
|
+
builtin: Set False to disable the built-in text patterns (key names still apply).
|
|
192
|
+
mask: Replacement for key-based masks.
|
|
193
|
+
|
|
194
|
+
Example:
|
|
195
|
+
>>> Redactor()({"note": "mail bob@example.com", "api_key": "k"})
|
|
196
|
+
{'note': 'mail [redacted:email]', 'api_key': '***'}
|
|
197
|
+
"""
|
|
198
|
+
|
|
199
|
+
def __init__(
|
|
200
|
+
self,
|
|
201
|
+
*,
|
|
202
|
+
fragments: Iterable[str] | None = None,
|
|
203
|
+
patterns: Iterable[str | re.Pattern[str]] = (),
|
|
204
|
+
max_chars: int = 2000,
|
|
205
|
+
max_items: int = 100,
|
|
206
|
+
max_depth: int = 12,
|
|
207
|
+
builtin: bool = True,
|
|
208
|
+
mask: str = MASK,
|
|
209
|
+
) -> None:
|
|
210
|
+
if max_chars < 1 or max_items < 1 or max_depth < 0:
|
|
211
|
+
raise ValueError("max_chars and max_items must be >= 1 and max_depth >= 0")
|
|
212
|
+
self.fragments = None if fragments is None else tuple(fragments)
|
|
213
|
+
self.patterns = tuple(re.compile(p) if isinstance(p, str) else p for p in patterns)
|
|
214
|
+
self.max_chars, self.max_items, self.max_depth = max_chars, max_items, max_depth
|
|
215
|
+
self.builtin, self.mask = builtin, mask
|
|
216
|
+
|
|
217
|
+
def scrub_text(self, text: str) -> str:
|
|
218
|
+
"""Mask secrets, emails, card numbers and custom patterns in ``text``; then truncate."""
|
|
219
|
+
if self.builtin:
|
|
220
|
+
for pattern in _BUILTIN_SECRETS:
|
|
221
|
+
text = pattern.sub("[redacted:secret]", text)
|
|
222
|
+
text = _BEARER.sub(lambda m: f"{m.group(1)} [redacted:secret]", text)
|
|
223
|
+
text = _ASSIGNMENT.sub(lambda m: f"{m.group(1)}{m.group(2)}[redacted:secret]", text)
|
|
224
|
+
text = _EMAIL.sub("[redacted:email]", text)
|
|
225
|
+
text = _CARD.sub(
|
|
226
|
+
lambda m: "[redacted:card]" if _luhn(re.sub(r"\D", "", m.group(0))) else m.group(0),
|
|
227
|
+
text,
|
|
228
|
+
)
|
|
229
|
+
for pattern in self.patterns:
|
|
230
|
+
text = pattern.sub("[redacted]", text)
|
|
231
|
+
if len(text) > self.max_chars:
|
|
232
|
+
text = f"{text[: self.max_chars]}...[truncated {len(text) - self.max_chars} chars]"
|
|
233
|
+
return text
|
|
234
|
+
|
|
235
|
+
def __call__(self, value: Any) -> Any:
|
|
236
|
+
"""Return a scrubbed, JSON-shaped copy of ``value``."""
|
|
237
|
+
return self._walk(value, 0, frozenset())
|
|
238
|
+
|
|
239
|
+
def _walk(self, value: Any, depth: int, ancestors: frozenset[int]) -> Any:
|
|
240
|
+
if value is None or isinstance(value, (bool, int, float)):
|
|
241
|
+
return value
|
|
242
|
+
if isinstance(value, str):
|
|
243
|
+
return self.scrub_text(value)
|
|
244
|
+
if isinstance(value, (bytes, bytearray)):
|
|
245
|
+
return f"<{len(value)} bytes>"
|
|
246
|
+
if not isinstance(value, (Mapping, list, tuple, set, frozenset)):
|
|
247
|
+
converted = _convert(value)
|
|
248
|
+
if converted is _UNSET:
|
|
249
|
+
return self.scrub_text(repr(value))
|
|
250
|
+
value = converted
|
|
251
|
+
if isinstance(value, str):
|
|
252
|
+
return self.scrub_text(value)
|
|
253
|
+
if depth > self.max_depth or id(value) in ancestors:
|
|
254
|
+
return self.mask
|
|
255
|
+
ancestors = ancestors | {id(value)}
|
|
256
|
+
if isinstance(value, Mapping):
|
|
257
|
+
out: dict[str, Any] = {}
|
|
258
|
+
for key, item in value.items():
|
|
259
|
+
name = str(key)
|
|
260
|
+
masked = is_sensitive(name, self.fragments)
|
|
261
|
+
out[name] = self.mask if masked else self._walk(item, depth + 1, ancestors)
|
|
262
|
+
return out
|
|
263
|
+
items = list(value)
|
|
264
|
+
kept = [self._walk(item, depth + 1, ancestors) for item in items[: self.max_items]]
|
|
265
|
+
if len(items) > self.max_items:
|
|
266
|
+
kept.append(f"...[{len(items) - self.max_items} more items]")
|
|
267
|
+
return kept
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _convert(value: Any) -> Any:
|
|
271
|
+
"""Turn a known object shape into plain data; `_UNSET` when it has none."""
|
|
272
|
+
if dataclasses.is_dataclass(value) and not isinstance(value, type):
|
|
273
|
+
return {f.name: getattr(value, f.name, None) for f in dataclasses.fields(value)}
|
|
274
|
+
for method in ("model_dump", "to_dict", "dict"):
|
|
275
|
+
func = getattr(value, method, None)
|
|
276
|
+
if callable(func):
|
|
277
|
+
with contextlib.suppress(Exception):
|
|
278
|
+
result = func()
|
|
279
|
+
if isinstance(result, Mapping):
|
|
280
|
+
return dict(result)
|
|
281
|
+
return _UNSET
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
# --------------------------------------------------------------------------- usage and cost
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _field(source: Any, name: str) -> Any:
|
|
288
|
+
if isinstance(source, Mapping):
|
|
289
|
+
return source.get(name)
|
|
290
|
+
return getattr(source, name, None)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _count(value: Any) -> int | None:
|
|
294
|
+
return value if isinstance(value, int) and not isinstance(value, bool) else None
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def extract_usage(
|
|
298
|
+
response: Any, usage: Callable[[Any], tuple[int | None, int | None]] | None = None
|
|
299
|
+
) -> tuple[int | None, int | None]:
|
|
300
|
+
"""Read ``(input_tokens, output_tokens)`` from a provider response without any SDK.
|
|
301
|
+
|
|
302
|
+
Understands ``usage.input_tokens/output_tokens`` (Anthropic style) and
|
|
303
|
+
``usage.prompt_tokens/completion_tokens`` (OpenAI style) on objects or dicts, and a
|
|
304
|
+
``usage`` mapping at the top level. A ``usage`` callable you supply wins.
|
|
305
|
+
|
|
306
|
+
Example:
|
|
307
|
+
>>> extract_usage({"usage": {"prompt_tokens": 10, "completion_tokens": 3}})
|
|
308
|
+
(10, 3)
|
|
309
|
+
"""
|
|
310
|
+
if usage is not None:
|
|
311
|
+
return usage(response)
|
|
312
|
+
block = _field(response, "usage")
|
|
313
|
+
if block is None:
|
|
314
|
+
return None, None
|
|
315
|
+
first = _count(_field(block, "input_tokens"))
|
|
316
|
+
second = _count(_field(block, "output_tokens"))
|
|
317
|
+
if first is None:
|
|
318
|
+
first = _count(_field(block, "prompt_tokens"))
|
|
319
|
+
if second is None:
|
|
320
|
+
second = _count(_field(block, "completion_tokens"))
|
|
321
|
+
return first, second
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _cost(
|
|
325
|
+
prices: Prices | None, model: str | None, tin: int | None, tout: int | None
|
|
326
|
+
) -> float | None:
|
|
327
|
+
if not prices or model is None or (tin is None and tout is None):
|
|
328
|
+
return None
|
|
329
|
+
key = (
|
|
330
|
+
model
|
|
331
|
+
if model in prices
|
|
332
|
+
else max((k for k in prices if model.startswith(k)), key=len, default=None)
|
|
333
|
+
)
|
|
334
|
+
if key is None:
|
|
335
|
+
return None
|
|
336
|
+
per_in, per_out = prices[key]
|
|
337
|
+
return ((tin or 0) * per_in + (tout or 0) * per_out) / 1_000_000
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
# --------------------------------------------------------------------------- audit tape
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
@dataclasses.dataclass(frozen=True)
|
|
344
|
+
class TapeRecord:
|
|
345
|
+
"""One recorded call.
|
|
346
|
+
|
|
347
|
+
Attributes:
|
|
348
|
+
seq: 1-based position in the tape.
|
|
349
|
+
timestamp: Wall-clock start time (seconds since the epoch).
|
|
350
|
+
kind: ``"llm"`` or ``"tool"``.
|
|
351
|
+
name: Tool name, or model name for LLM calls (falls back to the function name).
|
|
352
|
+
function: Qualified name of the traced function.
|
|
353
|
+
run_id / step / model / tool: The `RunContext` at call time.
|
|
354
|
+
status: ``"ok"`` or ``"error"``.
|
|
355
|
+
input: Redacted arguments as a dict (None when content capture is off).
|
|
356
|
+
output: Redacted result (None when content capture is off or the call failed).
|
|
357
|
+
error: ``{"type": ..., "message": ...}`` for a failed call (message only with content).
|
|
358
|
+
input_tokens / output_tokens / cost / latency: Metrics.
|
|
359
|
+
attempts: Failed attempts of an inner `retry`: dicts with ``number``, ``exception``,
|
|
360
|
+
``next_delay`` and, when available, ``duration``.
|
|
361
|
+
content: Whether input/output were captured.
|
|
362
|
+
"""
|
|
363
|
+
|
|
364
|
+
seq: int
|
|
365
|
+
timestamp: float
|
|
366
|
+
kind: str
|
|
367
|
+
name: str
|
|
368
|
+
function: str
|
|
369
|
+
run_id: str | None = None
|
|
370
|
+
step: int | None = None
|
|
371
|
+
model: str | None = None
|
|
372
|
+
tool: str | None = None
|
|
373
|
+
status: str = "ok"
|
|
374
|
+
input: Any = None
|
|
375
|
+
output: Any = None
|
|
376
|
+
error: dict[str, str] | None = None
|
|
377
|
+
input_tokens: int | None = None
|
|
378
|
+
output_tokens: int | None = None
|
|
379
|
+
cost: float | None = None
|
|
380
|
+
latency: float = 0.0
|
|
381
|
+
attempts: tuple[dict[str, Any], ...] = ()
|
|
382
|
+
content: bool = False
|
|
383
|
+
|
|
384
|
+
def to_dict(self) -> dict[str, Any]:
|
|
385
|
+
"""A JSON-serialisable dict."""
|
|
386
|
+
data = dataclasses.asdict(self)
|
|
387
|
+
data["attempts"] = list(self.attempts)
|
|
388
|
+
return data
|
|
389
|
+
|
|
390
|
+
@classmethod
|
|
391
|
+
def from_dict(cls, data: Mapping[str, Any]) -> TapeRecord:
|
|
392
|
+
"""Rebuild a record from `to_dict` output; unknown keys are ignored."""
|
|
393
|
+
names = {f.name for f in dataclasses.fields(cls)}
|
|
394
|
+
values = {k: v for k, v in data.items() if k in names}
|
|
395
|
+
values["attempts"] = tuple(values.get("attempts") or ())
|
|
396
|
+
return cls(**values)
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
class AuditTape:
|
|
400
|
+
"""An ordered, redacted log of LLM and tool calls, in memory, JSONL or SQLite.
|
|
401
|
+
|
|
402
|
+
Args:
|
|
403
|
+
path: ``None`` keeps records in memory. Otherwise a file: ``.db``, ``.sqlite`` or
|
|
404
|
+
``.sqlite3`` selects SQLite, anything else JSONL (one JSON object per line).
|
|
405
|
+
An existing file is appended to and its records are readable.
|
|
406
|
+
capture_content: Keep redacted inputs and outputs. The tape is an explicit sink and
|
|
407
|
+
replay needs results, so this defaults to True; pass False for metadata only.
|
|
408
|
+
redactor: Applied to inputs, outputs and error messages recorded here, on top of
|
|
409
|
+
whatever the caller already scrubbed.
|
|
410
|
+
max_records: For a memory tape, keep only the newest N records.
|
|
411
|
+
|
|
412
|
+
Thread-safe. Use `close` (or ``with``) to release a SQLite connection.
|
|
413
|
+
|
|
414
|
+
Example:
|
|
415
|
+
>>> tape = AuditTape()
|
|
416
|
+
>>> len(tape)
|
|
417
|
+
0
|
|
418
|
+
"""
|
|
419
|
+
|
|
420
|
+
def __init__(
|
|
421
|
+
self,
|
|
422
|
+
path: str | Path | None = None,
|
|
423
|
+
*,
|
|
424
|
+
capture_content: bool = True,
|
|
425
|
+
redactor: Redactor | None = None,
|
|
426
|
+
max_records: int | None = None,
|
|
427
|
+
) -> None:
|
|
428
|
+
if max_records is not None and max_records < 1:
|
|
429
|
+
raise ValueError("max_records must be positive")
|
|
430
|
+
self.capture_content = capture_content
|
|
431
|
+
self.redactor = redactor
|
|
432
|
+
self.max_records = max_records
|
|
433
|
+
self.path = None if path is None else Path(path)
|
|
434
|
+
self._lock = _fork.ForkSafeLock()
|
|
435
|
+
self._memory: list[TapeRecord] = []
|
|
436
|
+
self._seq = 0
|
|
437
|
+
self._db: sqlite3.Connection | None = None
|
|
438
|
+
self.backend: Literal["memory", "jsonl", "sqlite"] = "memory"
|
|
439
|
+
if self.path is not None:
|
|
440
|
+
if self.path.suffix.lower() in (".db", ".sqlite", ".sqlite3"):
|
|
441
|
+
self.backend = "sqlite"
|
|
442
|
+
self._db = sqlite3.connect(self.path, check_same_thread=False)
|
|
443
|
+
self._db.execute(
|
|
444
|
+
"CREATE TABLE IF NOT EXISTS tape "
|
|
445
|
+
"(seq INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT NOT NULL)"
|
|
446
|
+
)
|
|
447
|
+
self._db.commit()
|
|
448
|
+
else:
|
|
449
|
+
self.backend = "jsonl"
|
|
450
|
+
self._seq = len(self._read())
|
|
451
|
+
|
|
452
|
+
def _read(self) -> list[TapeRecord]:
|
|
453
|
+
if self.backend == "sqlite" and self._db is not None:
|
|
454
|
+
rows = self._db.execute("SELECT data FROM tape ORDER BY seq").fetchall()
|
|
455
|
+
return [TapeRecord.from_dict(json.loads(row[0])) for row in rows]
|
|
456
|
+
if self.backend == "jsonl" and self.path is not None and self.path.exists():
|
|
457
|
+
with self.path.open(encoding="utf-8") as handle:
|
|
458
|
+
return [TapeRecord.from_dict(json.loads(line)) for line in handle if line.strip()]
|
|
459
|
+
return list(self._memory)
|
|
460
|
+
|
|
461
|
+
def record(self, **fields: Any) -> TapeRecord:
|
|
462
|
+
"""Append a call. Takes `TapeRecord` fields (``seq`` is assigned); returns the record.
|
|
463
|
+
|
|
464
|
+
Content is dropped when ``capture_content`` is False and scrubbed with the tape's
|
|
465
|
+
``redactor`` if there is one.
|
|
466
|
+
"""
|
|
467
|
+
fields.pop("seq", None)
|
|
468
|
+
if not self.capture_content:
|
|
469
|
+
fields.update(input=None, output=None, content=False)
|
|
470
|
+
if fields.get("error"):
|
|
471
|
+
fields["error"] = {"type": fields["error"].get("type", "")}
|
|
472
|
+
elif self.redactor is not None:
|
|
473
|
+
for key in ("input", "output"):
|
|
474
|
+
if fields.get(key) is not None:
|
|
475
|
+
fields[key] = self.redactor(fields[key])
|
|
476
|
+
if fields.get("error"):
|
|
477
|
+
fields["error"] = {k: self.redactor(v) for k, v in fields["error"].items()}
|
|
478
|
+
with self._lock:
|
|
479
|
+
self._seq += 1
|
|
480
|
+
entry = TapeRecord(seq=self._seq, **fields)
|
|
481
|
+
if self.backend == "sqlite" and self._db is not None:
|
|
482
|
+
self._db.execute(
|
|
483
|
+
"INSERT INTO tape (data) VALUES (?)", (json.dumps(entry.to_dict()),)
|
|
484
|
+
)
|
|
485
|
+
self._db.commit()
|
|
486
|
+
elif self.backend == "jsonl" and self.path is not None:
|
|
487
|
+
with self.path.open("a", encoding="utf-8") as handle:
|
|
488
|
+
handle.write(json.dumps(entry.to_dict()) + "\n")
|
|
489
|
+
else:
|
|
490
|
+
self._memory.append(entry)
|
|
491
|
+
if self.max_records is not None and len(self._memory) > self.max_records:
|
|
492
|
+
del self._memory[: len(self._memory) - self.max_records]
|
|
493
|
+
return entry
|
|
494
|
+
|
|
495
|
+
def records(self) -> list[TapeRecord]:
|
|
496
|
+
"""All records, oldest first."""
|
|
497
|
+
with self._lock:
|
|
498
|
+
return self._read()
|
|
499
|
+
|
|
500
|
+
def __len__(self) -> int:
|
|
501
|
+
with self._lock:
|
|
502
|
+
return len(self._read())
|
|
503
|
+
|
|
504
|
+
def __iter__(self) -> Iterator[TapeRecord]:
|
|
505
|
+
return iter(self.records())
|
|
506
|
+
|
|
507
|
+
def clear(self) -> None:
|
|
508
|
+
"""Delete every record (a file backend is emptied)."""
|
|
509
|
+
with self._lock:
|
|
510
|
+
self._memory.clear()
|
|
511
|
+
self._seq = 0
|
|
512
|
+
if self.backend == "sqlite" and self._db is not None:
|
|
513
|
+
self._db.execute("DELETE FROM tape")
|
|
514
|
+
self._db.commit()
|
|
515
|
+
elif self.backend == "jsonl" and self.path is not None:
|
|
516
|
+
self.path.write_text("", encoding="utf-8")
|
|
517
|
+
|
|
518
|
+
def close(self) -> None:
|
|
519
|
+
"""Release the SQLite connection, if any. Safe to call twice."""
|
|
520
|
+
with self._lock:
|
|
521
|
+
if self._db is not None:
|
|
522
|
+
self._db.close()
|
|
523
|
+
self._db = None
|
|
524
|
+
|
|
525
|
+
def __enter__(self) -> AuditTape:
|
|
526
|
+
return self
|
|
527
|
+
|
|
528
|
+
def __exit__(self, *exc: object) -> None:
|
|
529
|
+
self.close()
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
# --------------------------------------------------------------------------- instrumentation
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
@dataclasses.dataclass(frozen=True)
|
|
536
|
+
class _Settings:
|
|
537
|
+
capture_content: bool = False
|
|
538
|
+
redactor: Redactor = dataclasses.field(default_factory=Redactor)
|
|
539
|
+
prices: Prices | None = None
|
|
540
|
+
tape: AuditTape | None = None
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
_settings_lock = _fork.ForkSafeLock()
|
|
544
|
+
_active: _Settings | None = None
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
class Instrumentation:
|
|
548
|
+
"""Handle returned by `instrument`; `close()` restores the previous defaults."""
|
|
549
|
+
|
|
550
|
+
def __init__(self, settings: _Settings, previous: _Settings | None) -> None:
|
|
551
|
+
self.settings = settings
|
|
552
|
+
self._previous = previous
|
|
553
|
+
self.closed = False
|
|
554
|
+
#: The OpenTelemetry adapter subscription, or None when OTel is absent or disabled.
|
|
555
|
+
self.otel: Any = None
|
|
556
|
+
|
|
557
|
+
def close(self) -> None:
|
|
558
|
+
global _active
|
|
559
|
+
if self.closed:
|
|
560
|
+
return
|
|
561
|
+
self.closed = True
|
|
562
|
+
if self.otel is not None:
|
|
563
|
+
self.otel.close()
|
|
564
|
+
with _settings_lock:
|
|
565
|
+
if _active is self.settings:
|
|
566
|
+
_active = self._previous
|
|
567
|
+
|
|
568
|
+
def __enter__(self) -> Instrumentation:
|
|
569
|
+
return self
|
|
570
|
+
|
|
571
|
+
def __exit__(self, *exc: object) -> None:
|
|
572
|
+
self.close()
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def instrument(
|
|
576
|
+
*,
|
|
577
|
+
capture_content: bool = False,
|
|
578
|
+
redactor: Redactor | None = None,
|
|
579
|
+
prices: Prices | None = None,
|
|
580
|
+
tape: AuditTape | None = None,
|
|
581
|
+
otel: bool = True,
|
|
582
|
+
tracer: Any = None,
|
|
583
|
+
tracer_provider: Any = None,
|
|
584
|
+
) -> Instrumentation:
|
|
585
|
+
"""Set process-wide defaults for `traced_llm` and `traced_tool`, and emit OTel spans.
|
|
586
|
+
|
|
587
|
+
Args:
|
|
588
|
+
capture_content: Put redacted inputs and outputs in events and spans. Off by
|
|
589
|
+
default: events then carry metadata only.
|
|
590
|
+
redactor: Scrubbing rules for captured content; a default `Redactor` if omitted.
|
|
591
|
+
prices: ``{model: (usd_per_million_input_tokens, usd_per_million_output_tokens)}``.
|
|
592
|
+
A model matches exactly or by longest key prefix.
|
|
593
|
+
tape: An `AuditTape` that records every traced call.
|
|
594
|
+
otel: Create OpenTelemetry GenAI spans when ``opentelemetry`` is installed; silently
|
|
595
|
+
nothing otherwise.
|
|
596
|
+
tracer: A tracer to use instead of the global provider's.
|
|
597
|
+
tracer_provider: A tracer provider to use instead of the global one.
|
|
598
|
+
|
|
599
|
+
Returns:
|
|
600
|
+
An `Instrumentation` handle; use it as a context manager or call `close()`.
|
|
601
|
+
"""
|
|
602
|
+
global _active
|
|
603
|
+
settings = _Settings(capture_content, redactor or Redactor(), prices, tape)
|
|
604
|
+
with _settings_lock:
|
|
605
|
+
previous = _active
|
|
606
|
+
_active = settings
|
|
607
|
+
handle = Instrumentation(settings, previous)
|
|
608
|
+
if otel:
|
|
609
|
+
from python_wrap import observability
|
|
610
|
+
|
|
611
|
+
handle.otel = observability.enable_genai(tracer=tracer, tracer_provider=tracer_provider)
|
|
612
|
+
return handle
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def _settings() -> _Settings:
|
|
616
|
+
return _active or _Settings()
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
# Retry events seen while a traced call runs are attached to its record. The listener is
|
|
620
|
+
# subscribed only while at least one traced call is in flight.
|
|
621
|
+
_collectors: contextvars.ContextVar[tuple[list[dict[str, Any]], ...]] = contextvars.ContextVar(
|
|
622
|
+
"python_wrap_genai_collectors", default=()
|
|
623
|
+
)
|
|
624
|
+
_collect_lock = _fork.ForkSafeLock()
|
|
625
|
+
_collect_users = 0
|
|
626
|
+
_collect_off: Callable[[], None] | None = None
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
def _collect(event: Event) -> None:
|
|
630
|
+
if event.name != "retry.attempt_failed":
|
|
631
|
+
return
|
|
632
|
+
exc = event.fields.get("exception")
|
|
633
|
+
entry = {
|
|
634
|
+
"number": event.fields.get("attempt"),
|
|
635
|
+
"exception": type(exc).__qualname__ if exc is not None else "rejected_result",
|
|
636
|
+
"next_delay": event.fields.get("next_delay"),
|
|
637
|
+
}
|
|
638
|
+
for sink in _collectors.get():
|
|
639
|
+
sink.append(entry)
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
def _collect_enter() -> None:
|
|
643
|
+
global _collect_users, _collect_off
|
|
644
|
+
with _collect_lock:
|
|
645
|
+
_collect_users += 1
|
|
646
|
+
if _collect_users == 1:
|
|
647
|
+
_collect_off = subscribe(_collect)
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
def _collect_exit() -> None:
|
|
651
|
+
global _collect_users, _collect_off
|
|
652
|
+
with _collect_lock:
|
|
653
|
+
_collect_users -= 1
|
|
654
|
+
if _collect_users == 0 and _collect_off is not None:
|
|
655
|
+
_collect_off()
|
|
656
|
+
_collect_off = None
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def _bind(
|
|
660
|
+
func: Callable[..., Any], args: tuple[Any, ...], kwargs: dict[str, Any]
|
|
661
|
+
) -> dict[str, Any]:
|
|
662
|
+
try:
|
|
663
|
+
bound = inspect.signature(func).bind(*args, **kwargs)
|
|
664
|
+
except (TypeError, ValueError):
|
|
665
|
+
return {"args": list(args), "kwargs": dict(kwargs)}
|
|
666
|
+
named = dict(bound.arguments)
|
|
667
|
+
if named and next(iter(named)) in ("self", "cls"):
|
|
668
|
+
del named[next(iter(named))]
|
|
669
|
+
return named
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
def _history(exc: BaseException, collected: list[dict[str, Any]]) -> tuple[dict[str, Any], ...]:
|
|
673
|
+
from python_wrap.retry import attempt_history
|
|
674
|
+
|
|
675
|
+
records = attempt_history(exc)
|
|
676
|
+
if records:
|
|
677
|
+
return tuple(
|
|
678
|
+
{
|
|
679
|
+
"number": r.number,
|
|
680
|
+
"exception": r.exception,
|
|
681
|
+
"next_delay": r.next_delay,
|
|
682
|
+
"duration": r.duration,
|
|
683
|
+
}
|
|
684
|
+
for r in records
|
|
685
|
+
)
|
|
686
|
+
return tuple(collected)
|
|
687
|
+
|
|
688
|
+
|
|
689
|
+
def _finish(
|
|
690
|
+
kind: Literal["llm", "tool"],
|
|
691
|
+
func: Callable[..., Any],
|
|
692
|
+
name: str,
|
|
693
|
+
model: str | None,
|
|
694
|
+
system: str | None,
|
|
695
|
+
options: dict[str, Any],
|
|
696
|
+
call: tuple[tuple[Any, ...], dict[str, Any]],
|
|
697
|
+
ctx: RunContext,
|
|
698
|
+
started: float,
|
|
699
|
+
latency: float,
|
|
700
|
+
collected: list[dict[str, Any]],
|
|
701
|
+
result: Any,
|
|
702
|
+
exc: BaseException | None,
|
|
703
|
+
) -> None:
|
|
704
|
+
"""Build the event and tape record. Never raises."""
|
|
705
|
+
try:
|
|
706
|
+
base = _settings()
|
|
707
|
+
capture = (
|
|
708
|
+
base.capture_content
|
|
709
|
+
if options["capture_content"] is None
|
|
710
|
+
else options["capture_content"]
|
|
711
|
+
)
|
|
712
|
+
redactor: Redactor = options["redactor"] or base.redactor
|
|
713
|
+
prices = options["prices"] or base.prices
|
|
714
|
+
tape: AuditTape | None = options["tape"] if options["tape"] is not None else base.tape
|
|
715
|
+
tin = tout = None
|
|
716
|
+
if exc is None and kind == "llm":
|
|
717
|
+
tin, tout = extract_usage(result, options["usage"])
|
|
718
|
+
if model is None:
|
|
719
|
+
found = _field(result, "model")
|
|
720
|
+
model = found if isinstance(found, str) else None
|
|
721
|
+
cost = _cost(prices, model, tin, tout) if kind == "llm" else None
|
|
722
|
+
attempts = _history(exc, collected) if exc is not None else tuple(collected)
|
|
723
|
+
error_type = None if exc is None else type(exc).__qualname__
|
|
724
|
+
need_content = capture or (tape is not None and tape.capture_content)
|
|
725
|
+
content_in = content_out = error_message = None
|
|
726
|
+
if need_content:
|
|
727
|
+
content_in = redactor(_bind(func, *call))
|
|
728
|
+
if exc is None:
|
|
729
|
+
content_out = redactor(result)
|
|
730
|
+
else:
|
|
731
|
+
error_message = redactor.scrub_text(str(exc))
|
|
732
|
+
fields: dict[str, Any] = {
|
|
733
|
+
"kind": kind,
|
|
734
|
+
"run_id": ctx.run_id,
|
|
735
|
+
"step": ctx.step,
|
|
736
|
+
"tool": name if kind == "tool" else ctx.tool,
|
|
737
|
+
"model": model,
|
|
738
|
+
"system": system,
|
|
739
|
+
"input_tokens": tin,
|
|
740
|
+
"output_tokens": tout,
|
|
741
|
+
"cost": cost,
|
|
742
|
+
"latency": latency,
|
|
743
|
+
"started": started,
|
|
744
|
+
"status": "ok" if exc is None else "error",
|
|
745
|
+
"error_type": error_type,
|
|
746
|
+
"attempts": len(attempts) or None,
|
|
747
|
+
}
|
|
748
|
+
if capture:
|
|
749
|
+
fields.update(input=content_in, output=content_out, error=error_message)
|
|
750
|
+
if kind == "tool":
|
|
751
|
+
_core.emit("genai.tool_call", _core.qualname(func), **fields)
|
|
752
|
+
else:
|
|
753
|
+
_core.emit("genai.llm_call", _core.qualname(func), **fields)
|
|
754
|
+
if tape is not None:
|
|
755
|
+
tape.record(
|
|
756
|
+
timestamp=started,
|
|
757
|
+
kind=kind,
|
|
758
|
+
name=name,
|
|
759
|
+
function=_core.qualname(func),
|
|
760
|
+
run_id=ctx.run_id,
|
|
761
|
+
step=ctx.step,
|
|
762
|
+
model=model,
|
|
763
|
+
tool=fields["tool"],
|
|
764
|
+
status=fields["status"],
|
|
765
|
+
input=content_in,
|
|
766
|
+
output=content_out,
|
|
767
|
+
error=None
|
|
768
|
+
if exc is None
|
|
769
|
+
else {"type": error_type or "", "message": error_message or ""},
|
|
770
|
+
input_tokens=tin,
|
|
771
|
+
output_tokens=tout,
|
|
772
|
+
cost=cost,
|
|
773
|
+
latency=latency,
|
|
774
|
+
attempts=attempts,
|
|
775
|
+
content=need_content,
|
|
776
|
+
)
|
|
777
|
+
except Exception:
|
|
778
|
+
_core.get_logger().exception("python_wrap.genai failed to record a call")
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
def _wrap(
|
|
782
|
+
kind: Literal["llm", "tool"],
|
|
783
|
+
name: str | None,
|
|
784
|
+
model: str | None,
|
|
785
|
+
system: str | None,
|
|
786
|
+
options: dict[str, Any],
|
|
787
|
+
) -> Callable[[Callable[P, R]], Callable[P, R]]:
|
|
788
|
+
def decorator(func: Callable[P, R]) -> Callable[P, R]:
|
|
789
|
+
label = name or getattr(func, "__name__", None) or "call"
|
|
790
|
+
shown = label if kind == "tool" else (model or label)
|
|
791
|
+
|
|
792
|
+
def begin() -> tuple[RunContext, list[dict[str, Any]], Any, Any, float, float]:
|
|
793
|
+
ctx = current_context()
|
|
794
|
+
inner = dataclasses.replace(
|
|
795
|
+
ctx, **({"tool": label} if kind == "tool" else {"model": model or ctx.model})
|
|
796
|
+
)
|
|
797
|
+
collected: list[dict[str, Any]] = []
|
|
798
|
+
_collect_enter()
|
|
799
|
+
ctoken = _collectors.set((*_collectors.get(), collected))
|
|
800
|
+
rtoken = run_context.set(inner)
|
|
801
|
+
return ctx, collected, ctoken, rtoken, _core.wall_time(), _core.perf_counter()
|
|
802
|
+
|
|
803
|
+
def end(ctoken: Any, rtoken: Any) -> None:
|
|
804
|
+
run_context.reset(rtoken)
|
|
805
|
+
_collectors.reset(ctoken)
|
|
806
|
+
_collect_exit()
|
|
807
|
+
|
|
808
|
+
if _core.is_async(func):
|
|
809
|
+
|
|
810
|
+
@functools.wraps(func)
|
|
811
|
+
async def async_wrapper(*args: P.args, **kwargs: P.kwargs) -> Any:
|
|
812
|
+
ctx, collected, ctoken, rtoken, started, t0 = begin()
|
|
813
|
+
try:
|
|
814
|
+
result = await func(*args, **kwargs) # type: ignore[misc]
|
|
815
|
+
except BaseException as exc:
|
|
816
|
+
end(ctoken, rtoken)
|
|
817
|
+
_finish(kind, func, shown, model, system, options, (args, kwargs), ctx,
|
|
818
|
+
started, _core.perf_counter() - t0, collected, None, exc) # fmt: skip
|
|
819
|
+
raise
|
|
820
|
+
end(ctoken, rtoken)
|
|
821
|
+
_finish(kind, func, shown, model, system, options, (args, kwargs), ctx,
|
|
822
|
+
started, _core.perf_counter() - t0, collected, result, None) # fmt: skip
|
|
823
|
+
return result
|
|
824
|
+
|
|
825
|
+
return async_wrapper # type: ignore[return-value]
|
|
826
|
+
|
|
827
|
+
@functools.wraps(func)
|
|
828
|
+
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
|
|
829
|
+
ctx, collected, ctoken, rtoken, started, t0 = begin()
|
|
830
|
+
try:
|
|
831
|
+
result = func(*args, **kwargs)
|
|
832
|
+
except BaseException as exc:
|
|
833
|
+
end(ctoken, rtoken)
|
|
834
|
+
_finish(kind, func, shown, model, system, options, (args, kwargs), ctx,
|
|
835
|
+
started, _core.perf_counter() - t0, collected, None, exc) # fmt: skip
|
|
836
|
+
raise
|
|
837
|
+
end(ctoken, rtoken)
|
|
838
|
+
_finish(kind, func, shown, model, system, options, (args, kwargs), ctx,
|
|
839
|
+
started, _core.perf_counter() - t0, collected, result, None) # fmt: skip
|
|
840
|
+
return result
|
|
841
|
+
|
|
842
|
+
return wrapper
|
|
843
|
+
|
|
844
|
+
return decorator
|
|
845
|
+
|
|
846
|
+
|
|
847
|
+
def traced_llm(
|
|
848
|
+
model: str | None = None,
|
|
849
|
+
*,
|
|
850
|
+
system: str | None = None,
|
|
851
|
+
usage: Callable[[Any], tuple[int | None, int | None]] | None = None,
|
|
852
|
+
prices: Prices | None = None,
|
|
853
|
+
capture_content: bool | None = None,
|
|
854
|
+
redactor: Redactor | None = None,
|
|
855
|
+
tape: AuditTape | None = None,
|
|
856
|
+
) -> Callable[[Callable[P, R]], Callable[P, R]]:
|
|
857
|
+
"""Decorate a function that calls an LLM; publish a ``genai.llm_call`` event per call.
|
|
858
|
+
|
|
859
|
+
The event (and the `AuditTape` record) carries the run context, model, input and
|
|
860
|
+
output token counts (read from the response, see `extract_usage`), cost when a price
|
|
861
|
+
table knows the model, latency, status and the attempts of an inner `retry`. Sync and
|
|
862
|
+
async functions are supported. While the call runs, ``run_context.model`` is set.
|
|
863
|
+
|
|
864
|
+
Args:
|
|
865
|
+
model: Model name; if omitted it is read from the response's ``model`` field.
|
|
866
|
+
system: Provider name for ``gen_ai.system`` (for example ``"openai"``).
|
|
867
|
+
usage: ``response -> (input_tokens, output_tokens)`` for unusual response shapes.
|
|
868
|
+
prices: Per-call price table; falls back to `instrument`'s.
|
|
869
|
+
capture_content: Override `instrument`'s content-capture default.
|
|
870
|
+
redactor: Override the redactor.
|
|
871
|
+
tape: Record to this tape in addition to `instrument`'s.
|
|
872
|
+
|
|
873
|
+
Example:
|
|
874
|
+
>>> @traced_llm(model="demo-1")
|
|
875
|
+
... def ask(prompt: str) -> dict:
|
|
876
|
+
... return {"text": "hi", "usage": {"input_tokens": 3, "output_tokens": 1}}
|
|
877
|
+
>>> ask("hello")["text"]
|
|
878
|
+
'hi'
|
|
879
|
+
"""
|
|
880
|
+
options = {
|
|
881
|
+
"usage": usage, "prices": prices, "capture_content": capture_content,
|
|
882
|
+
"redactor": redactor, "tape": tape,
|
|
883
|
+
} # fmt: skip
|
|
884
|
+
return _wrap("llm", None, model, system, options)
|
|
885
|
+
|
|
886
|
+
|
|
887
|
+
def traced_tool(
|
|
888
|
+
name: str | None = None,
|
|
889
|
+
*,
|
|
890
|
+
capture_content: bool | None = None,
|
|
891
|
+
redactor: Redactor | None = None,
|
|
892
|
+
tape: AuditTape | None = None,
|
|
893
|
+
) -> Callable[[Callable[P, R]], Callable[P, R]]:
|
|
894
|
+
"""Decorate a tool function; publish a ``genai.tool_call`` event per call.
|
|
895
|
+
|
|
896
|
+
Same enrichment as `traced_llm` without tokens or cost. ``run_context.tool`` is set to
|
|
897
|
+
the tool name while it runs, so nested LLM calls and events know which tool they are in.
|
|
898
|
+
|
|
899
|
+
Args:
|
|
900
|
+
name: Tool name; defaults to the function's name.
|
|
901
|
+
capture_content: Override `instrument`'s content-capture default.
|
|
902
|
+
redactor: Override the redactor.
|
|
903
|
+
tape: Record to this tape in addition to `instrument`'s.
|
|
904
|
+
"""
|
|
905
|
+
options = {
|
|
906
|
+
"usage": None, "prices": None, "capture_content": capture_content,
|
|
907
|
+
"redactor": redactor, "tape": tape,
|
|
908
|
+
} # fmt: skip
|
|
909
|
+
return _wrap("tool", name, None, None, options)
|
|
910
|
+
|
|
911
|
+
|
|
912
|
+
# --------------------------------------------------------------------------- replay
|
|
913
|
+
|
|
914
|
+
|
|
915
|
+
class ReplayMismatch(PythonWrapError, AssertionError):
|
|
916
|
+
"""The code under test made a call that does not match the next recorded one."""
|
|
917
|
+
|
|
918
|
+
|
|
919
|
+
class ReplayedError(RuntimeError):
|
|
920
|
+
"""Raised by a replayed call that failed when recorded.
|
|
921
|
+
|
|
922
|
+
Attributes:
|
|
923
|
+
error_type: The original exception's qualified type name.
|
|
924
|
+
"""
|
|
925
|
+
|
|
926
|
+
def __init__(self, error_type: str, message: str = "") -> None:
|
|
927
|
+
super().__init__(f"{error_type}: {message}" if message else error_type)
|
|
928
|
+
self.error_type = error_type
|
|
929
|
+
|
|
930
|
+
|
|
931
|
+
class ReplayProvider:
|
|
932
|
+
"""Fake callables that serve a tape's recorded results; build one with `replay`.
|
|
933
|
+
|
|
934
|
+
Attributes:
|
|
935
|
+
llm: Callable serving the next recorded LLM call (any arguments).
|
|
936
|
+
allm: Async version of ``llm``.
|
|
937
|
+
calls: Records served so far, in order.
|
|
938
|
+
"""
|
|
939
|
+
|
|
940
|
+
def __init__(
|
|
941
|
+
self,
|
|
942
|
+
records: Sequence[TapeRecord],
|
|
943
|
+
*,
|
|
944
|
+
ordered: bool = True,
|
|
945
|
+
check_inputs: bool = False,
|
|
946
|
+
redactor: Redactor | None = None,
|
|
947
|
+
rebuild: Callable[[TapeRecord], Any] | None = None,
|
|
948
|
+
) -> None:
|
|
949
|
+
self._records = list(records)
|
|
950
|
+
self._used = [False] * len(self._records)
|
|
951
|
+
self._cursor = 0
|
|
952
|
+
self.ordered, self.check_inputs = ordered, check_inputs
|
|
953
|
+
self._redactor = redactor or Redactor()
|
|
954
|
+
self._rebuild = rebuild
|
|
955
|
+
self._lock = _fork.ForkSafeLock()
|
|
956
|
+
self.calls: list[TapeRecord] = []
|
|
957
|
+
|
|
958
|
+
@property
|
|
959
|
+
def remaining(self) -> list[TapeRecord]:
|
|
960
|
+
"""Recorded calls that have not been served yet."""
|
|
961
|
+
with self._lock:
|
|
962
|
+
return [r for r, used in zip(self._records, self._used, strict=True) if not used]
|
|
963
|
+
|
|
964
|
+
def assert_exhausted(self) -> None:
|
|
965
|
+
"""Raise `ReplayMismatch` if recorded calls were never made."""
|
|
966
|
+
left = self.remaining
|
|
967
|
+
if left:
|
|
968
|
+
raise ReplayMismatch(
|
|
969
|
+
f"{len(left)} recorded call(s) were never made; "
|
|
970
|
+
f"next: {left[0].kind} {left[0].name!r}"
|
|
971
|
+
)
|
|
972
|
+
|
|
973
|
+
def _serve(
|
|
974
|
+
self, kind: str, name: str | None, args: tuple[Any, ...], kwargs: dict[str, Any]
|
|
975
|
+
) -> Any:
|
|
976
|
+
want = f"{kind} {name!r}" if name else kind
|
|
977
|
+
with self._lock:
|
|
978
|
+
if self.ordered:
|
|
979
|
+
if self._cursor >= len(self._records):
|
|
980
|
+
raise ReplayMismatch(f"unexpected {want} call: the tape has no more records")
|
|
981
|
+
index = self._cursor
|
|
982
|
+
record = self._records[index]
|
|
983
|
+
if record.kind != kind or (name is not None and record.name != name):
|
|
984
|
+
raise ReplayMismatch(
|
|
985
|
+
f"call #{index + 1} is {want}, but the tape recorded "
|
|
986
|
+
f"{record.kind} {record.name!r}"
|
|
987
|
+
)
|
|
988
|
+
else:
|
|
989
|
+
index = next(
|
|
990
|
+
(
|
|
991
|
+
i
|
|
992
|
+
for i, r in enumerate(self._records)
|
|
993
|
+
if not self._used[i] and r.kind == kind and (name is None or r.name == name)
|
|
994
|
+
),
|
|
995
|
+
-1,
|
|
996
|
+
)
|
|
997
|
+
if index < 0:
|
|
998
|
+
raise ReplayMismatch(f"unexpected {want} call: no unused recorded call matches")
|
|
999
|
+
record = self._records[index]
|
|
1000
|
+
if self.check_inputs:
|
|
1001
|
+
self._compare(record, args, kwargs)
|
|
1002
|
+
if record.status == "ok" and record.output is None and not record.content:
|
|
1003
|
+
raise ReplayMismatch(
|
|
1004
|
+
f"record #{record.seq} has no captured output (tape recorded metadata only)"
|
|
1005
|
+
)
|
|
1006
|
+
self._used[index] = True
|
|
1007
|
+
self._cursor = index + 1
|
|
1008
|
+
self.calls.append(record)
|
|
1009
|
+
if record.status == "error":
|
|
1010
|
+
error = record.error or {}
|
|
1011
|
+
raise ReplayedError(error.get("type", "Error"), error.get("message", ""))
|
|
1012
|
+
if self._rebuild is not None:
|
|
1013
|
+
return self._rebuild(record)
|
|
1014
|
+
return copy.deepcopy(record.output)
|
|
1015
|
+
|
|
1016
|
+
def _compare(self, record: TapeRecord, args: tuple[Any, ...], kwargs: dict[str, Any]) -> None:
|
|
1017
|
+
recorded = record.input
|
|
1018
|
+
if not isinstance(recorded, dict):
|
|
1019
|
+
return
|
|
1020
|
+
names = list(recorded)
|
|
1021
|
+
given = {names[i]: v for i, v in enumerate(args) if i < len(names)}
|
|
1022
|
+
given.update(kwargs)
|
|
1023
|
+
scrubbed = self._redactor(given)
|
|
1024
|
+
for key, value in scrubbed.items():
|
|
1025
|
+
if key in recorded and recorded[key] != value:
|
|
1026
|
+
raise ReplayMismatch(
|
|
1027
|
+
f"call #{record.seq} ({record.name!r}): argument {key!r} was "
|
|
1028
|
+
f"{value!r}, the tape recorded {recorded[key]!r}"
|
|
1029
|
+
)
|
|
1030
|
+
|
|
1031
|
+
def llm(self, *args: Any, **kwargs: Any) -> Any:
|
|
1032
|
+
"""Serve the next recorded LLM call."""
|
|
1033
|
+
return self._serve("llm", None, args, kwargs)
|
|
1034
|
+
|
|
1035
|
+
async def allm(self, *args: Any, **kwargs: Any) -> Any:
|
|
1036
|
+
"""Async `llm`."""
|
|
1037
|
+
return self._serve("llm", None, args, kwargs)
|
|
1038
|
+
|
|
1039
|
+
def tool(self, name: str) -> Callable[..., Any]:
|
|
1040
|
+
"""A callable serving the recorded calls of tool ``name``."""
|
|
1041
|
+
|
|
1042
|
+
def call(*args: Any, **kwargs: Any) -> Any:
|
|
1043
|
+
return self._serve("tool", name, args, kwargs)
|
|
1044
|
+
|
|
1045
|
+
call.__name__ = name
|
|
1046
|
+
return call
|
|
1047
|
+
|
|
1048
|
+
def atool(self, name: str) -> Callable[..., Awaitable[Any]]:
|
|
1049
|
+
"""Async `tool`."""
|
|
1050
|
+
|
|
1051
|
+
async def call(*args: Any, **kwargs: Any) -> Any:
|
|
1052
|
+
return self._serve("tool", name, args, kwargs)
|
|
1053
|
+
|
|
1054
|
+
call.__name__ = name
|
|
1055
|
+
return call
|
|
1056
|
+
|
|
1057
|
+
def __enter__(self) -> ReplayProvider:
|
|
1058
|
+
return self
|
|
1059
|
+
|
|
1060
|
+
def __exit__(self, exc_type: object, *rest: object) -> None:
|
|
1061
|
+
if exc_type is None:
|
|
1062
|
+
self.assert_exhausted()
|
|
1063
|
+
|
|
1064
|
+
|
|
1065
|
+
def replay(
|
|
1066
|
+
tape: AuditTape | Iterable[TapeRecord] | str | Path,
|
|
1067
|
+
*,
|
|
1068
|
+
ordered: bool = True,
|
|
1069
|
+
check_inputs: bool = False,
|
|
1070
|
+
redactor: Redactor | None = None,
|
|
1071
|
+
rebuild: Callable[[TapeRecord], Any] | None = None,
|
|
1072
|
+
) -> ReplayProvider:
|
|
1073
|
+
"""Turn a recorded tape into fake callables for deterministic tests.
|
|
1074
|
+
|
|
1075
|
+
Results are the recorded (redacted, JSON-shaped) outputs. Used as a ``with`` block the
|
|
1076
|
+
provider also checks that every recorded call was made.
|
|
1077
|
+
|
|
1078
|
+
Args:
|
|
1079
|
+
tape: An `AuditTape`, a path to a JSONL/SQLite tape, or `TapeRecord` objects.
|
|
1080
|
+
ordered: Calls must come in the recorded order (default). With False each call is
|
|
1081
|
+
matched to the first unused record of its kind and name.
|
|
1082
|
+
check_inputs: Also compare the arguments (after redaction) with the recorded input.
|
|
1083
|
+
Positional arguments are matched by position, keywords by name.
|
|
1084
|
+
redactor: Used for ``check_inputs``; should match the one used when recording.
|
|
1085
|
+
rebuild: ``record -> object`` to return something richer than the recorded JSON.
|
|
1086
|
+
|
|
1087
|
+
Raises:
|
|
1088
|
+
ReplayMismatch: (from the callables) on an unexpected call, a different kind or tool
|
|
1089
|
+
name, different inputs, or (from `assert_exhausted`) leftover records.
|
|
1090
|
+
ReplayedError: (from the callables) when the recorded call had failed.
|
|
1091
|
+
"""
|
|
1092
|
+
if isinstance(tape, (str, Path)):
|
|
1093
|
+
with AuditTape(tape) as opened:
|
|
1094
|
+
records: Sequence[TapeRecord] = opened.records()
|
|
1095
|
+
elif isinstance(tape, AuditTape):
|
|
1096
|
+
records = tape.records()
|
|
1097
|
+
else:
|
|
1098
|
+
records = list(tape)
|
|
1099
|
+
return ReplayProvider(
|
|
1100
|
+
records, ordered=ordered, check_inputs=check_inputs, redactor=redactor, rebuild=rebuild
|
|
1101
|
+
)
|