diff --git a/src/ai_client.py b/src/ai_client.py index 2033cf84..f73d1047 100644 --- a/src/ai_client.py +++ b/src/ai_client.py @@ -2131,6 +2131,13 @@ def _trim_minimax_history(system_blocks: list[dict[str, Any]], history: list[dic removed = history.pop(1) dropped += 1 est -= _estimate_message_tokens(removed) + + # Ensure we don't leave dangling 'tool' messages if their parent 'assistant' was dropped. + # MiniMax strictly requires 'tool' messages to immediately follow 'assistant' with tool_calls. + while len(history) > 1 and history[1].get("role") == "tool": + removed_tool = history.pop(1) + dropped += 1 + est -= _estimate_message_tokens(removed_tool) return dropped def _ensure_minimax_client() -> None: