|
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): |
@@ -48,6 +49,9 @@ class _SyncToolTraceState(_ToolTraceState): |
48 | 49 | _tool_trace_state: contextvars.ContextVar[_ToolTraceState | None] = contextvars.ContextVar( |
49 | 50 | "braintrust_pydantic_ai_tool_trace_state", default=None |
50 | 51 | ) |
| 52 | +_tool_dispatch: contextvars.ContextVar[tuple[Any, Span] | None] = contextvars.ContextVar( |
| 53 | + "braintrust_pydantic_ai_tool_dispatch", default=None |
| 54 | +) |
51 | 55 |
|
52 | 56 |
|
53 | 57 | def wrap_agent(Agent: Any) -> Any: |
@@ -1197,12 +1201,15 @@ async def _trace_tool_execution(wrapped: Any, args: Any, kwargs: Any): |
1197 | 1201 | deferral: CallDeferred | ApprovalRequired | None = None |
1198 | 1202 | with start_span(name=tool_name, type=SpanTypeAttribute.TOOL, input=input_data, metadata=metadata) as tool_span: |
1199 | 1203 | start_time = time.time() |
| 1204 | + dispatch_token = _tool_dispatch.set((call, tool_span)) |
1200 | 1205 | try: |
1201 | 1206 | result = await wrapped(*args, **kwargs) |
1202 | 1207 | except (CallDeferred, ApprovalRequired) as exc: |
1203 | 1208 | # The tool handed the call back to the caller as DeferredToolRequests. |
1204 | 1209 | # That is control flow, not a tool failure, so the span must not record an error. |
1205 | 1210 | deferral = exc |
| 1211 | + finally: |
| 1212 | + _tool_dispatch.reset(dispatch_token) |
1206 | 1213 | end_time = time.time() |
1207 | 1214 | metrics = _timing_metrics(start_time, end_time) |
1208 | 1215 | if deferral is None: |
@@ -1230,6 +1237,38 @@ async def _tool_manager_execute_function_tool_wrapper(wrapped: Any, instance: An |
1230 | 1237 | return await _trace_tool_execution(wrapped, args, kwargs) |
1231 | 1238 |
|
1232 | 1239 |
|
| 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: |
| 1245 | + return await wrapped(*args, **kwargs) |
| 1246 | + |
| 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 |
| 1268 | + |
| 1269 | + return await wrapped(*args, **{**kwargs, "handler": trace_handler}) |
| 1270 | + |
| 1271 | + |
1233 | 1272 | def _create_tool_spans_from_messages(result: Any) -> None: |
1234 | 1273 | # Reconstruct TOOL-type spans from tool call/return message parts, using |
1235 | 1274 | # ModelResponse/ModelRequest timestamps to position spans in the trace. |
|
0 commit comments