Skip to content

Commit 8dde5b5

Browse files
feat(pydantic-ai): trace harness capability decisions
> 🤖 **This text was AI-generated.** Braintrust traces show the agent and model calls but leave out what Pydantic AI Harness did between them. Patch the optional Harness hooks to record history compaction, memory injection, guardrail blocks, and the model route without depending on native instrumentation. ```text agent_run model_router.select agent_run [model_router] memory.inject compact_messages guardrail blocked output ``` Older Pydantic AI versions and installs without Harness continue to use the existing agent and model patches. Co-authored-by: Abhijeet Prasad <abhijeet@braintrustdata.com>
1 parent 9878cf7 commit 8dde5b5

6 files changed

Lines changed: 330 additions & 0 deletions

File tree

‎py/nox_session_constraints.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
"test_pydantic_ai_harness": {"min_python": "3.11"},
2222
"test_pydantic_ai_logfire": {"versions": {"latest": {"min_python": "3.11"}}},
2323
"test_pydantic_ai_wrap_openai": {"versions": {"latest": {"min_python": "3.11"}}},
24+
"test_pydantic_ai_harness": {"min_python": "3.11"},
2425
"test_dspy": {"versions": {"latest": {"min_python": "3.11", "max_python_exclusive": "3.15"}}}, # fastuuid
2526
"test_crewai": {"max_python_exclusive": "3.14"},
2627
"test_deepagents": {"min_python": "3.11", "max_python_exclusive": "3.15"}, # ormsgpack

‎py/noxfile.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -657,6 +657,23 @@ def test_pydantic_ai_wrap_openai(session, version):
657657
_run_tests(session, f"{INTEGRATION_DIR}/pydantic_ai/test_pydantic_ai_wrap_openai.py", version=version)
658658

659659

660+
@nox.session()
661+
def test_pydantic_ai_harness(session):
662+
_skip_if_incompatible(session)
663+
_install_test_deps(session)
664+
# Harness 0.75 and its matching Pydantic AI releases postdate the global cutoff.
665+
_session_install(
666+
session,
667+
_MATRIX["pydantic-ai-harness"]["latest"],
668+
*(
669+
f"--exclude-newer-package={package}=2026-11-26"
670+
for package in ("pydantic-ai-harness", "pydantic-ai-slim", "pydantic-graph")
671+
),
672+
silent=SILENT_INSTALLS,
673+
)
674+
_run_tests(session, f"{INTEGRATION_DIR}/pydantic_ai/test_pydantic_ai_harness_decisions.py")
675+
676+
660677
AUTOEVALS_VERSIONS = _get_matrix_versions("autoevals")
661678

662679

‎py/pyproject.toml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -575,6 +575,9 @@ latest = "pydantic-ai-harness==0.75.0"
575575
latest = "pydantic-ai==2.75.0"
576576
"1.107.9" = "pydantic-ai==1.107.9"
577577

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

‎py/src/braintrust/integrations/pydantic_ai/integration.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,12 @@
22

33
from braintrust.integrations.base import BaseIntegration
44

