BerriAI/litellm · error · Exception
Missing corresponding tool call for tool response message…
Error message
Missing corresponding tool call for tool response message. Received - message={message}, last_message_with_tool_calls={last_message_with_tool_calls} What it means
A tool-response message could not be matched to any function name: the tool_call_id had no match in the last assistant message with tool_calls (or there was none), leaving name empty. Gemini functionResponse blocks require the function name, which litellm derives from that matching assistant tool call (after stripping thought-signature suffixes from ids).
Solutions
- Ensure every tool message is preceded by an assistant message containing a tool_call with the same id
- Never trim the assistant tool_calls turn out of history while keeping its tool response
- When replaying/resuming, rewrite tool_call_id values so they match the assistant turn
Example fix
# before: tool_call_id does not match any assistant tool call
messages = [
{"role": "assistant", "content": None, "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "get_weather", "arguments": "{}"}}]},
{"role": "tool", "tool_call_id": "call_2", "content": "72F"},
]
# after
messages = [
{"role": "assistant", "content": None, "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "get_weather", "arguments": "{}"}}]},
{"role": "tool", "tool_call_id": "call_1", "content": "72F"},
] Defensive patterns
Strategy: validation
Validate before calling
def tool_results_are_matched(messages: list[dict]) -> bool:
"""Every tool message must follow an assistant turn with a matching tool_call_id."""
pending_ids: set[str] = set()
for m in messages:
if m.get("role") == "assistant":
pending_ids = {tc.get("id") for tc in (m.get("tool_calls") or []) if tc.get("id")}
elif m.get("role") == "tool":
if m.get("tool_call_id") not in pending_ids:
return False
pending_ids.discard(m.get("tool_call_id"))
return True
# assert tool_results_are_matched(messages) before calling gemini models Try / catch
try:
litellm.completion(model="gemini/...", messages=messages)
except Exception as e:
if "Missing corresponding tool call for tool response" in str(e):
# drop orphan tool messages or restore the assistant tool_calls turn, then retry
messages = prune_orphan_tool_messages(messages)
else:
raise Prevention
- Persist whole conversations (assistant tool_calls + tool responses) - never tool outputs alone
- When resuming from checkpoints, keep original tool_call_ids; do not regenerate them
- Never trim the assistant tool_calls turn while keeping its tool response in history
When it happens
Trigger: A tool message whose tool_call_id does not match any id in the preceding assistant tool_calls; sending a tool result with no prior assistant tool_calls message in history; history trimming that removed the assistant tool_calls turn but kept the tool response.
Common situations: Agent loops persisting only tool outputs across turns or restarts; checkpoint formats that regenerate ids; splicing captured conversations into new sessions.
Related errors
- Unable to convert openai tool calls=
- BedrockException - . Enable 'litellm.modify_params=True'…
- Chat provider: Invalid function argument delta
- Either 'model' or 'agent' must be provided
- Error parsing file delete response
AI-assisted analysis of BerriAI/litellm@77b7c6c40c (2026-08-18).
Data as JSON: /api/errors/95e226d8a343e45e.
Report an issue: GitHub.
Appendix: source
Thrown at litellm/litellm_core_utils/prompt_templates/factory.py:1497
if last_message_with_tool_calls:
tools: Final = last_message_with_tool_calls.get("tool_calls", [])
msg_tool_call_id: Final = message.get("tool_call_id", None)
for tool in tools:
prev_tool_call_id = tool.get("id", None)
if msg_tool_call_id and prev_tool_call_id and msg_tool_call_id == prev_tool_call_id:
name = tool.get("function", {}).get("name", "")
# Echo the OpenAI tool_call_id on functionResponse (strip thought-signature suffix).
gemini_call_id: str | None = None
if forward_function_call_id:
raw_tool_call_id: Final = message.get("tool_call_id")
if raw_tool_call_id and isinstance(raw_tool_call_id, str):
stripped_id: Final = raw_tool_call_id.split(THOUGHT_SIGNATURE_SEPARATOR, 1)[0]
if stripped_id:
gemini_call_id = stripped_id
if not name:
raise Exception(
f"Missing corresponding tool call for tool response message. Received - message={message}, last_message_with_tool_calls={last_message_with_tool_calls}"
)
# Parse response data - support both JSON string and plain string
# For Computer Use, the response should contain structured data like {"url": "..."}
response_data: dict
try:
if content_str.strip().startswith("{") or content_str.strip().startswith("["):
# Try to parse as JSON (for Computer Use structured responses)
parsed: Final = json.loads(content_str)
if isinstance(parsed, dict):
response_data = parsed # Use the parsed JSON directly
else:
response_data = {"content": content_str}
else:
response_data = {"content": content_str}
except (json.JSONDecodeError, ValueError):
# Not valid JSON, wrap in content fieldView on GitHub (pinned to 77b7c6c40c)