feat: add repair_tool_orphans history processor

Closed
RI
7mo ago
+617-0

Summary

  • Adds a built-in repair_tool_orphans history processor that fixes structurally invalid message history, addressing the common pain point described in #4728
  • Handles dangling tool calls (injects synthetic ToolReturnPart / BuiltinToolReturnPart), orphaned tool returns (removes them), and empty requests (inserts placeholder UserPromptPart)
  • Builtin tool returns are placed in the same ModelResponse as required by Anthropic; regular tool returns go in the following ModelRequest

Usage

from pydantic_ai import Agent
from pydantic_ai.history_processors import repair_tool_orphans

agent = Agent('anthropic:claude-sonnet', history_processors=[repair_tool_orphans])

Test plan

  • 19 unit tests covering all repair scenarios: empty history, clean passthrough, dangling regular/builtin calls, orphaned returns/retries, partial answers, mixed scenarios, trailing responses, metadata preservation, multi-turn poisoned conversations
  • Integration test with Agent using FunctionModel and poisoned message history
  • All existing test_history_processor.py tests still pass (28/28)

Closes #4728

šŸ¤– Generated with Claude Code