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 precedingrole: "assistant"message that declared thattool_call_id. - Missing tool response for a tool call: An assistant message requested
tool_calls(especially multiple parallel tool calls), but one or moretool_call_idresponses 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_callsmessage while keeping thetoolresult (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
toolmessage (with an error payload) for thattool_call_idleaves the call unanswered.
How to Format Multi-Turn Tool History Cleanly
- Keep the exact sequence: Append the user message -> assistant message (containing
tool_calls) -> onerole: "tool"message pertool_call_id-> next assistant/user messages. - Match every
tool_call.id: Everyidinassistant.tool_callsmust have a correspondingtoolmessage withtool_call_id: call.idand stringifiedcontent. - Trim in complete tool groups: When pruning old history, remove whole turn/tool exchanges together rather than splitting an assistant
tool_callsmessage from itstoolreplies. - Always return a tool response: Even if a tool fails or times out, return a JSON string error message with the matching
tool_call_idso 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
toolmessage’stool_call_idappears in an earlierassistantmessage’stool_callsand has no duplicate or orphaned IDs. - Always pass string
content: Tool messagecontentshould be a string (such asJSON.stringify(...)), even when returning structured data or error details. - Keep tool schemas consistent: Send the same
toolsdefinitions across turns in the conversation so the model can continue calling or referencing them reliably.
You must log in or register to comment.
