Skip to content

Commit bdf030a

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 aa8d50e commit bdf030a

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,
@@ -35,4 +36,5 @@ class PydanticAIIntegration(BaseIntegration):
3536
DirectModelRequestStreamSyncPatcher,
3637
ToolManagerFunctionToolPatcher,
3738
StepPersistencePatcher,
39+
BackgroundToolExecutionPatcher,
3840
)

‎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,
@@ -198,6 +200,14 @@ class ToolManagerFunctionToolPatcher(CompositeFunctionWrapperPatcher):
198200
)
199201

200202

203+
class BackgroundToolExecutionPatcher(FunctionWrapperPatcher):
204+
name = "pydantic_ai.harness.background_tool_execution"
205+
target_module = _BACKGROUND_TOOLS_CAPABILITY_MODULE
206+
target_path = "BackgroundTools.wrap_tool_execute"
207+
wrapper = _background_tool_execution_wrapper
208+
min_version: ClassVar[str] = "2.0.0"
209+
210+
201211
def wrap_agent(Agent: Any) -> Any:
202212
return AgentPatcher.wrap_target(Agent)
203213

‎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):
@@ -47,6 +48,9 @@ class _SyncToolTraceState(_ToolTraceState):
4748
_tool_trace_state: contextvars.ContextVar[_ToolTraceState | None] = contextvars.ContextVar(
4849
"braintrust_pydantic_ai_tool_trace_state", default=None
4950
)
51+
_tool_dispatch: contextvars.ContextVar[tuple[Any, Span] | None] = contextvars.ContextVar(
52+
"braintrust_pydantic_ai_tool_dispatch", default=None
53+
)
5054

5155

5256
def wrap_agent(Agent: Any) -> Any:
@@ -1150,12 +1154,15 @@ async def _trace_tool_execution(wrapped: Any, args: Any, kwargs: Any):
11501154
deferral: CallDeferred | ApprovalRequired | None = None
11511155
with start_span(name=tool_name, type=SpanTypeAttribute.TOOL, input=input_data, metadata=metadata) as tool_span:
11521156
start_time = time.time()
1157+
dispatch_token = _tool_dispatch.set((call, tool_span))
11531158
try:
11541159
result = await wrapped(*args, **kwargs)
11551160
except (CallDeferred, ApprovalRequired) as exc:
11561161
# The tool handed the call back to the caller as DeferredToolRequests.
11571162
# That is control flow, not a tool failure, so the span must not record an error.
11581163
deferral = exc
1164+
finally:
1165+
_tool_dispatch.reset(dispatch_token)
11591166
end_time = time.time()
11601167
metrics = _timing_metrics(start_time, end_time)
11611168
if deferral is None:
@@ -1183,6 +1190,38 @@ async def _tool_manager_execute_function_tool_wrapper(wrapped: Any, instance: An
11831190
return await _trace_tool_execution(wrapped, args, kwargs)
11841191

11851192

1193+
async def _background_tool_execution_wrapper(wrapped: Any, instance: Any, args: Any, kwargs: Any):
1194+
backgrounded_call = getattr(sys.modules.get(_BACKGROUND_TOOLS_CAPABILITY_MODULE), "_backgrounded_call", None)
1195+
call = kwargs.get("call")
1196+
handler = kwargs.get("handler")
1197+
if backgrounded_call is None or call is None or handler is None or backgrounded_call.get() is call:
1198+
return await wrapped(*args, **kwargs)
1199+
1200+
dispatch = _tool_dispatch.get()
1201+
if dispatch is not None and dispatch[0] is call:
1202+
start_execution_span = dispatch[1].start_span
1203+
else:
1204+
start_execution_span = _bt_start_span
1205+
1206+
async def trace_handler(tool_args: dict[str, Any]):
1207+
if backgrounded_call.get() is not call:
1208+
return await handler(tool_args)
1209+
1210+
# Harness sets the marker in its scheduled task, after which ambient context may skip the ended dispatch span.
1211+
with start_execution_span(
1212+
name=call.tool_name,
1213+
type=SpanTypeAttribute.TOOL,
1214+
input=tool_args,
1215+
metadata={"tool_call_id": call.tool_call_id},
1216+
internal={"instrumentation": _INSTRUMENTATION},
1217+
) as execution_span:
1218+
result = await handler(tool_args)
1219+
execution_span.log(output=result)
1220+
return result
1221+
1222+
return await wrapped(*args, **{**kwargs, "handler": trace_handler})
1223+
1224+
11861225
def _create_tool_spans_from_messages(result: Any) -> None:
11871226
# Reconstruct TOOL-type spans from tool call/return message parts, using
11881227
# ModelResponse/ModelRequest timestamps to position spans in the trace.

0 commit comments

Comments
 (0)