Skip to content

Commit 416689a

Browse files
fix(pydantic-ai): trace direct agent iteration (#1192)
## Summary Direct `Agent.iter()` under `setup_pydantic_ai()` emitted independent `llm`/`tool` root spans with no agent span. `Agent.iter` is now patched (target detection, no version cutoff — works on 1.107.9 and latest) to keep one `agent_run` task span open for the lifetime of the async iter context, parenting model/tool spans and logging the final result output when the run completes. ```text Agent.iter() -> agent_run [task] -> llm, tool, llm ``` `run()` / `run_stream()` etc. call `iter()` internally; a one-shot guard skips the extra span there so they still produce a single root. Early exit and exceptions inside the iter context are covered by tests (reusing the existing tool-execution cassette). Link to Devin session: https://braintrust.devinenterprise.com/sessions/65f99aeaed0543229807e7a25aadf324 Open in Devin Desktop: https://braintrust.devinenterprise.com/desktop/session/65f99aeaed0543229807e7a25aadf324?variant=devin --------- Co-authored-by: Abhijeet Prasad <abhijeet@braintrustdata.com> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
1 parent 18be56d commit 416689a

5 files changed

Lines changed: 393 additions & 7 deletions

File tree

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

Lines changed: 216 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import pytest
2+
from braintrust import logger, setup_pydantic_ai
3+
from braintrust.span_types import SpanTypeAttribute
4+
from braintrust.test_helpers import find_span_by_name, find_spans_by_type, init_test_logger
5+
6+
7+
@pytest.mark.vcr
8+
@pytest.mark.asyncio
9+
async def test_harness_iter_traces_model_and_tool():
10+
from pydantic_ai import Agent
11+
from pydantic_ai.models.openai import OpenAIChatModel
12+
13+
persistence = pytest.importorskip("pydantic_ai_harness.step_persistence", exc_type=ModuleNotFoundError)
14+
15+
project = "test-pydantic-ai-harness-iter"
16+
assert setup_pydantic_ai(project_name=project)
17+
init_test_logger(project)
18+
19+
store = persistence.InMemoryStepStore()
20+
agent = Agent(
21+
OpenAIChatModel("gpt-4.1-mini"), name="harness_iter", capabilities=[persistence.StepPersistence(store=store)]
22+
)
23+
24+
@agent.tool_plain
25+
def echo(text: str) -> str:
26+
"""Return the supplied text."""
27+
return text
28+
29+
prompt = 'Call the echo tool exactly once with text "hello", then reply with only the tool result.'
30+
run_id = "harness-iter"
31+
with logger._internal_with_memory_background_logger() as memory_logger:
32+
async with agent.iter(prompt, run_id=run_id) as agent_run:
33+
async for _ in agent_run:
34+
pass
35+
spans = memory_logger.pop()
36+
37+
assert agent_run.result is not None
38+
assert agent_run.result.output.strip().lower() == "hello"
39+
assert await store.list_events(run_id=run_id)
40+
41+
run = find_span_by_name(spans, "agent_run [harness_iter]")
42+
assert run["span_attributes"]["type"] == SpanTypeAttribute.TASK
43+
assert [span for span in spans if not span.get("span_parents")] == [run]
44+
assert run["input"]["user_prompt"] == prompt
45+
assert run["output"]["output"] == agent_run.result.output
46+
47+
llm_spans = find_spans_by_type(spans, SpanTypeAttribute.LLM)
48+
assert len(llm_spans) == 2
49+
for span in llm_spans:
50+
assert span["span_parents"] == [run["span_id"]]
51+
52+
tool = find_span_by_name(spans, "echo")
53+
assert tool["span_attributes"]["type"] == SpanTypeAttribute.TOOL
54+
assert tool["span_parents"] == [run["span_id"]]
55+
assert tool["input"] == {"text": "hello"}
56+
assert tool["output"] == "hello"

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
from .tracing import (
99
_agent_get_model_wrapper,
10+
_agent_iter_wrapper,
1011
_agent_resolve_model_selection_wrapper,
1112
_agent_run_stream_events_wrapper,
1213
_agent_run_stream_sync_wrapper,
@@ -35,6 +36,13 @@ class _AgentRunPatcher(FunctionWrapperPatcher):
3536
wrapper = _agent_run_wrapper
3637

3738

39+
class _AgentIterPatcher(FunctionWrapperPatcher):
40+
name = "pydantic_ai.agent.iter"
41+
target_module = "pydantic_ai"
42+
target_path = "Agent.iter"
43+
wrapper = _agent_iter_wrapper
44+
45+
3846
class _AgentRunSyncPatcher(FunctionWrapperPatcher):
3947
name = "pydantic_ai.agent.run_sync"
4048
target_module = "pydantic_ai.agent.abstract"
@@ -88,6 +96,7 @@ class AgentPatcher(CompositeFunctionWrapperPatcher):
8896
name = "pydantic_ai.agent"
8997
sub_patchers = (
9098
_AgentRunPatcher,
99+
_AgentIterPatcher,
91100
_AgentRunSyncPatcher,
92101
_AgentToCliSyncPatcher,
93102
_AgentRunStreamPatcher,

0 commit comments

Comments
 (0)