Skip to content

Commit 916a8e1

Browse files
WorkWork
authored andcommitted
Use tool_retry.content, without surrounding error message.
1 parent b41f23b commit 916a8e1

File tree

2 files changed

+35
-3
lines changed

2 files changed

+35
-3
lines changed

pydantic_ai_slim/pydantic_ai/exceptions.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,23 @@ class ToolRetryError(Exception):
188188

189189
def __init__(self, tool_retry: RetryPromptPart):
190190
self.tool_retry = tool_retry
191-
super().__init__(tool_retry.model_response())
191+
super().__init__(_format_tool_retry_message(tool_retry))
192+
193+
194+
def _format_tool_retry_message(tool_retry: RetryPromptPart) -> str:
195+
"""Format a human-readable error message for ToolRetryError."""
196+
content = tool_retry.content
197+
if isinstance(content, str):
198+
return f"Tool '{tool_retry.tool_name}' failed: {content}"
199+
200+
# Format list of ErrorDetails in a human-readable way
201+
error_count = len(content)
202+
error_word = 'error' if error_count == 1 else 'errors'
203+
lines = [f"Tool '{tool_retry.tool_name}' failed: {error_count} validation {error_word}"]
204+
for error in content:
205+
loc = '.'.join(str(loc) for loc in error['loc'])
206+
lines.append(f' {loc}: {error["msg"]}')
207+
return '\n'.join(lines)
192208

193209

194210
class IncompleteToolCall(UnexpectedModelBehavior):

tests/test_exceptions.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from typing import Any
55

66
import pytest
7+
from pydantic_core import ErrorDetails
78

89
from pydantic_ai import ModelRetry
910
from pydantic_ai.exceptions import (
@@ -67,7 +68,22 @@ def test_exceptions_hashable(exc_factory: Callable[[], Any]):
6768

6869
def test_tool_retry_error_str():
6970
"""Test that ToolRetryError has a meaningful string representation."""
70-
7171
part = RetryPromptPart(content='Invalid query syntax', tool_name='sql_query')
7272
error = ToolRetryError(part)
73-
assert 'Invalid query syntax' in str(error)
73+
assert str(error) == "Tool 'sql_query' failed: Invalid query syntax"
74+
75+
76+
def test_tool_retry_error_str_with_error_details():
77+
"""Test that ToolRetryError handles list of ErrorDetails content."""
78+
error_details: list[ErrorDetails] = [
79+
{'type': 'missing', 'loc': ('field1',), 'msg': 'Field required', 'input': {}},
80+
{'type': 'string_type', 'loc': ('field2',), 'msg': 'Input should be a valid string', 'input': 123},
81+
]
82+
part = RetryPromptPart(content=error_details, tool_name='my_tool')
83+
error = ToolRetryError(part)
84+
85+
expected = """\
86+
Tool 'my_tool' failed: 2 validation errors
87+
field1: Field required
88+
field2: Input should be a valid string"""
89+
assert str(error) == expected

0 commit comments

Comments
 (0)