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
@@ -47,8 +47,8 @@ class _SyncToolTraceState(_ToolTraceState):
4747_tool_trace_state : contextvars .ContextVar [_ToolTraceState | None ] = contextvars .ContextVar (
4848 "braintrust_pydantic_ai_tool_trace_state" , default = None
4949)
50- _tool_dispatch : contextvars .ContextVar [tuple [ Any , Span ] | None ] = contextvars .ContextVar (
51- "braintrust_pydantic_ai_tool_dispatch " , default = None
50+ _background_tools_run_id : contextvars .ContextVar [str | None ] = contextvars .ContextVar (
51+ "braintrust_pydantic_ai_background_tools_run_id " , default = None
5252)
5353
5454
@@ -1125,11 +1125,7 @@ def _extract_tool_call(call_or_validated: Any) -> Any:
11251125 return call_or_validated
11261126
11271127
1128- async def _trace_tool_execution (wrapped : Any , args : Any , kwargs : Any ):
1129- call = _extract_tool_call (args [0 ] if args else kwargs .get ("validated" ) or kwargs .get ("call" ))
1130- if call is None :
1131- return await wrapped (* args , ** kwargs )
1132-
1128+ async def _trace_tool_execution (call : Any , wrapped : Any , args : Any , kwargs : Any , * , deferred_is_error : bool = False ):
11331129 tool_name = getattr (call , "tool_name" , None ) or "unknown_tool"
11341130 tool_call_id = getattr (call , "tool_call_id" , None )
11351131
@@ -1146,15 +1142,14 @@ async def _trace_tool_execution(wrapped: Any, args: Any, kwargs: Any):
11461142 deferral : CallDeferred | ApprovalRequired | None = None
11471143 with start_span (name = tool_name , type = SpanTypeAttribute .TOOL , input = input_data , metadata = metadata ) as tool_span :
11481144 start_time = time .time ()
1149- dispatch_token = _tool_dispatch .set ((call , tool_span ))
11501145 try :
11511146 result = await wrapped (* args , ** kwargs )
11521147 except (CallDeferred , ApprovalRequired ) as exc :
1148+ if deferred_is_error :
1149+ raise
11531150 # The tool handed the call back to the caller as DeferredToolRequests.
11541151 # That is control flow, not a tool failure, so the span must not record an error.
11551152 deferral = exc
1156- finally :
1157- _tool_dispatch .reset (dispatch_token )
11581153 end_time = time .time ()
11591154 metrics = _timing_metrics (start_time , end_time )
11601155 if deferral is None :
@@ -1174,44 +1169,52 @@ async def _trace_tool_execution(wrapped: Any, args: Any, kwargs: Any):
11741169 return result
11751170
11761171
1177- async def _tool_manager_call_function_tool_wrapper (wrapped : Any , instance : Any , args : Any , kwargs : Any ):
1178- return await _trace_tool_execution (wrapped , args , kwargs )
1172+ async def _tool_manager_execute_tool_wrapper (wrapped : Any , instance : Any , args : Any , kwargs : Any ):
1173+ validated = args [0 ] if args else kwargs .get ("validated" ) or kwargs .get ("call" )
1174+ call = _extract_tool_call (validated )
1175+ if call is None :
1176+ return await wrapped (* args , ** kwargs )
11791177
1178+ if (
1179+ _is_background_tools_run (getattr (validated , "ctx" , None ))
1180+ and getattr (instance , "root_capability" , None ) is not None
1181+ and validated .args_valid
1182+ and validated .deferral is None
1183+ and validated .tool .tool_def .kind not in ("output" , "external" )
1184+ ):
1185+ # Only the lifecycle hook sees the actual execution, not the pending receipt.
1186+ _mark_tool_span_emitted ()
1187+ return await wrapped (* args , ** kwargs )
1188+ return await _trace_tool_execution (call , wrapped , args , kwargs )
11801189
1181- async def _tool_manager_execute_function_tool_wrapper (wrapped : Any , instance : Any , args : Any , kwargs : Any ):
1182- return await _trace_tool_execution (wrapped , args , kwargs )
11831190
1191+ def _is_background_tools_run (ctx : Any ) -> bool :
1192+ run_id = _background_tools_run_id .get ()
1193+ return run_id is not None and getattr (ctx , "run_id" , None ) == run_id
11841194
1185- async def _background_tool_execution_wrapper ( wrapped : Any , instance : Any , args : Any , kwargs : Any ):
1186- backgrounded_call = getattr ( sys . modules . get ( _BACKGROUND_TOOLS_CAPABILITY_MODULE ), "_backgrounded_call" , None )
1187- call = kwargs .get ("call " )
1188- handler = kwargs . get ( "handler" )
1189- if backgrounded_call is None or call is None or handler is None or backgrounded_call . get () is call :
1195+
1196+ async def _background_tools_run_wrapper ( wrapped : Any , instance : Any , args : Any , kwargs : Any ):
1197+ ctx = args [ 0 ] if args else kwargs .get ("ctx " )
1198+ token = _background_tools_run_id . set ( getattr ( ctx , "run_id" , None ) )
1199+ try :
11901200 return await wrapped (* args , ** kwargs )
1201+ finally :
1202+ _background_tools_run_id .reset (token )
11911203
1192- dispatch = _tool_dispatch .get ()
1193- if dispatch is not None and dispatch [0 ] is call :
1194- start_execution_span = dispatch [1 ].start_span
1195- else :
1196- start_execution_span = _bt_start_span
1197-
1198- async def trace_handler (tool_args : dict [str , Any ]):
1199- if backgrounded_call .get () is not call :
1200- return await handler (tool_args )
1201-
1202- # Harness sets the marker in its scheduled task, after which ambient context may skip the ended dispatch span.
1203- with start_execution_span (
1204- name = call .tool_name ,
1205- type = SpanTypeAttribute .TOOL ,
1206- input = tool_args ,
1207- metadata = {"tool_call_id" : call .tool_call_id },
1208- internal = {"instrumentation" : _INSTRUMENTATION },
1209- ) as execution_span :
1210- result = await handler (tool_args )
1211- execution_span .log (output = result )
1212- return result
12131204
1214- return await wrapped (* args , ** {** kwargs , "handler" : trace_handler })
1205+ async def _background_tool_execution_wrapper (wrapped : Any , instance : Any , args : Any , kwargs : Any ):
1206+ ctx = args [1 ] if len (args ) > 1 else kwargs .get ("ctx" )
1207+ call = args [2 ] if len (args ) > 2 else kwargs .get ("call" )
1208+ if call is None or not _is_background_tools_run (ctx ):
1209+ return await wrapped (* args , ** kwargs )
1210+ backgrounded_call = getattr (sys .modules .get (_BACKGROUND_TOOLS_CAPABILITY_MODULE ), "_backgrounded_call" , None )
1211+ return await _trace_tool_execution (
1212+ call ,
1213+ wrapped ,
1214+ args ,
1215+ kwargs ,
1216+ deferred_is_error = backgrounded_call is not None and backgrounded_call .get () is call ,
1217+ )
12151218
12161219
12171220def _create_tool_spans_from_messages (result : Any ) -> None :
0 commit comments