1010from typing import Any
1111
1212from braintrust .integrations .utils import _materialize_attachment , _metered_duration_metrics , _timing_metrics
13- from braintrust .logger import Span , _internal_get_global_state , current_span
13+ from braintrust .logger import _internal_get_global_state , current_span
1414from braintrust .logger import start_span as _bt_start_span
1515
1616
@@ -48,8 +48,8 @@ class _SyncToolTraceState(_ToolTraceState):
4848_tool_trace_state : contextvars .ContextVar [_ToolTraceState | None ] = contextvars .ContextVar (
4949 "braintrust_pydantic_ai_tool_trace_state" , default = None
5050)
51- _tool_dispatch : contextvars .ContextVar [tuple [ Any , Span ] | None ] = contextvars .ContextVar (
52- "braintrust_pydantic_ai_tool_dispatch " , default = None
51+ _background_tools_run_id : contextvars .ContextVar [str | None ] = contextvars .ContextVar (
52+ "braintrust_pydantic_ai_background_tools_run_id " , default = None
5353)
5454
5555
@@ -1133,11 +1133,7 @@ def _extract_tool_call(call_or_validated: Any) -> Any:
11331133 return call_or_validated
11341134
11351135
1136- async def _trace_tool_execution (wrapped : Any , args : Any , kwargs : Any ):
1137- call = _extract_tool_call (args [0 ] if args else kwargs .get ("validated" ) or kwargs .get ("call" ))
1138- if call is None :
1139- return await wrapped (* args , ** kwargs )
1140-
1136+ async def _trace_tool_execution (call : Any , wrapped : Any , args : Any , kwargs : Any , * , deferred_is_error : bool = False ):
11411137 tool_name = getattr (call , "tool_name" , None ) or "unknown_tool"
11421138 tool_call_id = getattr (call , "tool_call_id" , None )
11431139
@@ -1154,15 +1150,14 @@ async def _trace_tool_execution(wrapped: Any, args: Any, kwargs: Any):
11541150 deferral : CallDeferred | ApprovalRequired | None = None
11551151 with start_span (name = tool_name , type = SpanTypeAttribute .TOOL , input = input_data , metadata = metadata ) as tool_span :
11561152 start_time = time .time ()
1157- dispatch_token = _tool_dispatch .set ((call , tool_span ))
11581153 try :
11591154 result = await wrapped (* args , ** kwargs )
11601155 except (CallDeferred , ApprovalRequired ) as exc :
1156+ if deferred_is_error :
1157+ raise
11611158 # The tool handed the call back to the caller as DeferredToolRequests.
11621159 # That is control flow, not a tool failure, so the span must not record an error.
11631160 deferral = exc
1164- finally :
1165- _tool_dispatch .reset (dispatch_token )
11661161 end_time = time .time ()
11671162 metrics = _timing_metrics (start_time , end_time )
11681163 if deferral is None :
@@ -1182,44 +1177,52 @@ async def _trace_tool_execution(wrapped: Any, args: Any, kwargs: Any):
11821177 return result
11831178
11841179
1185- async def _tool_manager_call_function_tool_wrapper (wrapped : Any , instance : Any , args : Any , kwargs : Any ):
1186- return await _trace_tool_execution (wrapped , args , kwargs )
1180+ async def _tool_manager_execute_tool_wrapper (wrapped : Any , instance : Any , args : Any , kwargs : Any ):
1181+ validated = args [0 ] if args else kwargs .get ("validated" ) or kwargs .get ("call" )
1182+ call = _extract_tool_call (validated )
1183+ if call is None :
1184+ return await wrapped (* args , ** kwargs )
11871185
1186+ if (
1187+ _is_background_tools_run (getattr (validated , "ctx" , None ))
1188+ and getattr (instance , "root_capability" , None ) is not None
1189+ and validated .args_valid
1190+ and validated .deferral is None
1191+ and validated .tool .tool_def .kind not in ("output" , "external" )
1192+ ):
1193+ # Only the lifecycle hook sees the actual execution, not the pending receipt.
1194+ _mark_tool_span_emitted ()
1195+ return await wrapped (* args , ** kwargs )
1196+ return await _trace_tool_execution (call , wrapped , args , kwargs )
11881197
1189- async def _tool_manager_execute_function_tool_wrapper (wrapped : Any , instance : Any , args : Any , kwargs : Any ):
1190- return await _trace_tool_execution (wrapped , args , kwargs )
11911198
1199+ def _is_background_tools_run (ctx : Any ) -> bool :
1200+ run_id = _background_tools_run_id .get ()
1201+ return run_id is not None and getattr (ctx , "run_id" , None ) == run_id
11921202
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 :
1203+
1204+ async def _background_tools_run_wrapper ( wrapped : Any , instance : Any , args : Any , kwargs : Any ):
1205+ ctx = args [ 0 ] if args else kwargs .get ("ctx " )
1206+ token = _background_tools_run_id . set ( getattr ( ctx , "run_id" , None ) )
1207+ try :
11981208 return await wrapped (* args , ** kwargs )
1209+ finally :
1210+ _background_tools_run_id .reset (token )
11991211
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
12211212
1222- return await wrapped (* args , ** {** kwargs , "handler" : trace_handler })
1213+ async def _background_tool_execution_wrapper (wrapped : Any , instance : Any , args : Any , kwargs : Any ):
1214+ ctx = args [1 ] if len (args ) > 1 else kwargs .get ("ctx" )
1215+ call = args [2 ] if len (args ) > 2 else kwargs .get ("call" )
1216+ if call is None or not _is_background_tools_run (ctx ):
1217+ return await wrapped (* args , ** kwargs )
1218+ backgrounded_call = getattr (sys .modules .get (_BACKGROUND_TOOLS_CAPABILITY_MODULE ), "_backgrounded_call" , None )
1219+ return await _trace_tool_execution (
1220+ call ,
1221+ wrapped ,
1222+ args ,
1223+ kwargs ,
1224+ deferred_is_error = backgrounded_call is not None and backgrounded_call .get () is call ,
1225+ )
12231226
12241227
12251228def _create_tool_spans_from_messages (result : Any ) -> None :
0 commit comments