Skip to content

Commit 833df48

Browse files
fix(pydantic-ai): trace harness background tool execution
> 🤖 **This text was AI-generated.** A Harness background tool returns a pending receipt before the handler finishes. That receipt remains on the dispatch span; previously the handler’s result and its child agent runs had no execution span. Wrap the scheduled handler so it records its result or error in a Braintrust tool span with the dispatch as its explicit parent. ```text agent run -> tool dispatch -> tool execution -> child agent run ``` Co-authored-by: Abhijeet Prasad <abhijeet@braintrustdata.com> Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
1 parent 19afe35 commit 833df48

4 files changed

Lines changed: 117 additions & 1 deletion

File tree

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import asyncio
2+
3+
import pytest
4+
from braintrust import setup_pydantic_ai
5+
from braintrust.span_types import SpanTypeAttribute
6+
from braintrust.test_helpers import init_test_logger
7+
from braintrust.test_helpers import with_memory_logger as with_memory_logger
8+
from pydantic_ai import Agent
9+
from pydantic_ai.messages import ModelResponse, TextPart, ToolCallPart, ToolReturnPart
10+
from pydantic_ai.models.function import FunctionModel
11+
from pydantic_ai.models.test import TestModel
12+
13+
14+
@pytest.mark.asyncio
15+
@pytest.mark.parametrize("fails", [False, True], ids=["success", "failure"])
16+
async def test_harness_background_tool_execution(with_memory_logger, fails):
17+
background_tools = pytest.importorskip("pydantic_ai_harness.background_tools", exc_type=ModuleNotFoundError)
18+
from pydantic_ai.exceptions import ToolFailed
19+
20+
project = "test-pydantic-ai-harness"
21+
assert setup_pydantic_ai(project_name=project)
22+
init_test_logger(project)
23+
24+
call_id = "background-call"
25+
receipt_seen = asyncio.Event()
26+
child = Agent(TestModel(custom_output_text="offline answer"), name="background_child")
27+
28+
def respond(messages, _info):
29+
for message in messages:
30+
for part in message.parts:
31+
if isinstance(part, ToolReturnPart) and part.tool_call_id == call_id:
32+
assert "is running in background" in part.content
33+
receipt_seen.set()
34+
return ModelResponse(parts=[TextPart("done")])
35+
return ModelResponse(parts=[ToolCallPart("slow", {"query": "lookup"}, tool_call_id=call_id)])
36+
37+
parent = Agent(FunctionModel(respond), name="background_parent", capabilities=[background_tools.BackgroundTools()])
38+
39+
@parent.tool_plain(metadata={"background": True})
40+
async def slow(query: str) -> str:
41+
await receipt_seen.wait()
42+
if fails:
43+
raise ToolFailed(f"failed: {query}")
44+
return (await child.run(query)).output
45+
46+
assert (await parent.run("dispatch background tool")).output == "done"
47+
spans = with_memory_logger.pop()
48+
parent_span = next(s for s in spans if s["span_attributes"]["name"] == "agent_run [background_parent]")
49+
tool_spans = [s for s in spans if s["span_attributes"]["type"] == SpanTypeAttribute.TOOL]
50+
assert [span["span_attributes"]["name"] for span in tool_spans] == ["slow", "slow"]
51+
dispatch = next(s for s in tool_spans if s["span_parents"] == [parent_span["span_id"]])
52+
execution = next(s for s in tool_spans if s["span_parents"] == [dispatch["span_id"]])
53+
assert "is running in background" in dispatch["output"]
54+
assert dispatch.get("error") is None
55+
assert execution["input"] == {"query": "lookup"}
56+
assert execution["metadata"]["tool_call_id"] == dispatch["metadata"]["tool_call_id"] == call_id
57+
assert execution["context"]["span_origin"]["instrumentation"]["name"] == "pydantic-ai-auto"
58+
if fails:
59+
assert "failed: lookup" in execution["error"]
60+
assert execution.get("output") is None
61+
else:
62+
assert execution["output"] == "offline answer"
63+
assert execution.get("error") is None
64+
child_span = next(s for s in spans if s["span_attributes"]["name"] == "agent_run [background_child]")
65+
assert child_span["span_parents"] == [execution["span_id"]]

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from .harness_patchers import StepPersistencePatcher
66
from .patchers import (
77
AgentPatcher,
8+
BackgroundToolExecutionPatcher,
89
DirectModelRequestPatcher,
910
DirectModelRequestStreamPatcher,
1011
DirectModelRequestStreamSyncPatcher,
@@ -37,4 +38,5 @@ class PydanticAIIntegration(BaseIntegration):
3738
ToolManagerFunctionToolPatcher,
3839
StepPersistencePatcher,
3940
ToolCallClassificationPatcher,
41+
BackgroundToolExecutionPatcher,
4042
)

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from braintrust.integrations.base import ClassScanPatcher, CompositeFunctionWrapperPatcher, FunctionWrapperPatcher
77

