|
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): |
@@ -46,6 +47,9 @@ class _SyncToolTraceState(_ToolTraceState): |
46 | 47 | _tool_trace_state: contextvars.ContextVar[_ToolTraceState | None] = contextvars.ContextVar( |
47 | 48 | "braintrust_pydantic_ai_tool_trace_state", default=None |
48 | 49 | ) |
| 50 | +_tool_dispatch: contextvars.ContextVar[tuple[Any, Span] | None] = contextvars.ContextVar( |
| 51 | + "braintrust_pydantic_ai_tool_dispatch", default=None |
| 52 | +) |
49 | 53 |
|
50 | 54 |
|
51 | 55 | def wrap_agent(Agent: Any) -> Any: |
@@ -1142,12 +1146,15 @@ async def _trace_tool_execution(wrapped: Any, args: Any, kwargs: Any): |
1142 | 1146 | deferral: CallDeferred | ApprovalRequired | None = None |
1143 | 1147 | with start_span(name=tool_name, type=SpanTypeAttribute.TOOL, input=input_data, metadata=metadata) as tool_span: |
1144 | 1148 | start_time = time.time() |
| 1149 | + dispatch_token = _tool_dispatch.set((call, tool_span)) |
1145 | 1150 | try: |
1146 | 1151 | result = await wrapped(*args, **kwargs) |
1147 | 1152 | except (CallDeferred, ApprovalRequired) as exc: |
1148 | 1153 | # The tool handed the call back to the caller as DeferredToolRequests. |
1149 | 1154 | # That is control flow, not a tool failure, so the span must not record an error. |
1150 | 1155 | deferral = exc |
| 1156 | + finally: |
| 1157 | + _tool_dispatch.reset(dispatch_token) |
1151 | 1158 | end_time = time.time() |
1152 | 1159 | metrics = _timing_metrics(start_time, end_time) |
1153 | 1160 | if deferral is None: |
@@ -1175,6 +1182,38 @@ async def _tool_manager_execute_function_tool_wrapper(wrapped: Any, instance: An |
1175 | 1182 | return await _trace_tool_execution(wrapped, args, kwargs) |
1176 | 1183 |
|
1177 | 1184 |
|
| 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: |
| 1190 | + return await wrapped(*args, **kwargs) |
| 1191 | + |
| 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 |
| 1213 | + |
| 1214 | + return await wrapped(*args, **{**kwargs, "handler": trace_handler}) |
| 1215 | + |
| 1216 | + |
1178 | 1217 | def _create_tool_spans_from_messages(result: Any) -> None: |
1179 | 1218 | # Reconstruct TOOL-type spans from tool call/return message parts, using |
1180 | 1219 | # ModelResponse/ModelRequest timestamps to position spans in the trace. |
|
0 commit comments