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
@@ -49,8 +49,8 @@ class _SyncToolTraceState(_ToolTraceState):
4949_tool_trace_state : contextvars .ContextVar [_ToolTraceState | None ] = contextvars .ContextVar (
5050 "braintrust_pydantic_ai_tool_trace_state" , default = None
5151)
52- _tool_dispatch : contextvars .ContextVar [tuple [ Any , Span ] | None ] = contextvars .ContextVar (
53- "braintrust_pydantic_ai_tool_dispatch " , default = None
52+ _background_tools_run_id : contextvars .ContextVar [str | None ] = contextvars .ContextVar (
53+ "braintrust_pydantic_ai_background_tools_run_id " , default = None
5454)
5555
5656
@@ -1176,40 +1176,40 @@ async def _process_tool_calls_wrapper(wrapped: Any, instance: Any, args: Any, kw
11761176 yield event
11771177
11781178
1179- async def _trace_tool_execution (wrapped : Any , args : Any , kwargs : Any ):
1180- call_or_validated = args [0 ] if args else kwargs .get ("validated" ) or kwargs .get ("call" )
1181- call = _extract_tool_call (call_or_validated )
1182- if call is None :
1183- return await wrapped (* args , ** kwargs )
1184-
1179+ async def _trace_tool_execution (
1180+ call : Any ,
1181+ wrapped : Any ,
1182+ args : Any ,
1183+ kwargs : Any ,
1184+ * ,
1185+ ctx : Any ,
1186+ args_valid : bool = True ,
1187+ deferred_is_error : bool = False ,
1188+ ):
11851189 from pydantic_ai .exceptions import ApprovalRequired , CallDeferred
11861190
1187- if isinstance (getattr (call_or_validated , "deferral" , None ), (ApprovalRequired , CallDeferred )):
1188- return await wrapped (* args , ** kwargs )
1189-
11901191 tool_name = getattr (call , "tool_name" , None ) or "unknown_tool"
11911192 tool_call_id = getattr (call , "tool_call_id" , None )
11921193
11931194 input_data = _tool_call_input (call )
11941195 metadata = {"tool_call_id" : tool_call_id } if tool_call_id else {}
1195- if getattr ( call_or_validated , " args_valid" , True ) :
1196+ if args_valid :
11961197 metadata ["tool_outcome" ] = "executed"
1197- if getattr (getattr ( call_or_validated , " ctx" , None ) , "tool_call_approved" , False ):
1198+ if getattr (ctx , "tool_call_approved" , False ):
11981199 metadata ["tool_approval" ] = "approved"
11991200
12001201 _mark_tool_span_emitted ()
12011202 deferral : CallDeferred | ApprovalRequired | None = None
12021203 with start_span (name = tool_name , type = SpanTypeAttribute .TOOL , input = input_data , metadata = metadata ) as tool_span :
12031204 start_time = time .time ()
1204- dispatch_token = _tool_dispatch .set ((call , tool_span ))
12051205 try :
12061206 result = await wrapped (* args , ** kwargs )
12071207 except (CallDeferred , ApprovalRequired ) as exc :
1208+ if deferred_is_error :
1209+ raise
12081210 # The tool handed the call back to the caller as DeferredToolRequests.
12091211 # That is control flow, not a tool failure, so the span must not record an error.
12101212 deferral = exc
1211- finally :
1212- _tool_dispatch .reset (dispatch_token )
12131213 end_time = time .time ()
12141214 metrics = _timing_metrics (start_time , end_time )
12151215 if deferral is None :
@@ -1229,44 +1229,56 @@ async def _trace_tool_execution(wrapped: Any, args: Any, kwargs: Any):
12291229 return result
12301230
12311231
1232- async def _tool_manager_call_function_tool_wrapper (wrapped : Any , instance : Any , args : Any , kwargs : Any ):
1233- return await _trace_tool_execution ( wrapped , args , kwargs )
1232+ async def _tool_manager_execute_tool_wrapper (wrapped : Any , instance : Any , args : Any , kwargs : Any ):
1233+ from pydantic_ai . exceptions import ApprovalRequired , CallDeferred
12341234
1235+ validated = args [0 ] if args else kwargs .get ("validated" ) or kwargs .get ("call" )
1236+ call = _extract_tool_call (validated )
1237+ if call is None or isinstance (getattr (validated , "deferral" , None ), (ApprovalRequired , CallDeferred )):
1238+ return await wrapped (* args , ** kwargs )
12351239
1236- async def _tool_manager_execute_function_tool_wrapper (wrapped : Any , instance : Any , args : Any , kwargs : Any ):
1237- return await _trace_tool_execution (wrapped , args , kwargs )
1240+ ctx = getattr (validated , "ctx" , None )
1241+ args_valid = getattr (validated , "args_valid" , True )
1242+ if (
1243+ _is_background_tools_run (ctx )
1244+ and getattr (instance , "root_capability" , None ) is not None
1245+ and args_valid
1246+ and validated .tool .tool_def .kind not in ("output" , "external" )
1247+ ):
1248+ # Only the lifecycle hook sees the actual execution, not the pending receipt.
1249+ _mark_tool_span_emitted ()
1250+ return await wrapped (* args , ** kwargs )
1251+ return await _trace_tool_execution (call , wrapped , args , kwargs , ctx = ctx , args_valid = args_valid )
12381252
12391253
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 :
1254+ def _is_background_tools_run (ctx : Any ) -> bool :
1255+ run_id = _background_tools_run_id .get ()
1256+ return run_id is not None and getattr (ctx , "run_id" , None ) == run_id
1257+
1258+
1259+ async def _background_tools_run_wrapper (wrapped : Any , instance : Any , args : Any , kwargs : Any ):
1260+ ctx = args [0 ] if args else kwargs .get ("ctx" )
1261+ token = _background_tools_run_id .set (getattr (ctx , "run_id" , None ))
1262+ try :
12451263 return await wrapped (* args , ** kwargs )
1264+ finally :
1265+ _background_tools_run_id .reset (token )
12461266
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
12681267
1269- return await wrapped (* args , ** {** kwargs , "handler" : trace_handler })
1268+ async def _background_tool_execution_wrapper (wrapped : Any , instance : Any , args : Any , kwargs : Any ):
1269+ ctx = args [1 ] if len (args ) > 1 else kwargs .get ("ctx" )
1270+ call = args [2 ] if len (args ) > 2 else kwargs .get ("call" )
1271+ if call is None or not _is_background_tools_run (ctx ):
1272+ return await wrapped (* args , ** kwargs )
1273+ backgrounded_call = getattr (sys .modules .get (_BACKGROUND_TOOLS_CAPABILITY_MODULE ), "_backgrounded_call" , None )
1274+ return await _trace_tool_execution (
1275+ call ,
1276+ wrapped ,
1277+ args ,
1278+ kwargs ,
1279+ ctx = ctx ,
1280+ deferred_is_error = backgrounded_call is not None and backgrounded_call .get () is call ,
1281+ )
12701282
12711283
12721284def _create_tool_spans_from_messages (result : Any ) -> None :
0 commit comments