88
from .tracing import (
9+
_BACKGROUND_TOOLS_CAPABILITY_MODULE,
910
_agent_get_model_wrapper,
1011
_agent_iter_wrapper,
1112
_agent_resolve_model_selection_wrapper,
@@ -15,6 +16,7 @@
1516
_agent_run_sync_wrapper,
1617
_agent_run_wrapper,
1718
_agent_to_cli_sync_wrapper,
19+
_background_tool_execution_wrapper,
1820
_create_direct_model_request_stream_sync_wrapper,
1921
_create_direct_model_request_stream_wrapper,
2022
_create_direct_model_request_sync_wrapper,
@@ -206,6 +208,14 @@ class ToolCallClassificationPatcher(FunctionWrapperPatcher):
206208
wrapper = _process_tool_calls_wrapper
207209

208210

211+
class BackgroundToolExecutionPatcher(FunctionWrapperPatcher):
212+
name = "pydantic_ai.harness.background_tool_execution"
213+
target_module = _BACKGROUND_TOOLS_CAPABILITY_MODULE
214+
target_path = "BackgroundTools.wrap_tool_execute"
215+
wrapper = _background_tool_execution_wrapper
216+
min_version: ClassVar[str] = "2.0.0"
217+
218+
209219
def wrap_agent(Agent: Any) -> Any:
210220
return AgentPatcher.wrap_target(Agent)
211221

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

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,14 @@
1010
from typing import Any
1111

1212
from braintrust.integrations.utils import _materialize_attachment, _metered_duration_metrics, _timing_metrics
13-
from braintrust.logger import _internal_get_global_state, current_span
13+
from braintrust.logger import Span, _internal_get_global_state, current_span
1414
from braintrust.logger import start_span as _bt_start_span
1515

1616

1717
_INSTRUMENTATION = "pydantic-ai-auto"
1818
_AGENT_WRAPPER_MODULES = (__name__, "braintrust.integrations.base", "wrapt.wrappers", "contextlib")
1919
_delegated_iter = contextvars.ContextVar("braintrust_pydantic_ai_delegated_iter", default=False)
20+
_BACKGROUND_TOOLS_CAPABILITY_MODULE = "pydantic_ai_harness.background_tools._capability"
2021

2122

2223
def start_span(*args, **kwargs):
@@ -48,6 +49,9 @@ class _SyncToolTraceState(_ToolTraceState):
4849
_tool_trace_state: contextvars.ContextVar[_ToolTraceState | None] = contextvars.ContextVar(
4950
"braintrust_pydantic_ai_tool_trace_state", default=None
5051
)
52+
_tool_dispatch: contextvars.ContextVar[tuple[Any, Span] | None] = contextvars.ContextVar(
53+
"braintrust_pydantic_ai_tool_dispatch", default=None
54+
)
5155

5256

5357
def wrap_agent(Agent: Any) -> Any:
@@ -1197,12 +1201,15 @@ async def _trace_tool_execution(wrapped: Any, args: Any, kwargs: Any):
11971201
deferral: CallDeferred | ApprovalRequired | None = None
11981202
with start_span(name=tool_name, type=SpanTypeAttribute.TOOL, input=input_data, metadata=metadata) as tool_span:
11991203
start_time = time.time()
1204+
dispatch_token = _tool_dispatch.set((call, tool_span))
12001205
try:
12011206
result = await wrapped(*args, **kwargs)
12021207
except (CallDeferred, ApprovalRequired) as exc:
12031208
# The tool handed the call back to the caller as DeferredToolRequests.
12041209
# That is control flow, not a tool failure, so the span must not record an error.
12051210
deferral = exc
1211+
finally:
1212+
_tool_dispatch.reset(dispatch_token)
12061213
end_time = time.time()
12071214
metrics = _timing_metrics(start_time, end_time)
12081215
if deferral is None:
@@ -1230,6 +1237,38 @@ async def _tool_manager_execute_function_tool_wrapper(wrapped: Any, instance: An
12301237
return await _trace_tool_execution(wrapped, args, kwargs)
12311238

12321239

1240+
async def _background_tool_execution_wrapper(wrapped: Any, instance: Any, args: Any, kwargs: Any):
1241+
backgrounded_call = getattr(sys.modules.get(_BACKGROUND_TOOLS_CAPABILITY_MODULE), "_backgrounded_call", None)
1242+
call = kwargs.get("call")
1243+
handler = kwargs.get("handler")
1244+
if backgrounded_call is None or call is None or handler is None or backgrounded_call.get() is call:
1245+
return await wrapped(*args, **kwargs)
1246+
1247+
dispatch = _tool_dispatch.get()
1248+
if dispatch is not None and dispatch[0] is call:
1249+
start_execution_span = dispatch[1].start_span
1250+
else:
1251+
start_execution_span = _bt_start_span
1252+
1253+
async def trace_handler(tool_args: dict[str, Any]):
1254+
if backgrounded_call.get() is not call:
1255+
return await handler(tool_args)
1256+
1257+
# Harness sets the marker in its scheduled task, after which ambient context may skip the ended dispatch span.
1258+
with start_execution_span(
1259+
name=call.tool_name,
1260+
type=SpanTypeAttribute.TOOL,
1261+
input=tool_args,
1262+
metadata={"tool_call_id": call.tool_call_id},
1263+
internal={"instrumentation": _INSTRUMENTATION},
1264+
) as execution_span:
1265+
result = await handler(tool_args)
1266+
execution_span.log(output=result)
1267+
return result
1268+
1269+
return await wrapped(*args, **{**kwargs, "handler": trace_handler})
1270+
1271+
12331272
def _create_tool_spans_from_messages(result: Any) -> None:
12341273
# Reconstruct TOOL-type spans from tool call/return message parts, using
12351274
# ModelResponse/ModelRequest timestamps to position spans in the trace.

0 commit comments

Comments
 (0)