agenttrace-mcp 0.1.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.
- agenttrace/__init__.py +10 -0
- agenttrace/analysis.py +354 -0
- agenttrace/core/__init__.py +1 -0
- agenttrace/core/redaction.py +83 -0
- agenttrace/core/semconv.py +32 -0
- agenttrace/core/span.py +103 -0
- agenttrace/core/tracer.py +267 -0
- agenttrace/exporters/__init__.py +5 -0
- agenttrace/exporters/console.py +111 -0
- agenttrace/exporters/otlp.py +21 -0
- agenttrace/integrations/__init__.py +1 -0
- agenttrace/integrations/langchain.py +332 -0
- agenttrace/mcp_server.py +183 -0
- agenttrace/store/__init__.py +5 -0
- agenttrace/store/sqlite.py +419 -0
- agenttrace_mcp-0.1.0.dist-info/METADATA +245 -0
- agenttrace_mcp-0.1.0.dist-info/RECORD +20 -0
- agenttrace_mcp-0.1.0.dist-info/WHEEL +4 -0
- agenttrace_mcp-0.1.0.dist-info/entry_points.txt +2 -0
- agenttrace_mcp-0.1.0.dist-info/licenses/LICENSE +21 -0
agenttrace/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""AgentTrace: observability for AI agents, built on OpenTelemetry."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
|
|
5
|
+
from .core.redaction import Redactor # noqa: E402
|
|
6
|
+
from .core.semconv import SpanType # noqa: E402
|
|
7
|
+
from .core.span import AgentSpan # noqa: E402
|
|
8
|
+
from .core.tracer import AgentTrace # noqa: E402
|
|
9
|
+
|
|
10
|
+
__all__ = ["AgentSpan", "AgentTrace", "Redactor", "SpanType", "__version__"]
|
agenttrace/analysis.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
"""Rule-based trace analysis used by the MCP server (no LLM involved)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections import Counter, defaultdict
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
_EMPTY = {"", "[]", "{}", "null", "None", '""'}
|
|
9
|
+
_TREE_FIELDS = (
|
|
10
|
+
"span_id",
|
|
11
|
+
"name",
|
|
12
|
+
"span_type",
|
|
13
|
+
"status",
|
|
14
|
+
"duration_ms",
|
|
15
|
+
"started_at",
|
|
16
|
+
"model",
|
|
17
|
+
"input_tokens",
|
|
18
|
+
"output_tokens",
|
|
19
|
+
"cost_usd",
|
|
20
|
+
"status_message",
|
|
21
|
+
"error_type",
|
|
22
|
+
"input",
|
|
23
|
+
"output",
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _children(spans: list[dict[str, Any]]) -> tuple[dict[str | None, list[dict]], dict[str, dict]]:
|
|
28
|
+
by_id = {s["span_id"]: s for s in spans}
|
|
29
|
+
kids: dict[str | None, list[dict]] = defaultdict(list)
|
|
30
|
+
for s in spans:
|
|
31
|
+
parent = s.get("parent_span_id")
|
|
32
|
+
kids[parent if parent in by_id else None].append(s)
|
|
33
|
+
for v in kids.values():
|
|
34
|
+
# start time first; on coarse clocks (Windows) fall back to the end order
|
|
35
|
+
# recorded by the store, which for siblings matches execution order.
|
|
36
|
+
v.sort(key=lambda s: (s["start_ns"], s.get("seq", 0)))
|
|
37
|
+
return kids, by_id
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def span_tree(spans: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
41
|
+
kids, _ = _children(spans)
|
|
42
|
+
|
|
43
|
+
def node(s: dict[str, Any]) -> dict[str, Any]:
|
|
44
|
+
out = {k: s[k] for k in _TREE_FIELDS if k in s and s[k] is not None}
|
|
45
|
+
if s.get("events"):
|
|
46
|
+
out["events"] = [
|
|
47
|
+
{"name": e["name"], **({"attributes": e["attributes"]} if e["attributes"] else {})}
|
|
48
|
+
for e in s["events"]
|
|
49
|
+
]
|
|
50
|
+
if s.get("attributes"):
|
|
51
|
+
out["attributes"] = s["attributes"]
|
|
52
|
+
children = [node(c) for c in kids.get(s["span_id"], [])]
|
|
53
|
+
if children:
|
|
54
|
+
out["children"] = children
|
|
55
|
+
return out
|
|
56
|
+
|
|
57
|
+
return [node(r) for r in kids.get(None, [])]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _path(span: dict[str, Any], by_id: dict[str, dict]) -> list[str]:
|
|
61
|
+
names, cur, seen = [], span, set()
|
|
62
|
+
while cur is not None and cur["span_id"] not in seen:
|
|
63
|
+
seen.add(cur["span_id"])
|
|
64
|
+
names.append(cur["name"])
|
|
65
|
+
cur = by_id.get(cur.get("parent_span_id") or "")
|
|
66
|
+
return list(reversed(names))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _short(s: dict[str, Any]) -> dict[str, Any]:
|
|
70
|
+
return {
|
|
71
|
+
"span_id": s["span_id"],
|
|
72
|
+
"name": s["name"],
|
|
73
|
+
"span_type": s["span_type"],
|
|
74
|
+
"duration_ms": s["duration_ms"],
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _exception(span: dict[str, Any]) -> dict[str, Any] | None:
|
|
79
|
+
for e in span.get("events", []):
|
|
80
|
+
if e["name"] == "exception":
|
|
81
|
+
a = e["attributes"]
|
|
82
|
+
tail = str(a.get("exception.stacktrace", "")).strip().splitlines()[-4:]
|
|
83
|
+
return {
|
|
84
|
+
"type": a.get("exception.type"),
|
|
85
|
+
"message": a.get("exception.message"),
|
|
86
|
+
"stacktrace_tail": "\n".join(tail),
|
|
87
|
+
}
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def analyze(summary: dict[str, Any] | None, spans: list[dict[str, Any]]) -> dict[str, Any]:
|
|
92
|
+
if not spans:
|
|
93
|
+
raise LookupError("trace has no spans")
|
|
94
|
+
kids, by_id = _children(spans)
|
|
95
|
+
roots = kids.get(None, [])
|
|
96
|
+
total_ms = summary["duration_ms"] if summary else max(s["duration_ms"] for s in spans)
|
|
97
|
+
findings: list[str] = []
|
|
98
|
+
checks: list[str] = []
|
|
99
|
+
|
|
100
|
+
# --- failures -----------------------------------------------------------
|
|
101
|
+
errors = [s for s in spans if s["status"] == "error"]
|
|
102
|
+
error_ids = {s["span_id"] for s in errors}
|
|
103
|
+
origins = [
|
|
104
|
+
s for s in errors if not any(c["span_id"] in error_ids for c in kids.get(s["span_id"], []))
|
|
105
|
+
]
|
|
106
|
+
origins.sort(key=lambda s: s["start_ns"])
|
|
107
|
+
failure = None
|
|
108
|
+
recovered = []
|
|
109
|
+
for o in origins:
|
|
110
|
+
path = _path(o, by_id)
|
|
111
|
+
ancestors_failed, cur = True, by_id.get(o.get("parent_span_id") or "")
|
|
112
|
+
while cur is not None:
|
|
113
|
+
if cur["status"] != "error":
|
|
114
|
+
ancestors_failed = False
|
|
115
|
+
break
|
|
116
|
+
cur = by_id.get(cur.get("parent_span_id") or "")
|
|
117
|
+
item = {
|
|
118
|
+
**_short(o),
|
|
119
|
+
"path": " > ".join(path),
|
|
120
|
+
"error_type": o.get("error_type"),
|
|
121
|
+
"message": o.get("status_message"),
|
|
122
|
+
"exception": _exception(o),
|
|
123
|
+
"input": o.get("input"),
|
|
124
|
+
}
|
|
125
|
+
if ancestors_failed and failure is None:
|
|
126
|
+
failure = item
|
|
127
|
+
elif not ancestors_failed:
|
|
128
|
+
recovered.append(item)
|
|
129
|
+
if failure:
|
|
130
|
+
findings.append(
|
|
131
|
+
f"Run failed. The error originated in {failure['span_type']} span "
|
|
132
|
+
f"'{failure['name']}' ({failure['path']}): {failure['message']}"
|
|
133
|
+
)
|
|
134
|
+
stype = failure["span_type"]
|
|
135
|
+
if stype == "tool":
|
|
136
|
+
checks.append(
|
|
137
|
+
"Check the tool's arguments (the span input) against what the tool expects; "
|
|
138
|
+
"the LLM may have produced malformed or out-of-range arguments."
|
|
139
|
+
)
|
|
140
|
+
elif stype == "llm":
|
|
141
|
+
checks.append(
|
|
142
|
+
"The model call itself failed: check rate limits, context length, API "
|
|
143
|
+
"credentials and the provider status."
|
|
144
|
+
)
|
|
145
|
+
elif stype == "retriever":
|
|
146
|
+
checks.append("Check the retriever/vector store connection and the query.")
|
|
147
|
+
else:
|
|
148
|
+
checks.append("Inspect this span's input and the outputs of the steps right before it.")
|
|
149
|
+
if recovered:
|
|
150
|
+
findings.append(
|
|
151
|
+
f"{len(recovered)} error(s) were caught and the run continued: "
|
|
152
|
+
+ ", ".join(f"'{r['name']}'" for r in recovered[:5])
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
# --- retries and loops ----------------------------------------------------
|
|
156
|
+
retry_events = Counter()
|
|
157
|
+
for s in spans:
|
|
158
|
+
for e in s.get("events", []):
|
|
159
|
+
if "retry" in e["name"].lower():
|
|
160
|
+
retry_events[s["name"]] += 1
|
|
161
|
+
if retry_events:
|
|
162
|
+
findings.append(
|
|
163
|
+
"Retries: " + ", ".join(f"{n} ×{c}" for n, c in retry_events.most_common(5))
|
|
164
|
+
)
|
|
165
|
+
repeated = Counter(
|
|
166
|
+
(s["name"], s.get("input")) for s in spans if s["span_type"] in ("tool", "llm")
|
|
167
|
+
)
|
|
168
|
+
loops = [(name, c) for (name, _), c in repeated.items() if c >= 3]
|
|
169
|
+
if loops:
|
|
170
|
+
findings.append(
|
|
171
|
+
"Possible loop: identical calls repeated " + ", ".join(f"'{n}' ×{c}" for n, c in loops)
|
|
172
|
+
)
|
|
173
|
+
checks.append(
|
|
174
|
+
"The agent repeated the same call with the same input; check its stop "
|
|
175
|
+
"condition or whether the tool result is being fed back to the model."
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
# --- empty results -------------------------------------------------------
|
|
179
|
+
empty = [
|
|
180
|
+
_short(s)
|
|
181
|
+
for s in spans
|
|
182
|
+
if s["status"] != "error"
|
|
183
|
+
and s["span_type"] in ("tool", "retriever", "llm")
|
|
184
|
+
and s.get("output") is not None
|
|
185
|
+
and s["output"].strip() in _EMPTY
|
|
186
|
+
]
|
|
187
|
+
if empty:
|
|
188
|
+
findings.append(
|
|
189
|
+
"Steps that succeeded but returned an empty result: "
|
|
190
|
+
+ ", ".join(f"'{e['name']}'" for e in empty[:5])
|
|
191
|
+
)
|
|
192
|
+
checks.append(
|
|
193
|
+
"An empty tool/retriever result often leads to a wrong final answer without "
|
|
194
|
+
"an error. Check the query or filters used by those steps."
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
# --- latency -------------------------------------------------------------
|
|
198
|
+
self_ms = {}
|
|
199
|
+
for s in spans:
|
|
200
|
+
child_ms = sum(c["duration_ms"] for c in kids.get(s["span_id"], []))
|
|
201
|
+
self_ms[s["span_id"]] = max(0.0, s["duration_ms"] - child_ms)
|
|
202
|
+
leaves_or_work = sorted(spans, key=lambda s: self_ms[s["span_id"]], reverse=True)[:3]
|
|
203
|
+
bottlenecks = [
|
|
204
|
+
{
|
|
205
|
+
**_short(s),
|
|
206
|
+
"self_time_ms": round(self_ms[s["span_id"]], 1),
|
|
207
|
+
"share_of_run": round(self_ms[s["span_id"]] / total_ms, 3) if total_ms else None,
|
|
208
|
+
}
|
|
209
|
+
for s in leaves_or_work
|
|
210
|
+
]
|
|
211
|
+
if bottlenecks and bottlenecks[0]["share_of_run"] and bottlenecks[0]["share_of_run"] > 0.5:
|
|
212
|
+
b = bottlenecks[0]
|
|
213
|
+
findings.append(f"'{b['name']}' accounts for {b['share_of_run']:.0%} of the run's time.")
|
|
214
|
+
|
|
215
|
+
critical_path = []
|
|
216
|
+
node = max(roots, key=lambda r: r["duration_ms"]) if roots else None
|
|
217
|
+
while node is not None:
|
|
218
|
+
critical_path.append(_short(node))
|
|
219
|
+
children = kids.get(node["span_id"], [])
|
|
220
|
+
node = (
|
|
221
|
+
max(children, key=lambda c: c["start_ns"] + c["duration_ms"] * 1e6)
|
|
222
|
+
if children
|
|
223
|
+
else None
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
# --- tokens --------------------------------------------------------------
|
|
227
|
+
per_model: dict[str, dict[str, Any]] = {}
|
|
228
|
+
for s in spans:
|
|
229
|
+
if s["span_type"] == "llm" or s.get("model"):
|
|
230
|
+
m = per_model.setdefault(
|
|
231
|
+
s.get("model") or "unknown",
|
|
232
|
+
{"calls": 0, "input_tokens": 0, "output_tokens": 0, "cost_usd": 0.0},
|
|
233
|
+
)
|
|
234
|
+
m["calls"] += 1
|
|
235
|
+
m["input_tokens"] += s.get("input_tokens") or 0
|
|
236
|
+
m["output_tokens"] += s.get("output_tokens") or 0
|
|
237
|
+
m["cost_usd"] += s.get("cost_usd") or 0.0
|
|
238
|
+
llm_spans = [s for s in spans if s["span_type"] == "llm"]
|
|
239
|
+
if llm_spans and not any(s.get("input_tokens") for s in llm_spans):
|
|
240
|
+
checks.append("No token usage was recorded for LLM calls; set it with span.set_usage().")
|
|
241
|
+
|
|
242
|
+
if not findings:
|
|
243
|
+
findings.append("Run completed without errors, retries or empty results.")
|
|
244
|
+
return {
|
|
245
|
+
"summary": summary,
|
|
246
|
+
"findings": findings,
|
|
247
|
+
"failure": failure,
|
|
248
|
+
"recovered_errors": recovered,
|
|
249
|
+
"bottlenecks": bottlenecks,
|
|
250
|
+
"critical_path": critical_path,
|
|
251
|
+
"llm_usage": per_model,
|
|
252
|
+
"what_to_check": checks,
|
|
253
|
+
"note": (
|
|
254
|
+
"A trace shows what happened, not whether the answer is semantically correct. "
|
|
255
|
+
"If the run succeeded but the answer is wrong, inspect the outputs of the "
|
|
256
|
+
"tool/retriever steps with get_trace."
|
|
257
|
+
),
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _preorder(spans: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
262
|
+
kids, _ = _children(spans)
|
|
263
|
+
out: list[dict[str, Any]] = []
|
|
264
|
+
stack = list(reversed(kids.get(None, [])))
|
|
265
|
+
while stack:
|
|
266
|
+
s = stack.pop()
|
|
267
|
+
out.append(s)
|
|
268
|
+
stack.extend(reversed(kids.get(s["span_id"], [])))
|
|
269
|
+
return out
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _keyed(spans: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
|
|
273
|
+
_, by_id = _children(spans)
|
|
274
|
+
seen: Counter[str] = Counter()
|
|
275
|
+
out = {}
|
|
276
|
+
for s in _preorder(spans): # execution order, robust to equal timestamps
|
|
277
|
+
base = " > ".join(_path(s, by_id)[1:]) or "(root)"
|
|
278
|
+
seen[base] += 1
|
|
279
|
+
key = base if seen[base] == 1 else f"{base} #{seen[base]}"
|
|
280
|
+
out[key] = s
|
|
281
|
+
return out
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def compare(
|
|
285
|
+
sum_a: dict[str, Any] | None,
|
|
286
|
+
spans_a: list[dict[str, Any]],
|
|
287
|
+
sum_b: dict[str, Any] | None,
|
|
288
|
+
spans_b: list[dict[str, Any]],
|
|
289
|
+
) -> dict[str, Any]:
|
|
290
|
+
a, b = _keyed(spans_a), _keyed(spans_b)
|
|
291
|
+
only_a = [k for k in a if k not in b]
|
|
292
|
+
only_b = [k for k in b if k not in a]
|
|
293
|
+
changed = []
|
|
294
|
+
for key in a:
|
|
295
|
+
if key not in b:
|
|
296
|
+
continue
|
|
297
|
+
sa, sb = a[key], b[key]
|
|
298
|
+
diff: dict[str, Any] = {}
|
|
299
|
+
if sa["status"] != sb["status"]:
|
|
300
|
+
diff["status"] = [sa["status"], sb["status"]]
|
|
301
|
+
delta = sb["duration_ms"] - sa["duration_ms"]
|
|
302
|
+
if abs(delta) >= max(50.0, 0.5 * sa["duration_ms"]):
|
|
303
|
+
diff["duration_ms"] = [sa["duration_ms"], sb["duration_ms"]]
|
|
304
|
+
ta = (sa.get("input_tokens") or 0) + (sa.get("output_tokens") or 0)
|
|
305
|
+
tb = (sb.get("input_tokens") or 0) + (sb.get("output_tokens") or 0)
|
|
306
|
+
if ta != tb:
|
|
307
|
+
diff["tokens"] = [ta, tb]
|
|
308
|
+
if sa.get("output") != sb.get("output") and sa["span_type"] in ("tool", "retriever"):
|
|
309
|
+
diff["output_changed"] = True
|
|
310
|
+
if diff:
|
|
311
|
+
changed.append({"step": key, **diff})
|
|
312
|
+
|
|
313
|
+
order_a, order_b = list(a), list(b)
|
|
314
|
+
status_diff = {k for k in a if k in b and a[k]["status"] != b[k]["status"]}
|
|
315
|
+
|
|
316
|
+
def propagated(key: str) -> bool: # an error that only bubbled up from a child step
|
|
317
|
+
return any(o != key and (key == "(root)" or o.startswith(key + " > ")) for o in status_diff)
|
|
318
|
+
|
|
319
|
+
divergence = None
|
|
320
|
+
for i in range(max(len(order_a), len(order_b))):
|
|
321
|
+
ka = order_a[i] if i < len(order_a) else None
|
|
322
|
+
kb = order_b[i] if i < len(order_b) else None
|
|
323
|
+
if ka != kb:
|
|
324
|
+
divergence = {"index": i, "a": ka, "b": kb, "reason": "different step"}
|
|
325
|
+
break
|
|
326
|
+
if a[ka]["status"] != b[kb]["status"] and not propagated(ka):
|
|
327
|
+
divergence = {
|
|
328
|
+
"index": i,
|
|
329
|
+
"a": ka,
|
|
330
|
+
"b": kb,
|
|
331
|
+
"reason": f"status {a[ka]['status']} vs {b[kb]['status']}",
|
|
332
|
+
}
|
|
333
|
+
break
|
|
334
|
+
|
|
335
|
+
def delta(field: str) -> Any:
|
|
336
|
+
if not sum_a or not sum_b:
|
|
337
|
+
return None
|
|
338
|
+
return round(sum_b[field] - sum_a[field], 3)
|
|
339
|
+
|
|
340
|
+
return {
|
|
341
|
+
"a": sum_a,
|
|
342
|
+
"b": sum_b,
|
|
343
|
+
"delta": {
|
|
344
|
+
"duration_ms": delta("duration_ms"),
|
|
345
|
+
"input_tokens": delta("input_tokens"),
|
|
346
|
+
"output_tokens": delta("output_tokens"),
|
|
347
|
+
"span_count": delta("span_count"),
|
|
348
|
+
"error_count": delta("error_count"),
|
|
349
|
+
},
|
|
350
|
+
"first_divergence": divergence,
|
|
351
|
+
"steps_only_in_a": only_a,
|
|
352
|
+
"steps_only_in_b": only_b,
|
|
353
|
+
"changed_steps": changed,
|
|
354
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Core tracing primitives."""
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Mask secrets and personal data before anything leaves the process."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from collections.abc import Callable, Iterable
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
MASK = "[REDACTED]"
|
|
11
|
+
|
|
12
|
+
DEFAULT_PATTERNS: dict[str, str] = {
|
|
13
|
+
"api_key": r"\b(?:sk|pk|rk)-[A-Za-z0-9_\-]{16,}\b",
|
|
14
|
+
"aws_access_key": r"\bAKIA[0-9A-Z]{16}\b",
|
|
15
|
+
"bearer_token": r"(?i)\bbearer\s+[A-Za-z0-9._\-]{16,}",
|
|
16
|
+
"jwt": r"\beyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\b",
|
|
17
|
+
"email": r"\b[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}\b",
|
|
18
|
+
"password_field": r"(?i)(\"?(?:password|passwd|pwd|secret)\"?\s*[:=]\s*)\"?[^\s\",}]+\"?",
|
|
19
|
+
}
|
|
20
|
+
_CARD = re.compile(r"\b(?:\d[ -]?){13,19}\b")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _luhn_ok(digits: str) -> bool:
|
|
24
|
+
total, alt = 0, False
|
|
25
|
+
for ch in reversed(digits):
|
|
26
|
+
d = int(ch)
|
|
27
|
+
if alt:
|
|
28
|
+
d = d * 2 - 9 if d > 4 else d * 2
|
|
29
|
+
total += d
|
|
30
|
+
alt = not alt
|
|
31
|
+
return total % 10 == 0
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Redactor:
|
|
35
|
+
"""Applies regex masks (plus a Luhn-checked card-number mask) to text.
|
|
36
|
+
|
|
37
|
+
Pass ``patterns`` to add your own, ``disable`` to drop built-ins, or
|
|
38
|
+
``custom`` for a final function of your own.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
patterns: dict[str, str] | None = None,
|
|
44
|
+
disable: Iterable[str] = (),
|
|
45
|
+
custom: Callable[[str], str] | None = None,
|
|
46
|
+
cards: bool = True,
|
|
47
|
+
) -> None:
|
|
48
|
+
merged = {k: v for k, v in DEFAULT_PATTERNS.items() if k not in set(disable)}
|
|
49
|
+
merged.update(patterns or {})
|
|
50
|
+
self._rules = [re.compile(p) for p in merged.values()]
|
|
51
|
+
self._custom = custom
|
|
52
|
+
self._cards = cards
|
|
53
|
+
|
|
54
|
+
def __call__(self, text: str) -> str:
|
|
55
|
+
for rule in self._rules:
|
|
56
|
+
if rule.groups: # keep the field name, mask the value
|
|
57
|
+
text = rule.sub(lambda m: m.group(1) + MASK, text)
|
|
58
|
+
else:
|
|
59
|
+
text = rule.sub(MASK, text)
|
|
60
|
+
if self._cards:
|
|
61
|
+
text = _CARD.sub(self._mask_card, text)
|
|
62
|
+
if self._custom:
|
|
63
|
+
text = self._custom(text)
|
|
64
|
+
return text
|
|
65
|
+
|
|
66
|
+
@staticmethod
|
|
67
|
+
def _mask_card(m: re.Match[str]) -> str:
|
|
68
|
+
digits = re.sub(r"\D", "", m.group(0))
|
|
69
|
+
return MASK if 13 <= len(digits) <= 19 and _luhn_ok(digits) else m.group(0)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def serialize(value: Any, max_chars: int = 8000) -> str:
|
|
73
|
+
"""Turn any value into a bounded string for a span attribute."""
|
|
74
|
+
if isinstance(value, str):
|
|
75
|
+
text = value
|
|
76
|
+
else:
|
|
77
|
+
try:
|
|
78
|
+
text = json.dumps(value, default=repr, ensure_ascii=False)
|
|
79
|
+
except (TypeError, ValueError):
|
|
80
|
+
text = repr(value)
|
|
81
|
+
if len(text) > max_chars:
|
|
82
|
+
text = text[:max_chars] + f"... [truncated {len(text) - max_chars} chars]"
|
|
83
|
+
return text
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Attribute names AgentTrace writes on spans.
|
|
2
|
+
|
|
3
|
+
Where an OpenTelemetry GenAI semantic convention exists we use it, so traces
|
|
4
|
+
stay readable by any OTel backend (Jaeger, Tempo, Phoenix, Langfuse ...).
|
|
5
|
+
Input/output use the OpenInference names that most LLM tools already read.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
PROJECT = "agenttrace.project"
|
|
9
|
+
SPAN_TYPE = "agenttrace.span.type"
|
|
10
|
+
COST_USD = "agenttrace.cost.usd"
|
|
11
|
+
SDK_VERSION = "agenttrace.sdk.version"
|
|
12
|
+
|
|
13
|
+
INPUT_VALUE = "input.value"
|
|
14
|
+
OUTPUT_VALUE = "output.value"
|
|
15
|
+
|
|
16
|
+
GEN_AI_SYSTEM = "gen_ai.system"
|
|
17
|
+
GEN_AI_REQUEST_MODEL = "gen_ai.request.model"
|
|
18
|
+
GEN_AI_USAGE_INPUT_TOKENS = "gen_ai.usage.input_tokens"
|
|
19
|
+
GEN_AI_USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens"
|
|
20
|
+
GEN_AI_TOOL_NAME = "gen_ai.tool.name"
|
|
21
|
+
|
|
22
|
+
ERROR_TYPE = "error.type"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class SpanType:
|
|
26
|
+
TRACE = "trace"
|
|
27
|
+
AGENT = "agent"
|
|
28
|
+
LLM = "llm"
|
|
29
|
+
TOOL = "tool"
|
|
30
|
+
RETRIEVER = "retriever"
|
|
31
|
+
CHAIN = "chain"
|
|
32
|
+
CUSTOM = "custom"
|
agenttrace/core/span.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""AgentSpan: a small, agent-friendly handle around an OpenTelemetry span."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from opentelemetry.trace import Span, Status, StatusCode
|
|
9
|
+
|
|
10
|
+
from . import semconv as sc
|
|
11
|
+
from .redaction import serialize
|
|
12
|
+
|
|
13
|
+
_PRIMITIVES = (str, bool, int, float)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _attr(value: Any) -> Any:
|
|
17
|
+
if isinstance(value, _PRIMITIVES):
|
|
18
|
+
return value
|
|
19
|
+
if isinstance(value, (list, tuple)) and all(isinstance(v, _PRIMITIVES) for v in value):
|
|
20
|
+
return list(value)
|
|
21
|
+
return serialize(value)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class AgentSpan:
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
span: Span,
|
|
28
|
+
redact: Callable[[str], str] | None,
|
|
29
|
+
capture_io: bool,
|
|
30
|
+
max_chars: int,
|
|
31
|
+
) -> None:
|
|
32
|
+
self._span = span
|
|
33
|
+
self._redact = redact
|
|
34
|
+
self._capture_io = capture_io
|
|
35
|
+
self._max_chars = max_chars
|
|
36
|
+
|
|
37
|
+
# ids -----------------------------------------------------------------
|
|
38
|
+
@property
|
|
39
|
+
def trace_id(self) -> str:
|
|
40
|
+
return format(self._span.get_span_context().trace_id, "032x")
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def span_id(self) -> str:
|
|
44
|
+
return format(self._span.get_span_context().span_id, "016x")
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def otel_span(self) -> Span:
|
|
48
|
+
return self._span
|
|
49
|
+
|
|
50
|
+
# data ----------------------------------------------------------------
|
|
51
|
+
def _text(self, value: Any) -> str:
|
|
52
|
+
text = serialize(value, self._max_chars)
|
|
53
|
+
return self._redact(text) if self._redact else text
|
|
54
|
+
|
|
55
|
+
def set_input(self, value: Any) -> AgentSpan:
|
|
56
|
+
if self._capture_io and value is not None:
|
|
57
|
+
self._span.set_attribute(sc.INPUT_VALUE, self._text(value))
|
|
58
|
+
return self
|
|
59
|
+
|
|
60
|
+
def set_output(self, value: Any) -> AgentSpan:
|
|
61
|
+
if self._capture_io and value is not None:
|
|
62
|
+
self._span.set_attribute(sc.OUTPUT_VALUE, self._text(value))
|
|
63
|
+
return self
|
|
64
|
+
|
|
65
|
+
def set_model(self, model: str, system: str | None = None) -> AgentSpan:
|
|
66
|
+
self._span.set_attribute(sc.GEN_AI_REQUEST_MODEL, model)
|
|
67
|
+
if system:
|
|
68
|
+
self._span.set_attribute(sc.GEN_AI_SYSTEM, system)
|
|
69
|
+
return self
|
|
70
|
+
|
|
71
|
+
def set_usage(
|
|
72
|
+
self,
|
|
73
|
+
input_tokens: int | None = None,
|
|
74
|
+
output_tokens: int | None = None,
|
|
75
|
+
cost_usd: float | None = None,
|
|
76
|
+
) -> AgentSpan:
|
|
77
|
+
if input_tokens is not None:
|
|
78
|
+
self._span.set_attribute(sc.GEN_AI_USAGE_INPUT_TOKENS, int(input_tokens))
|
|
79
|
+
if output_tokens is not None:
|
|
80
|
+
self._span.set_attribute(sc.GEN_AI_USAGE_OUTPUT_TOKENS, int(output_tokens))
|
|
81
|
+
if cost_usd is not None:
|
|
82
|
+
self._span.set_attribute(sc.COST_USD, float(cost_usd))
|
|
83
|
+
return self
|
|
84
|
+
|
|
85
|
+
def set_attribute(self, key: str, value: Any) -> AgentSpan:
|
|
86
|
+
self._span.set_attribute(key, _attr(value))
|
|
87
|
+
return self
|
|
88
|
+
|
|
89
|
+
def add_event(self, name: str, **attributes: Any) -> AgentSpan:
|
|
90
|
+
attrs = {k: _attr(v) for k, v in attributes.items()}
|
|
91
|
+
if self._redact:
|
|
92
|
+
attrs = {k: self._redact(v) if isinstance(v, str) else v for k, v in attrs.items()}
|
|
93
|
+
self._span.add_event(name, attrs)
|
|
94
|
+
return self
|
|
95
|
+
|
|
96
|
+
def record_error(self, exc: BaseException) -> AgentSpan:
|
|
97
|
+
self._span.record_exception(exc)
|
|
98
|
+
self._span.set_attribute(sc.ERROR_TYPE, type(exc).__name__)
|
|
99
|
+
self._span.set_status(Status(StatusCode.ERROR, f"{type(exc).__name__}: {exc}"))
|
|
100
|
+
return self
|
|
101
|
+
|
|
102
|
+
def __repr__(self) -> str: # pragma: no cover
|
|
103
|
+
return f"<AgentSpan trace={self.trace_id} span={self.span_id}>"
|