Extends _sanitize_messages_for_api() with a two-pass approach: 1. Collect all tool_call_ids declared in assistant messages (handles both OpenAI 'id' and Anthropic 'call_id' field names). 2. Drop any tool-role messages whose tool_call_id was not declared by a preceding assistant message. Strictly-conformant providers (Mercury-2/Inception, newer OpenAI models) reject histories with orphaned tool results with a 400 error: 'Message has tool role, but there was no previous assistant message with a tool call.' This can happen when histories are edited, when switching between providers, or when partial messages are stored. Adds 13 regression tests covering: valid roundtrip preservation, multiple tool calls, partial orphan filtering, Anthropic call_id, edge cases (None tool_calls, missing tool_call_id, non-dict entries).
6.6 KiB
6.6 KiB