-
Notifications
You must be signed in to change notification settings - Fork 2k
feat: add built-in repair_orphaned_tool_parts history processor
#5090
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
Closed
anmolg1997
wants to merge
6
commits into
pydantic:main
from
anmolg1997:feat/repair-orphaned-tool-parts
Closed
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
8ee25f9
fix(evals): constrain judge_output reason to be concise and retry-safe
anmolg1997 a5c0e3e
feat: add built-in `repair_orphaned_tool_parts` history processor
anmolg1997 387a38e
fix: address lint, coverage, and Devin review findings
anmolg1997 40797f2
fix: use frontier model name in docstring example per repo conventions
anmolg1997 9723948
refactor: extract helpers to fix C901 complexity (24 > 15)
anmolg1997 a56ab1c
fix: resolve pyright type errors in history_processors
anmolg1997 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| """Built-in history processor functions for common message history repair tasks. | ||
|
|
||
| These functions can be passed directly to `Agent(history_processors=[...])` or | ||
| used with `capabilities.HistoryProcessor(processor=...)`. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import logging | ||
| from dataclasses import replace | ||
|
|
||
| from pydantic_ai import messages as _messages | ||
|
|
||
| __all__ = ('repair_orphaned_tool_parts',) | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def repair_orphaned_tool_parts( | ||
| messages: list[_messages.ModelMessage], | ||
| ) -> list[_messages.ModelMessage]: | ||
| """Remove orphaned tool call/return parts from message history. | ||
|
|
||
| Multi-turn agent conversations can accumulate structurally invalid history | ||
| when tool calls and their corresponding results become mismatched. Common | ||
| causes include streaming timeouts, deferred tool result drops, and history | ||
| trimming by other processors. | ||
|
|
||
| Providers like Anthropic strictly enforce that every `ToolCallPart` has a | ||
| matching `ToolReturnPart` (or `RetryPromptPart`) and vice versa; orphaned | ||
| entries cause 400 errors. | ||
|
|
||
| This processor performs a two-pass repair: | ||
|
|
||
| 1. **Orphaned returns/retries**: `ToolReturnPart` or `RetryPromptPart` whose | ||
| `tool_call_id` does not match any preceding `ToolCallPart` are removed. | ||
| 2. **Orphaned calls**: `ToolCallPart` whose `tool_call_id` does not match | ||
| any following `ToolReturnPart` or `RetryPromptPart` are removed. | ||
|
|
||
| Empty messages (all parts removed) are dropped entirely. | ||
|
|
||
| Example: | ||
| ```python | ||
| from pydantic_ai import Agent | ||
| from pydantic_ai.history_processors import repair_orphaned_tool_parts | ||
|
|
||
| agent = Agent('openai:gpt-4o', history_processors=[repair_orphaned_tool_parts]) | ||
| ``` | ||
| """ | ||
| call_ids: set[str] = set() | ||
| for message in messages: | ||
| if isinstance(message, _messages.ModelResponse): | ||
| for part in message.parts: | ||
| if isinstance(part, _messages.ToolCallPart) and part.tool_call_id: | ||
| call_ids.add(part.tool_call_id) | ||
|
|
||
| return_ids: set[str] = set() | ||
| for message in messages: | ||
| if isinstance(message, _messages.ModelRequest): | ||
| for part in message.parts: | ||
| if isinstance(part, (_messages.ToolReturnPart, _messages.RetryPromptPart)): | ||
| if part.tool_call_id: | ||
| return_ids.add(part.tool_call_id) | ||
|
|
||
| repaired: list[_messages.ModelMessage] = [] | ||
| for message in messages: | ||
| if isinstance(message, _messages.ModelRequest): | ||
| kept_parts: list[_messages.ModelRequestPart] = [] | ||
| for part in message.parts: | ||
| if isinstance(part, _messages.ToolReturnPart): | ||
| if part.tool_call_id and part.tool_call_id not in call_ids: | ||
| logger.debug( | ||
| 'Removing orphaned ToolReturnPart with tool_call_id=%r (no matching ToolCallPart)', | ||
| part.tool_call_id, | ||
| ) | ||
| continue | ||
| elif isinstance(part, _messages.RetryPromptPart): | ||
| if part.tool_name is not None and part.tool_call_id and part.tool_call_id not in call_ids: | ||
| logger.debug( | ||
| 'Removing orphaned RetryPromptPart with tool_call_id=%r (no matching ToolCallPart)', | ||
| part.tool_call_id, | ||
| ) | ||
| continue | ||
| kept_parts.append(part) | ||
|
|
||
| if kept_parts: | ||
| if len(kept_parts) != len(message.parts): | ||
| repaired.append(replace(message, parts=kept_parts)) | ||
| else: | ||
| repaired.append(message) | ||
|
|
||
| elif isinstance(message, _messages.ModelResponse): | ||
| kept_response_parts: list[_messages.ModelResponsePart] = [] | ||
| for part in message.parts: | ||
| if isinstance(part, _messages.ToolCallPart): | ||
| if part.tool_call_id and part.tool_call_id not in return_ids: | ||
| logger.debug( | ||
| 'Removing orphaned ToolCallPart with tool_call_id=%r (no matching return)', | ||
| part.tool_call_id, | ||
| ) | ||
| continue | ||
| kept_response_parts.append(part) | ||
|
|
||
| if kept_response_parts: | ||
| if len(kept_response_parts) != len(message.parts): | ||
| repaired.append(replace(message, parts=kept_response_parts)) | ||
| else: | ||
| repaired.append(message) | ||
|
|
||
| return repaired | ||
|
anmolg1997 marked this conversation as resolved.
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.