{"record":{"id":"95e226d8a343e45e","repo":"BerriAI/litellm","slug":"missing-corresponding-tool-call-for-tool-response","errorCode":null,"errorMessage":"Missing corresponding tool call for tool response message. Received - message={message}, last_message_with_tool_calls={last_message_with_tool_calls}","messagePattern":"Missing corresponding tool call for tool response message\\. Received - message=(.+?), last_message_with_tool_calls=(.+?)","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"litellm/litellm_core_utils/prompt_templates/factory.py","lineNumber":1497,"sourceCode":"    if last_message_with_tool_calls:\n        tools: Final = last_message_with_tool_calls.get(\"tool_calls\", [])\n        msg_tool_call_id: Final = message.get(\"tool_call_id\", None)\n        for tool in tools:\n            prev_tool_call_id = tool.get(\"id\", None)\n            if msg_tool_call_id and prev_tool_call_id and msg_tool_call_id == prev_tool_call_id:\n                name = tool.get(\"function\", {}).get(\"name\", \"\")\n\n    # Echo the OpenAI tool_call_id on functionResponse (strip thought-signature suffix).\n    gemini_call_id: str | None = None\n    if forward_function_call_id:\n        raw_tool_call_id: Final = message.get(\"tool_call_id\")\n        if raw_tool_call_id and isinstance(raw_tool_call_id, str):\n            stripped_id: Final = raw_tool_call_id.split(THOUGHT_SIGNATURE_SEPARATOR, 1)[0]\n            if stripped_id:\n                gemini_call_id = stripped_id\n\n    if not name:\n        raise Exception(\n            f\"Missing corresponding tool call for tool response message. Received - message={message}, last_message_with_tool_calls={last_message_with_tool_calls}\"\n        )\n\n    # Parse response data - support both JSON string and plain string\n    # For Computer Use, the response should contain structured data like {\"url\": \"...\"}\n    response_data: dict\n    try:\n        if content_str.strip().startswith(\"{\") or content_str.strip().startswith(\"[\"):\n            # Try to parse as JSON (for Computer Use structured responses)\n            parsed: Final = json.loads(content_str)\n            if isinstance(parsed, dict):\n                response_data = parsed  # Use the parsed JSON directly\n            else:\n                response_data = {\"content\": content_str}\n        else:\n            response_data = {\"content\": content_str}\n    except (json.JSONDecodeError, ValueError):\n        # Not valid JSON, wrap in content field","sourceCodeStart":1479,"sourceCodeEnd":1515,"githubUrl":"https://github.com/BerriAI/litellm/blob/77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8/litellm/litellm_core_utils/prompt_templates/factory.py#L1479-L1515","documentation":"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).","triggerScenarios":"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.","commonSituations":"Agent loops persisting only tool outputs across turns or restarts; checkpoint formats that regenerate ids; splicing captured conversations into new sessions.","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"],"exampleFix":"# before: tool_call_id does not match any assistant tool call\nmessages = [\n    {\"role\": \"assistant\", \"content\": None, \"tool_calls\": [{\"id\": \"call_1\", \"type\": \"function\", \"function\": {\"name\": \"get_weather\", \"arguments\": \"{}\"}}]},\n    {\"role\": \"tool\", \"tool_call_id\": \"call_2\", \"content\": \"72F\"},\n]\n\n# after\nmessages = [\n    {\"role\": \"assistant\", \"content\": None, \"tool_calls\": [{\"id\": \"call_1\", \"type\": \"function\", \"function\": {\"name\": \"get_weather\", \"arguments\": \"{}\"}}]},\n    {\"role\": \"tool\", \"tool_call_id\": \"call_1\", \"content\": \"72F\"},\n]","handlingStrategy":"validation","validationCode":"def tool_results_are_matched(messages: list[dict]) -> bool:\n    \"\"\"Every tool message must follow an assistant turn with a matching tool_call_id.\"\"\"\n    pending_ids: set[str] = set()\n    for m in messages:\n        if m.get(\"role\") == \"assistant\":\n            pending_ids = {tc.get(\"id\") for tc in (m.get(\"tool_calls\") or []) if tc.get(\"id\")}\n        elif m.get(\"role\") == \"tool\":\n            if m.get(\"tool_call_id\") not in pending_ids:\n                return False\n            pending_ids.discard(m.get(\"tool_call_id\"))\n    return True\n\n# assert tool_results_are_matched(messages) before calling gemini models","typeGuard":null,"tryCatchPattern":"try:\n    litellm.completion(model=\"gemini/...\", messages=messages)\nexcept Exception as e:\n    if \"Missing corresponding tool call for tool response\" in str(e):\n        # drop orphan tool messages or restore the assistant tool_calls turn, then retry\n        messages = prune_orphan_tool_messages(messages)\n    else:\n        raise","preventionTips":["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"],"tags":["gemini","tool-calling","message-order","history"],"backgroundTag":"orphan-tool-response","analyzedSha":"77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8","analyzedAt":"2026-08-18T11:44:31.656Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}