Skip to content

Ask model to try again if it produced a response without text or tool call parts (e.g. only thinking) #2469

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions pydantic_ai_slim/pydantic_ai/_agent_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,24 @@ def is_agent_node(
return isinstance(node, AgentNode)


def _create_thinking_retry_request(parts: list[_messages.ModelResponsePart]) -> _messages.ModelRequest | None:
"""Handle thinking-only responses (responses that contain only ThinkingPart instances).

This can happen with models that support thinking mode when they don't provide
actionable output alongside their thinking content.
"""
thinking_parts = [p for p in parts if isinstance(p, _messages.ThinkingPart)]
if thinking_parts:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can drop this check and always try to get the model to try again instead of raising a hard error.

# Create the retry request using UserPromptPart for API compatibility
# We'll use a special content marker to detect this is a thinking retry
retry_part = _messages.UserPromptPart(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use a RetryPromptPart as we do here:

m = _messages.RetryPromptPart(
content='Plain text responses are not permitted, please include your response in a tool call',
)

'Based on your thinking above, you MUST now provide '
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we don't currently send back the thinking parts, the model won't know what this refers to. Can we simplify the message to be something more generic like "Responses without text or tool calls are not permitted." and see if that's enough to get the model to do better?

Note that wrapping it in a RetryPromptPart as suggested above already adds Fix the errors and try again. after this message:

def model_response(self) -> str:
"""Return a string message describing why the retry is requested."""
if isinstance(self.content, str):
if self.tool_name is None:
description = f'Validation feedback:\n{self.content}'
else:
description = self.content
else:
json_errors = error_details_ta.dump_json(self.content, exclude={'__all__': {'ctx'}}, indent=2)
description = f'{len(self.content)} validation errors: {json_errors.decode()}'
return f'{description}\n\nFix the errors and try again.'

'a specific answer or use the available tools to complete the task. '
'Do not respond with only thinking content. Provide actionable output.'
)
return _messages.ModelRequest(parts=[retry_part])


@dataclasses.dataclass
class UserPromptNode(AgentNode[DepsT, NodeRunEndT]):
"""The node that handles the user prompt and instructions."""
Expand Down Expand Up @@ -435,8 +453,7 @@ async def _run_stream( # noqa: C901
) -> AsyncIterator[_messages.HandleResponseEvent]:
if self._events_iterator is None:
# Ensure that the stream is only run once

async def _run_stream() -> AsyncIterator[_messages.HandleResponseEvent]:
async def _run_stream() -> AsyncIterator[_messages.HandleResponseEvent]: # noqa: C901
texts: list[str] = []
tool_calls: list[_messages.ToolCallPart] = []
for part in self.model_response.parts:
Expand Down Expand Up @@ -482,6 +499,12 @@ async def _run_stream() -> AsyncIterator[_messages.HandleResponseEvent]:
self._next_node = await self._handle_text_response(ctx, last_texts)
return

# If there are no preceding model responses, we prompt the model to try again and provide actionable output.
breakpoint()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please remove this breakpoint

if retry_request := _create_thinking_retry_request(self.model_response.parts):
self._next_node = ModelRequestNode[DepsT, NodeRunEndT](request=retry_request)
return

raise exceptions.UnexpectedModelBehavior('Received empty model response')

self._events_iterator = _run_stream()
Expand Down
5 changes: 4 additions & 1 deletion pydantic_ai_slim/pydantic_ai/models/google.py
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,10 @@ async def _map_messages(self, messages: list[ModelMessage]) -> tuple[ContentDict
message_parts = [{'text': ''}]
contents.append({'role': 'user', 'parts': message_parts})
elif isinstance(m, ModelResponse):
contents.append(_content_model_response(m))
model_content = _content_model_response(m)
# Skip model responses with empty parts (e.g., thinking-only responses)
if model_content.get('parts'):
contents.append(model_content)
else:
assert_never(m)
if instructions := self._get_instructions(messages):
Expand Down
Loading