|
10 | 10 | from typing import Any |
11 | 11 |
|
12 | 12 | 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 |
14 | 14 | from braintrust.logger import start_span as _bt_start_span |
15 | 15 |
|
16 | 16 |
|
17 | 17 | _INSTRUMENTATION = "pydantic-ai-auto" |
18 | 18 | _AGENT_WRAPPER_MODULES = (__name__, "braintrust.integrations.base", "wrapt.wrappers", "contextlib") |
19 | 19 | _delegated_iter = contextvars.ContextVar("braintrust_pydantic_ai_delegated_iter", default=False) |
| 20 | +_BACKGROUND_TOOLS_CAPABILITY_MODULE = "pydantic_ai_harness.background_tools._capability" |
20 | 21 |
|
21 | 22 |
|
22 | 23 | def start_span(*args, **kwargs): |
@@ -47,6 +48,9 @@ class _SyncToolTraceState(_ToolTraceState): |
47 | 48 | _tool_trace_state: contextvars.ContextVar[_ToolTraceState | None] = contextvars.ContextVar( |
48 | 49 | "braintrust_pydantic_ai_tool_trace_state", default=None |
49 | 50 | ) |
| 51 | +_tool_dispatch: contextvars.ContextVar[tuple[Any, Span] | None] = contextvars.ContextVar( |
| 52 | + "braintrust_pydantic_ai_tool_dispatch", default=None |
| 53 | +) |
50 | 54 |
|
51 | 55 |
|
52 | 56 | def wrap_agent(Agent: Any) -> Any: |
@@ -1150,12 +1154,15 @@ async def _trace_tool_execution(wrapped: Any, args: Any, kwargs: Any): |
1150 | 1154 | deferral: CallDeferred | ApprovalRequired | None = None |
1151 | 1155 | with start_span(name=tool_name, type=SpanTypeAttribute.TOOL, input=input_data, metadata=metadata) as tool_span: |
1152 | 1156 | start_time = time.time() |
| 1157 | + dispatch_token = _tool_dispatch.set((call, tool_span)) |
1153 | 1158 | try: |
1154 | 1159 | result = await wrapped(*args, **kwargs) |
1155 | 1160 | except (CallDeferred, ApprovalRequired) as exc: |
1156 | 1161 | # The tool handed the call back to the caller as DeferredToolRequests. |
1157 | 1162 | # That is control flow, not a tool failure, so the span must not record an error. |
1158 | 1163 | deferral = exc |
| 1164 | + finally: |
| 1165 | + _tool_dispatch.reset(dispatch_token) |
1159 | 1166 | end_time = time.time() |
1160 | 1167 | metrics = _timing_metrics(start_time, end_time) |
1161 | 1168 | if deferral is None: |
@@ -1183,6 +1190,38 @@ async def _tool_manager_execute_function_tool_wrapper(wrapped: Any, instance: An |
1183 | 1190 | return await _trace_tool_execution(wrapped, args, kwargs) |
1184 | 1191 |
|
1185 | 1192 |
|
| 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 | + |
1186 | 1225 | def _create_tool_spans_from_messages(result: Any) -> None: |
1187 | 1226 | # Reconstruct TOOL-type spans from tool call/return message parts, using |
1188 | 1227 | # ModelResponse/ModelRequest timestamps to position spans in the trace. |
|
0 commit comments