From f166365cbf2c397d4caefcb1d04ebcb07d13c905 Mon Sep 17 00:00:00 2001 From: Douwe Maan Date: Fri, 19 Sep 2025 13:05:14 +0000 Subject: [PATCH] Fix OTel for built-in tools returning a list (e.g. Anthropic web search) --- pydantic_ai_slim/pydantic_ai/messages.py | 6 +--- tests/models/test_instrumented.py | 36 ++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/pydantic_ai_slim/pydantic_ai/messages.py b/pydantic_ai_slim/pydantic_ai/messages.py index 349420fe02..2acc726e8c 100644 --- a/pydantic_ai_slim/pydantic_ai/messages.py +++ b/pydantic_ai_slim/pydantic_ai/messages.py @@ -1161,11 +1161,7 @@ def otel_message_parts(self, settings: InstrumentationSettings) -> list[_otel_me if settings.include_content and part.content is not None: # pragma: no branch from .models.instrumented import InstrumentedModel - return_part['result'] = ( - part.content - if isinstance(part.content, str) - else {k: InstrumentedModel.serialize_any(v) for k, v in part.content.items()} - ) + return_part['result'] = InstrumentedModel.serialize_any(part.content) parts.append(return_part) return parts diff --git a/tests/models/test_instrumented.py b/tests/models/test_instrumented.py index f759fa1d56..f48dc87404 100644 --- a/tests/models/test_instrumented.py +++ b/tests/models/test_instrumented.py @@ -1359,6 +1359,22 @@ def test_message_with_builtin_tool_calls(): BuiltinToolCallPart('code_execution', {'code': '2 * 2'}, tool_call_id='tool_call_1'), BuiltinToolReturnPart('code_execution', {'output': '4'}, tool_call_id='tool_call_1'), TextPart('text2'), + BuiltinToolCallPart( + 'web_search', + '{"query": "weather: San Francisco, CA", "type": "search"}', + tool_call_id='tool_call_2', + ), + BuiltinToolReturnPart( + 'web_search', + [ + { + 'url': 'https://www.weather.com/weather/today/l/USCA0987:1:US', + 'title': 'Weather in San Francisco', + } + ], + tool_call_id='tool_call_2', + ), + TextPart('text3'), ] ), ] @@ -1387,6 +1403,26 @@ def test_message_with_builtin_tool_calls(): 'result': {'output': '4'}, }, {'type': 'text', 'content': 'text2'}, + { + 'type': 'tool_call', + 'id': 'tool_call_2', + 'name': 'web_search', + 'builtin': True, + 'arguments': '{"query": "weather: San Francisco, CA", "type": "search"}', + }, + { + 'type': 'tool_call_response', + 'id': 'tool_call_2', + 'name': 'web_search', + 'builtin': True, + 'result': [ + { + 'url': 'https://www.weather.com/weather/today/l/USCA0987:1:US', + 'title': 'Weather in San Francisco', + } + ], + }, + {'type': 'text', 'content': 'text3'}, ], } ]