Skip to content

Commit 7fd4377

Browse files
feat(pydantic-ai): trace harness capability decisions (#1193)
## Summary Pydantic AI Harness decisions (compaction, memory injection, guardrail blocks, model routing) happened invisibly under `setup_pydantic_ai()`. `integrations/pydantic_ai/_harness.py` adds patches, applied only when `pydantic_ai_harness` is importable, that emit Braintrust `task` spans under the current agent run. These spans come from our own patching and do not depend on native OTel/Logfire. | Span | Captured | |---|---| | `compact_messages` | messages before/after counts, strategy, background/model-requested flags (retrieving already-finished background work (`background="used"`) is not traced) | | `memory.inject` | source sizes, truncation, outcome, injected char count (no memory text) | | `guardrail blocked <direction>` | block outcome, direction, tool name when applicable (free-text reason omitted; it can quote the guarded value) | | `model_router.select` | choices, default, selected route, fallback reason, allowlisted router attrs (`mode`, `run_step`, `probability`, `error.type`); the router's own agent run nests under it | ```text agent_run model_router.select agent_run [model_router] memory.inject compact_messages guardrail blocked output ``` Testing: `harness/test_decisions.py` runs in the shared harness nox session from #1191. Each decision is covered with real OpenAI VCR cassettes in `harness/cassettes/latest/`. The model-router test replays with native instrumentation both off and on, which confirms our spans are kept. Older pydantic-ai (1.107.9) and installs without Harness are unaffected. --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Abhijeet Prasad <abhijeet@braintrustdata.com>
1 parent 825f457 commit 7fd4377

7 files changed

Lines changed: 1032 additions & 0 deletions

File tree

Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
"""Optional Pydantic AI Harness capability instrumentation."""
2+
3+
import sys
4+
from contextvars import ContextVar
5+
6+
from braintrust.integrations.base import CompositeFunctionWrapperPatcher, FunctionWrapperPatcher
7+
from braintrust.logger import Span
8+
from braintrust.span_types import SpanTypeAttribute
9+
10+
from .tracing import start_span
11+
12+
13+
async def _compact_messages(wrapped, _instance, args, kwargs):
14+
background = kwargs.get("background")
15+
if background == "used":
16+
return await wrapped(*args, **kwargs)
17+
messages = kwargs["messages"]
18+
before = len(messages)
19+
compacted = await wrapped(*args, **kwargs)
20+
# Harness returns the original list when compaction leaves the history unchanged.
21+
if compacted is not messages:
22+
metadata = {"strategy": kwargs["strategy"]}
23+
if kwargs.get("model_requested"):
24+
metadata["model_requested"] = True
25+
if background is not None:
26+
metadata["background"] = background
27+
start_span(
28+
name="harness_message_compaction",
29+
type=SpanTypeAttribute.TASK,
30+
input={"messages": before},
31+
output={"messages": len(compacted)},
32+
metadata=metadata,
33+
).end()
34+
return compacted
35+
36+
37+
def _record_memory_injection(wrapped, instance, args, kwargs):
38+
result = wrapped(*args, **kwargs)
39+
_, main, subfiles, files_truncated, snapshot, appended, withheld = args
40+
main_chars = len(main.content) if main is not None else 0
41+
has_memory = bool(main_chars or subfiles or files_truncated)
42+
start_span(
43+
name="harness_memory_injection",
44+
type=SpanTypeAttribute.TASK,
45+
input={"main_chars": main_chars, "files": len(subfiles)},
46+
output={
47+
"appended": appended is not None,
48+
"injected_chars": len(appended or ""),
49+
"outcome": "budget_exhausted" if snapshot is None and has_memory else "ok",
50+
},
51+
metadata={
52+
"files_truncated": files_truncated,
53+
"main_truncated": main is not None and main.truncated,
54+
**({"main_withheld": withheld} if instance.scanner is not None else {}),
55+
},
56+
).end()
57+
return result
58+
59+
60+
def _trace_guardrail_block(wrapped, _instance, args, kwargs):
61+
result = wrapped(*args, **kwargs)
62+
metadata = {"direction": kwargs["direction"]}
63+
tool_name = kwargs.get("tool_name")
64+
if tool_name is not None:
65+
metadata["tool_name"] = tool_name
66+
start_span(
67+
name="harness_guardrail_block",
68+
type=SpanTypeAttribute.TASK,
69+
output={"action": "block"},
70+
metadata=metadata,
71+
).end()
72+
return result
73+
74+
75+
_router_span = ContextVar[Span | None]("pydantic_ai_harness_router_span", default=None)
76+
_ROUTER_METADATA_FIELDS = {
77+
"model_router.mode": "mode",
78+
"model_router.run_step": "run_step",
79+
"model_router.probability": "probability",
80+
"model_router.error.type": "error.type",
81+
}
82+
83+
84+
async def _select_model(wrapped, instance, args, kwargs):
85+
# Bootstrap and cached lookups do not make a routing decision.
86+
if instance._run_ctx is None or (instance.mode == "once" and instance._cached_choice is not None):
87+
return await wrapped(*args, **kwargs)
88+
with start_span(
89+
name="harness_model_selection",
90+
type=SpanTypeAttribute.TASK,
91+
input={"choices": list(instance.choices), "default": instance.default},
92+
) as span:
93+
token = _router_span.set(span)
94+
try:
95+
return await wrapped(*args, **kwargs)
96+
finally:
97+
_router_span.reset(token)
98+
99+
100+
def _record_model_selection(wrapped, _instance, args, kwargs):
101+
result = wrapped(*args, **kwargs)
102+
span = _router_span.get()
103+
if span is not None:
104+
_, attributes, choice, fallback_reason = args
105+
span.log(
106+
output={"choice": choice, "fallback_reason": fallback_reason},
107+
metadata={field: attributes[key] for key, field in _ROUTER_METADATA_FIELDS.items() if key in attributes},
108+
)
109+
return result
110+
111+
112+
class _HarnessPatcher(FunctionWrapperPatcher):
113+
version_spec = ">=2.75"
114+
115+
116+
class _SharedHarnessFunctionPatcher(_HarnessPatcher):
117+
@classmethod
118+
def patch(cls, module, version, *, target=None):
119+
root = cls.resolve_root(module, version, target=target)
120+
original = cls.resolve_target(module, version, target=target)
121+
if not super().patch(module, version, target=target):
122+
return False
123+
wrapped = cls.resolve_target(module, version, target=target)
124+
# Harness imports these helpers by name while initializing their feature packages.
125+
prefix = root.__package__ + "."
126+
for name, imported in sys.modules.copy().items():
127+
if name.startswith(prefix) and getattr(imported, cls.target_path, None) is original:
128+
setattr(imported, cls.target_path, wrapped)
129+
return True
130+
131+
132+
class HarnessCompactionPatcher(_SharedHarnessFunctionPatcher):
133+
name = "pydantic_ai.harness.compaction"
134+
target_module = "pydantic_ai_harness.compaction._shared"
135+
target_path = "compact_with_span"
136+
wrapper = _compact_messages
137+
138+
139+
class HarnessMemoryInjectionPatcher(_HarnessPatcher):
140+
name = "pydantic_ai.harness.memory_injection"
141+
target_module = "pydantic_ai_harness.memory._capability"
142+
target_path = "Memory._record_injection"
143+
wrapper = _record_memory_injection
144+
145+
146+
class HarnessGuardrailBlockPatcher(_SharedHarnessFunctionPatcher):
147+
name = "pydantic_ai.harness.guardrail_block"
148+
target_module = "pydantic_ai_harness.guardrails._shared"
149+
target_path = "trace_block"
150+
wrapper = _trace_guardrail_block
151+
152+
153+
class _HarnessModelRouterSelectPatcher(_HarnessPatcher):
154+
name = "pydantic_ai.harness.model_router.select"
155+
target_module = "pydantic_ai_harness.model_router._capability"
156+
target_path = "ModelRouter._select_model"
157+
wrapper = _select_model
158+
159+
160+
class _HarnessModelRouterRecordPatcher(_HarnessPatcher):
161+
name = "pydantic_ai.harness.model_router.record"
162+
target_module = "pydantic_ai_harness.model_router._capability"
163+
target_path = "_record"
164+
wrapper = _record_model_selection
165+
166+
167+
class HarnessModelRouterPatcher(CompositeFunctionWrapperPatcher):
168+
name = "pydantic_ai.harness.model_router"
169+
sub_patchers = (_HarnessModelRouterSelectPatcher, _HarnessModelRouterRecordPatcher)
170+
171+
@classmethod
172+
def applies(cls, module, version, *, target=None):
173+
return all(patcher.applies(module, version, target=target) for patcher in cls.sub_patchers)

‎py/src/braintrust/integrations/pydantic_ai/harness/cassettes/latest/test_harness_compaction_decision.yaml‎

Lines changed: 215 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)