5+
from .harness import (
6+
HarnessCompactionPatcher,
7+
HarnessGuardrailBlockPatcher,
8+
HarnessMemoryInjectionPatcher,
9+
HarnessModelRouterPatcher,
10+
)
511
from .patchers import (
612
AgentPatcher,
713
DirectModelRequestPatcher,
@@ -33,4 +39,8 @@ class PydanticAIIntegration(BaseIntegration):
3339
DirectModelRequestStreamPatcher,
3440
DirectModelRequestStreamSyncPatcher,
3541
ToolManagerFunctionToolPatcher,
42+
HarnessCompactionPatcher,
43+
HarnessMemoryInjectionPatcher,
44+
HarnessGuardrailBlockPatcher,
45+
HarnessModelRouterPatcher,
3646
)
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
import pytest
2+
from braintrust import logger, setup_pydantic_ai
3+
from braintrust.span_types import SpanTypeAttribute
4+
from braintrust.test_helpers import init_test_logger
5+
from pydantic_ai import Agent
6+
from pydantic_ai.messages import ModelResponse, TextPart, ToolCallPart, ToolReturnPart
7+
from pydantic_ai.models.function import FunctionModel
8+
from pydantic_ai.models.test import TestModel
9+
10+
11+
pytest.importorskip("pydantic_ai_harness")
12+
13+
PROJECT_NAME = "test-pydantic-ai-harness-decisions"
14+
15+
16+
@pytest.fixture
17+
def memory_logger():
18+
assert setup_pydantic_ai(project_name=PROJECT_NAME)
19+
init_test_logger(PROJECT_NAME)
20+
with logger._internal_with_memory_background_logger() as bgl:
21+
yield bgl
22+
23+
24+
def _decision_span(spans, name):
25+
(agent_span,) = (span for span in spans if span["span_attributes"]["name"] == "agent_run [harness]")
26+
(decision,) = (span for span in spans if span["span_attributes"]["name"] == name)
27+
assert decision["span_attributes"]["type"] == SpanTypeAttribute.TASK
28+
assert decision["span_parents"] == [agent_span["span_id"]]
29+
assert decision["context"]["span_origin"]["instrumentation"]["name"] == "pydantic-ai-auto"
30+
return decision
31+
32+
33+
@pytest.mark.asyncio
34+
async def test_harness_compaction_decision(memory_logger):
35+
compaction = pytest.importorskip("pydantic_ai_harness.compaction")
36+
tool_results = []
37+
38+
def model(messages, _info):
39+
results = [part.content for message in messages for part in message.parts if isinstance(part, ToolReturnPart)]
40+
if not results:
41+
return ModelResponse(parts=[ToolCallPart("note", {}, tool_call_id="note")])
42+
tool_results.extend(results)
43+
return ModelResponse(parts=[TextPart("done")])
44+
45+
agent = Agent(
46+
FunctionModel(model),
47+
name="harness",
48+
capabilities=[compaction.ClearToolResults(max_messages=1, keep_pairs=0)],
49+
)
50+
51+
@agent.tool_plain
52+
def note():
53+
return "old tool result"
54+
55+
assert (await agent.run("call the tool")).output == "done"
56+
assert tool_results == ["[tool result cleared]"]
57+
58+
decision = _decision_span(memory_logger.pop(), "compact_messages")
59+
assert decision["metadata"]["strategy"] == "ClearToolResults"
60+
assert decision["input"] == {"messages": 3}
61+
assert decision["output"] == {"messages": 3}
62+
63+
64+
@pytest.mark.asyncio
65+
async def test_harness_memory_injection_decision(memory_logger):
66+
memory = pytest.importorskip("pydantic_ai_harness.memory")
67+
store = memory.InMemoryMemoryStore()
68+
await store.write("main/MEMORY.md", "offline memory token", expected_version=None)
69+
agent = Agent(
70+
TestModel(call_tools=[], custom_output_text="done"),
71+
name="harness",
72+
capabilities=[memory.Memory(store=store)],
73+
)
74+
75+
assert (await agent.run("remember")).output == "done"
76+
77+
decision = _decision_span(memory_logger.pop(), "memory.inject")
78+
assert decision["output"]["outcome"] == "ok"
79+
assert decision["output"]["appended"] is True
80+
assert decision["output"]["injected_chars"] >= len("offline memory token")
81+
assert "offline memory token" not in str(decision)
82+
83+
84+
@pytest.mark.asyncio
85+
async def test_harness_guardrail_block_decision(memory_logger):
86+
guardrails = pytest.importorskip("pydantic_ai_harness.guardrails")
87+
88+
async def deny(_ctx, _output):
89+
return guardrails.GuardrailResult.block("blocked by test policy")
90+
91+
agent = Agent(
92+
TestModel(custom_output_text="rejected output"),
93+
name="harness",
94+
capabilities=[guardrails.OutputGuardrail(deny)],
95+
)
96+
97+
with pytest.raises(guardrails.OutputBlocked, match="blocked by test policy"):
98+
await agent.run("check output")
99+
100+
decision = _decision_span(memory_logger.pop(), "guardrail blocked output")
101+
assert decision["input"] == {"direction": "output"}
102+
assert decision["output"] == {"action": "block", "reason": "blocked by test policy"}
103+
assert not decision.get("error")
104+
105+
106+
@pytest.mark.asyncio
107+
@pytest.mark.parametrize("instrument", [False, True])
108+
async def test_harness_model_router_decision(memory_logger, instrument):
109+
router = pytest.importorskip("pydantic_ai_harness.model_router")
110+
capabilities = pytest.importorskip("pydantic_ai.capabilities")
111+
agent = Agent(
112+
TestModel(),
113+
name="harness",
114+
capabilities=[
115+
*([capabilities.Instrumentation()] if instrument else []),
116+
router.ModelRouter(
117+
choices={
118+
"default": router.ModelChoice(TestModel(custom_output_text="default"), "default"),
119+
"alternate": router.ModelChoice(TestModel(custom_output_text="alternate"), "alternate"),
120+
},
121+
router_model=TestModel(custom_output_args={"choice": "alternate"}),
122+
default="default",
123+
),
124+
],
125+
)
126+
127+
assert (await agent.run("route to alternate")).output == "alternate"
128+
129+
spans = memory_logger.pop()
130+
decision = _decision_span(spans, "model_router.select")
131+
assert decision["input"] == {"choices": ["default", "alternate"], "default": "default"}
132+
assert decision["metadata"]["mode"] == "once"
133+
assert decision["output"] == {"choice": "alternate", "fallback_reason": "none"}
134+
(router_agent,) = (span for span in spans if span["span_attributes"]["name"] == "agent_run [model_router]")
135+
assert router_agent["span_parents"] == [decision["span_id"]]

0 commit comments

Comments
 (0)