The Claude API error "tool_use ids were found without tool_result blocks immediately after" means the message after an assistant turn that called tools doesn't answer every call the way the API expects. The full 400 invalid_request_error looks like this, as quoted in a GitLab issue: "messages.22: tool_use ids were found without tool_result blocks immediately after: toolu_01LH6hajbBykU3ZrpSZWrweq. Each tool_use block must have a corresponding tool_result block in the next message." Anthropic's troubleshooting page gives two causes: a missing tool_result for some tool_use IDs, or a tool_result that is not the first content block in the user message. The fix is to send one tool_result for every tool_use block, all in the next user message, before any text.
This post lists the histories that produce the error, shows a checker that names the broken message before you send it, and covers the repairs for interrupted runs and trimmed histories. The code was run on Python 3.13 against plain message lists and a fake client, so it needs no API key.
The rules the API enforces
Anthropic's "Handle tool calls" page spells out the loop. When a response has stop_reason of tool_use, you run each tool, add the response's content unchanged as an assistant message, then add a user message with "one tool_result block for each tool_use block in that content, even if the tool failed." Each result carries the tool_use_id of the call it answers.
The same page lists the formatting requirements:
- Tool results must immediately follow their tool use blocks. "You cannot include any messages between the assistant's tool use message and the user's tool result message."
- In that user message,
tool_resultblocks come first. "Any text must come AFTER all tool results." - If the assistant turn also called a server tool that has no result block yet, the user message must contain only
tool_resultblocks.
The messages.N prefix in the error points at a position in the messages array you sent, and the toolu_ IDs after the colon are the calls with no answer. Search your history for those IDs to find the assistant turn that made them.
Six histories that cause the error
Each of these breaks one of the rules above. The first three come from the loop that builds the history, the last three from what happens to the history later.
- Only some calls answered. Claude can call several tools in one response, and parallel tool use is on by default. A loop that handles only the first
tool_useblock leaves the rest unanswered. - Results split across messages. The parallel tool use docs say to return every result "all together in the next user message." A separate user message per result leaves the next message missing IDs, and the docs add that this format "teaches" Claude to avoid parallel calls.
- Text before the results. A user message that starts with "Here are the results:" and then the
tool_resultblocks fails. The docs show this exact example as a 400. - A new user turn before the results. The run was interrupted after Claude called a tool, and the next request adds the user's new question instead of the results. This can happen in any app where a person can stop a run mid-turn.
- A tool call that never got a result. In a Strands Agents bug report, the model called a tool name that didn't exist, the framework recorded the
toolUseblock but never created a matching result, and the next request failed with this error. An exception in your own tool code that skips the append does the same. - History trimmed or reordered. Cutting old messages to fit the context window can drop a
tool_resultand keep itstool_use, or the reverse. The GitLab issue lists message trimming as a suspected cause. A related OpenAI Agents SDK bug report shows the mirror error: with extended thinking on and thinking blocks preserved, the SDK's message converter put a tool result before its call, and the API answered "unexpectedtool_use_idfound intool_resultblocks", adding that eachtool_result"must have a correspondingtool_useblock in the previous message."
Find the broken message before you send it
A local check can name every broken pairing before the request goes out, without spending an API call. This one works on plain dicts and on the SDK's content block objects:
"""Check and repair tool_use / tool_result pairing before calling the Claude API."""
def _get(block, key, default=None):
# Works for plain dicts and for SDK content block objects.
if isinstance(block, dict):
return block.get(key, default)
return getattr(block, key, default)
def _blocks(message):
content = _get(message, "content")
return [] if isinstance(content, str) else list(content or [])
def tool_use_ids(message) -> list[str]:
return [_get(b, "id") for b in _blocks(message) if _get(b, "type") == "tool_use"]
def pairing_problems(messages) -> list[str]:
"""Return the rule each assistant tool call breaks. Empty list means OK."""
problems = []
for i, msg in enumerate(messages):
if _get(msg, "role") != "assistant":
continue
ids = tool_use_ids(msg)
if not ids:
continue
if i + 1 == len(messages):
problems.append(f"messages.{i}: ends with tool_use {ids}, add the tool_result blocks")
continue
nxt = messages[i + 1]
blocks = _blocks(nxt)
if _get(nxt, "role") != "user":
problems.append(f"messages.{i + 1}: must be a user message with tool results")
continue
types = [_get(b, "type") for b in blocks]
n_results = types.count("tool_result")
if types[:n_results] != ["tool_result"] * n_results:
problems.append(f"messages.{i + 1}: put every tool_result before other content")
answered = {_get(b, "tool_use_id") for b in blocks if _get(b, "type") == "tool_result"}
missing = [x for x in ids if x not in answered]
if missing:
problems.append(f"messages.{i + 1}: no tool_result for {missing}")
return problems
We ran it on the first four histories plus an interrupted run and a correct one, each starting with a user question and an assistant turn that called toolu_1 and toolu_2:
only first result: ["messages.2: no tool_result for ['toolu_2']"]
split results: ["messages.2: no tool_result for ['toolu_2']"]
text first: ['messages.2: put every tool_result before other content']
new question first: ["messages.2: no tool_result for ['toolu_1', 'toolu_2']"]
interrupted: ["messages.1: ends with tool_use ['toolu_1', 'toolu_2'], add the tool_result blocks"]
correct: OK
The correct history answers both calls first and puts the new question after them, which the docs allow when the turn called only client tools: [tool_result toolu_1, tool_result toolu_2, text "Also Rome?"].
A loop that always answers every call
Cases 1, 3 and 5 come from the agent loop itself, so the fix belongs there: make the result step unable to skip a call. The docs' tutorial loop collects a result for every tool_use block into one list. The version below adds two things the docs recommend: is_error: true results for tools that fail, and a check for a tool call cut off by max_tokens.
import json
from tool_pairing import pairing_problems
TOOLS_BY_NAME = {} # name -> Python function
def run_one(block) -> dict:
"""Always return a tool_result, even for unknown tools and exceptions."""
fn = TOOLS_BY_NAME.get(block.name)
if fn is None:
return {"type": "tool_result", "tool_use_id": block.id, "is_error": True,
"content": f"Unknown tool {block.name!r}. Available: {sorted(TOOLS_BY_NAME)}"}
try:
output = fn(**block.input)
except Exception as exc:
return {"type": "tool_result", "tool_use_id": block.id, "is_error": True,
"content": f"{type(exc).__name__}: {exc}"}
return {"type": "tool_result", "tool_use_id": block.id, "content": json.dumps(output)}
def run_agent(client, messages, tools, model, max_steps=10):
for _ in range(max_steps):
problems = pairing_problems(messages)
if problems:
raise ValueError("Bad history, not sending: " + "; ".join(problems))
response = client.messages.create(model=model, max_tokens=4096,
tools=tools, messages=messages)
if response.stop_reason == "max_tokens" and response.content \
and response.content[-1].type == "tool_use":
raise RuntimeError("Tool call cut off by max_tokens: retry with a higher limit")
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
return response
results = [run_one(b) for b in response.content if b.type == "tool_use"]
messages.append({"role": "user", "content": results})
raise RuntimeError(f"No final answer after {max_steps} steps")
With a fake client whose first response called get_weather for Paris, get_weather for a city that raises, and a get_forecast tool that doesn't exist, every call got an answer in one message:
{'type': 'tool_result', 'tool_use_id': 'toolu_1', 'content': '{"city": "Paris", "temp_c": 15}'}
{'type': 'tool_result', 'tool_use_id': 'toolu_2', 'is_error': True, 'content': 'LookupError: no such city'}
{'type': 'tool_result', 'tool_use_id': 'toolu_3', 'is_error': True, 'content': "Unknown tool 'get_forecast'. Available: ['get_weather']"}
final: Paris is 15C. | problems: OK
Notes on the choices:
- Failures still get a result. The docs say to send
is_error: truewhen a tool fails or a call is invalid, and to write messages that say what went wrong. If you decide not to run a call, the parallel tool use page says to "still return atool_resultfor it withis_error: trueand a brief explanation." An unknown tool name is case 5 above, closed. For which errors to retry first, see agent tool retries, and if the model keeps naming tools that don't exist, see why your agent calls the wrong tool. - A truncated call is not appended. The stop reasons page says that when a response hits
max_tokensand contains an incomplete tool use block, you "retry the request with a higher max_tokens value to get the full tool use." - Thinking blocks go back unchanged. Appending
response.contentas is keeps them intact. The errors page says to pass back everythinkingandredacted_thinkingblock "exactly as received" when using tools, or the request can fail with a different 400. - Client tools only. If you use server tools such as web search, handle
pause_turnas the stop reasons page describes. The loop above returns on it instead.
If you don't need this much control, the Python SDK's tool runner, client.beta.messages.tool_runner() with @beta_tool functions, runs the tools and sends the results for you.
Repair an interrupted run
When a person stops a run after Claude called a tool, your stored history ends with an unanswered tool_use. Don't drop the assistant turn, which loses what Claude was doing. Answer each pending call with an error result that says what happened, then let the next user message follow:
def close_dangling_calls(messages, note="Not run: the previous turn was interrupted."):
"""Answer every unanswered tool_use with an is_error result. Returns a new list."""
fixed = []
for i, msg in enumerate(messages):
fixed.append(msg)
ids = tool_use_ids(msg) if _get(msg, "role") == "assistant" else []
if not ids:
continue
nxt = messages[i + 1] if i + 1 < len(messages) else None
if nxt is not None and _get(nxt, "role") == "user":
continue # the next user message is left to pairing_problems()
stubs = [{"type": "tool_result", "tool_use_id": x, "content": note, "is_error": True}
for x in ids]
fixed.append({"role": "user", "content": stubs})
return fixed
On the interrupted history, pairing_problems(close_dangling_calls(history)) returned an empty list. To add the user's new question in the same request, append it as a text block after the stub results, which keeps the results first. If the run was paused for a person to approve a risky call, as in human in the loop agents, the "denied" or "approved" outcome is the result to send.
Trim history on safe boundaries
Trimming by message count is the quiet way to break pairing, because it works until the cut lands between a call and its result. Start the kept slice at a user message that holds no tool_result blocks:
def trim_history(messages, keep_last: int):
"""Keep roughly the last keep_last messages without splitting a tool call from its result."""
start = max(0, len(messages) - keep_last)
while start < len(messages):
msg = messages[start]
has_result = any(_get(b, "type") == "tool_result" for b in _blocks(msg))
if _get(msg, "role") == "user" and not has_result:
return messages[start:]
start += 1
return []
On a seven-message history, keeping the last five by count started the list with a user message holding two orphaned tool_result blocks, answering calls that were no longer in the history. trim_history(history, keep_last=5) moved forward to the user's "And tomorrow?" message, kept three messages and passed the check. The same boundary rule applies when you summarize instead of cutting, as in budgeting the context window and AI agent memory.
Checklist
- Search your history for the
toolu_IDs named in the error. - Return one
tool_resultpertool_useblock, matched bytool_use_id. - Put all results for one assistant turn in the next user message, first, before any text.
- Send
is_error: trueresults for failed, skipped and unknown-tool calls. - Don't append a tool call cut off by
max_tokens. Retry with a higher limit. - Pass the assistant content back unchanged, thinking blocks included.
- Close dangling calls after an interrupt instead of adding a new user turn.
- Trim and summarize only at user messages without tool results.
- Run a pairing check before every request.
FAQ
What does "tool_use ids were found without tool_result blocks immediately after" mean?
An assistant message in your history called tools, and the message after it doesn't answer all of them with tool_result blocks at the start of its content. The IDs after the colon are the unanswered calls.
Can I send text with tool results?
Yes, after them. In the user message that answers tool calls, every tool_result block must come before any text. If the turn also called a server tool that is still waiting, send only the tool_result blocks.
Do I need a tool_result when my tool fails?
Yes. The docs say to add a result for each call "even if the tool failed." Set is_error: true and put a short, specific error message in content.
Why do I get "unexpected tool_use_id found in tool_result blocks"?
It is the reverse problem: a tool_result whose call is not in the previous assistant message. It can come from trimming that removed the call or from code that reordered messages.
How do I fix this error in Claude Code or another agent tool?
It means the conversation that tool sent to the API broke the pairing rule. Check that tool's issue tracker for the version you run. If you build the loop yourself, the checks above find and repair the history.
Sources
- Anthropic, Troubleshooting tool use (Claude API documentation)
- Anthropic, Handle tool calls (Claude API documentation)
- Anthropic, Parallel tool use (Claude API documentation)
- Anthropic, Handling stop reasons (Claude API documentation)
- Anthropic, Tutorial: Build a tool-using agent (Claude API documentation)
- Anthropic, Errors (Claude API documentation)
- Anthropic, Python SDK (tool runner)
- GitLab, Agentic Chat tool_use ids without tool_result, issue 556636 (full error text)
- Strands Agents, Invalid tool names result in dangling toolUse blocks, issue 1069
- OpenAI Agents SDK, tool_result blocks appear before corresponding tool_use blocks, issue 1797