Why do tool calls in multi-turn conversations fail with invalid tool_call_id errors and how do you format history? | A1Lab@HamzaM to AI & LLMEnglish • 5 days ago

Why do tool calls in multi-turn conversations fail with invalid tool_call_id errors and how do you format history?

message-square
0

Why invalid tool_call_id Errors Happen in Multi-Turn Tool Loops

When an LLM calls a tool (function), the assistant message includes one or more tool_calls (each with a unique id), and your app must return a matching tool message with the exact same tool_call_id. invalid tool_call_id errors usually happen when the message list gets out of sync:

  • Missing assistant tool-call message: Sending a role: "tool" message without the preceding role: "assistant" message that declared that tool_call_id.
  • Missing tool response for a tool call: An assistant message requested tool_calls (especially multiple parallel tool calls), but one or more tool_call_id responses were not included before sending the next request.
  • History trimming or sliding windows: Cutting old messages to save tokens can drop the assistant’s tool_calls message while keeping the tool result (or vice versa).
  • Id mismatch or reuse across turns: Changing, re-generating, or reusing IDs across turns or providers instead of copying the exact ID returned by the model.
  • Cancelled or failed tool execution: If a tool throws an error or is skipped, forgetting to still send a tool message (with an error payload) for that tool_call_id leaves the call unanswered.

How to Format Multi-Turn Tool History Cleanly

  1. Keep the exact sequence: Append the user message -> assistant message (containing tool_calls) -> one role: "tool" message per tool_call_id -> next assistant/user messages.
  2. Match every tool_call.id: Every id in assistant.tool_calls must have a corresponding tool message with tool_call_id: call.id and stringified content.
  3. Trim in complete tool groups: When pruning old history, remove whole turn/tool exchanges together rather than splitting an assistant tool_calls message from its tool replies.
  4. Always return a tool response: Even if a tool fails or times out, return a JSON string error message with the matching tool_call_id so the conversation stays valid.

JavaScript Example Formatting Tool-Call History

async function runToolTurn(openai, messages, tools, executeTool) {
  const completion = await openai.chat.completions.create({
    model: "gpt-4o-mini",
    messages,
    tools,
  });

  const assistantMsg = completion.choices[0].message;

  // 1. Append the assistant message (including its tool_calls) verbatim
  messages.push({
    role: "assistant",
    content: assistantMsg.content ?? null,
    tool_calls: assistantMsg.tool_calls,
  });

  // If no tools were called, this turn is finished
  if (!assistantMsg.tool_calls || assistantMsg.tool_calls.length === 0) {
    return assistantMsg.content ?? "";
  }

  // 2. Execute each requested tool and append a matching 'tool' message for every id
  for (const call of assistantMsg.tool_calls) {
    let toolOutput;
    try {
      const args = JSON.parse(call.function.arguments || "{}");
      const result = await executeTool(call.function.name, args);
      toolOutput = typeof result === "string" ? result : JSON.stringify(result);
    } catch (err) {
      toolOutput = JSON.stringify({ error: err.message || "Tool execution failed" });
    }

    messages.push({
      role: "tool",
      tool_call_id: call.id,
      content: toolOutput,
    });
  }

  // 3. Call the model again with the updated messages so it can answer using tool results
  const followUp = await openai.chat.completions.create({
    model: "gpt-4o-mini",
    messages,
    tools,
  });

  const finalMsg = followUp.choices[0].message;
  messages.push({
    role: "assistant",
    content: finalMsg.content ?? "",
  });

  return finalMsg.content ?? "";
}

// Example message history structure
const conversationHistory = [
  { role: "system", content: "You are a helpful assistant." },
  { role: "user", content: "What is the weather in Lahore?" },
  // After runToolTurn runs, `conversationHistory` will contain:
  // - assistant message with `tool_calls: [{ id: "call_abc123", type: "function", function: ... }]`
  // - tool message with `{ role: "tool", tool_call_id: "call_abc123", content: '{"tempC":26}' }`
  // - final assistant message with the natural language answer
];

Helpful Tips for Multi-Turn Apps

  • Validate before sending: Run a quick check in development that every tool message’s tool_call_id appears in an earlier assistant message’s tool_calls and has no duplicate or orphaned IDs.
  • Always pass string content: Tool message content should be a string (such as JSON.stringify(...)), even when returning structured data or error details.
  • Keep tool schemas consistent: Send the same tools definitions across turns in the conversation so the model can continue calling or referencing them reliably.