Missing Tool Result Block After Tool Use This error suggests that after a tool use block in the conversation, you did not include the corresponding tool result block, which is required by the API. To resolve this: 1. Ensure that any `tool_use` block is i

Resolved 💬 60 comments Opened Mar 13, 2025 by Belkins Closed Aug 22, 2025
💡 Likely answer: A maintainer (igorkofman, collaborator) responded on this thread — see the highlighted reply below.

Bug Description
stuck on Error: API Error: 400 {"type":"error","error":{"type":"invalid_request_error","message":"messages.156: Did not find 1 tool_result block(s) at the beginning of this message. Messages following tool_use blocks must begin with a matching number of
tool_result blocks."}}

Environment Info

  • Platform: macos
  • Terminal: Apple_Terminal
  • Version: 0.2.14
  • Feedback ID: 4441d4b9-707d-4983-b467-74dd96d8ddc5

View original on GitHub ↗

60 Comments

myzie · 1 year ago

I ran across this error when using the Anthropic API (not Claude Code) and I assumed it was my fault initially. However I've looked more into it and I'm seeing something that looks like it could be a mistake on Anthropic's side. And I'm wondering if Claude Code may be subject to the same situation occasionally.

The key message sequence seems to be:

  • An assistant message with two content blocks in an atypical order (tool_use first, text second)
  • Then a user message with the corresponding tool_result

Note the assistant's own text content is BETWEEN the "tool_use" and the "tool_result" in the overall sequence. This seems to be the atypical order, as Claude most often will respond with (text first, tool_use second).

Here's an excerpt from the messages that cause the problem for me:

[
    ... truncated ...
  {
    "role": "user",
    "content": [
      {
        "type": "tool_result",
        "tool_use_id": "toolu_01Ya9WAYPEZjkyjxcw8J2SxB",
        "content": "Error: Failed to read directory /home. open /home: operation not permitted"
      }
    ]
  },
  {
    "role": "assistant",
    "content": [
      {
        "id": "toolu_01FGfUwSu2N7d8f1tAFh4snU",
        "type": "tool_use",
        "name": "ListDirectory",
        "input": {
          "path": "."
        }
      },
      {
        "type": "text",
        "text": "I apologize for the confusion. It seems we don't have permission to access the /home directory directly. Let's try listing the current directory instead:"
      }
    ]
  },
  {
    "role": "user",
    "content": [
      {
        "type": "tool_result",
        "tool_use_id": "toolu_01FGfUwSu2N7d8f1tAFh4snU",
        "content": "Directory listing for ..."
      }
    ]
  }
]

The error I get is this:

`tool_use` ids were found without `tool_result` blocks immediately after: toolu_01FGfUwSu2N7d8f1tAFh4snU.
Each `tool_use` block must have a corresponding `tool_result` block in the next message.

Note that the tool_result toolu_01FGfUwSu2N7d8f1tAFh4snU IS directly after the assistant message.

Curious if this resonates with anyone else that stumbles across this!

johnewart · 1 year ago

Actually, I ran into this just this evening as well - my solution was to order content blocks in messages like this:

  1. Tool Result Block
  2. Text Block
  3. Tool Request Block

This makes the API happy and guarantees responses are always right after requests, if you take all the blocks out and process them in literal order.

I think this is a bug in the Anthropic API - it used to work fine with the blocks out of order until just recently.

@myzie

myzie · 1 year ago

Thanks @johnewart for chiming in!

sharyar · 1 year ago

Running into the same issue as well.
This becomes pretty complicated when it comes to building agents where you may not necessarily have a lot of control with the ordering of messages.

Kitenite · 1 year ago

I thought i was going crazy but seems like the Anthropic API calls occasionally will return the messages out of order with tool use and result

TweedBeetle · 1 year ago

Happening to me right now out of nowhere also

notabene01 · 1 year ago

@TweedBeetle same here, right now
version 0.2.100

IlyaMaksheev · 1 year ago

Hello. Same for me.

ravishrawal · 1 year ago

hi same for me

henricook · 1 year ago

From an affected user in Claude Code CLI: Is there a way I can recover my conversation when this happens? There's a lot of context I don't want to lose!

Edit: it's extremely hairy but I managed to rescue this session by finding the session JSON under ~/.claude/projects/_path_to_my_project/[LATEST-SESSION-STORE-HERE].json and editing out messages that caused the error (in my case the last 6 or so lines) before continuing the session with claude -c

kashramli · 1 year ago

Happening to me now as well in Claude Code. Anyone have a solution? Im stuck.

Erik-2040 · 1 year ago

I am experiencing this the past 2 weeks trying to use Neovim Avante plugin with Anthropic API:

Error: {
message = "messages.10: tool_use ids were found without tool_result blocks immediately after: toolu_019dFspJ71N2tnHV31Bwkgq5. Each tool_use block must have a corresponding tool_result block in the next message.",
type = "invalid_request_error"
}

Claude claims this is due to Avante. But looking at the discussions here, the problem seems to be related to Anthropic. I would appreciate any help.

cohml · 1 year ago

I'll chime in that I too have just experienced this error in Neovim's avante plugin (claude-3-7-sonnet-latest), basically the same as @Erik-2040:

Error: {
  message = "messages.1: `tool_use` ids were found without `tool_result` blocks immediately after: toolu_0166ConBrjB26ouQs8PfFyRv. Each `tool_use` block must have a corresponding `tool_result` block in the next message.",
  type = "invalid_request_error"
}

This issue was opened over two months ago with many reported sufferers and 👍 s. Anthropic, can we at least hear from you?

Erik-2040 · 1 year ago
I'll chime in that I too have just experienced this error in Neovim's avante plugin (claude-3-7-sonnet-latest), basically the same as @Erik-2040: `` Error: { message = "messages.1: tool_use ids were found without tool_result blocks immediately after: toolu_0166ConBrjB26ouQs8PfFyRv. Each tool_use block must have a corresponding tool_result block in the next message.", type = "invalid_request_error" } `` This issue was opened over two months ago with many reported sufferers and 👍 s. Anthropic, can we at least hear from you?

Here is how I solved the problem. In avante.lua, I added:

disable_tools = true

Like this:
6 provider = 'claude',
7 claude = {
8 endpoint = 'https://api.anthropic.com',
9 model = 'claude-3-7-sonnet-20250219',
10 timeout = 30000,
11 temperature = 0,
12 --max_tokens = 20480,
13 max_tokens = 4096,
14 disable_tools = true,
15 -- REMOVED: strip_whitespace = true,
16 },

cohml · 1 year ago

@Erik-2040 disable_tools = true kind of throws the baby out with the bathwater though, doesn't it? Sure you no longer get the error, but you also don't get tool calls, significantly limiting Claude's agentic intelligence. No?

Erik-2040 · 1 year ago
@Erik-2040 disable_tools = true kind of throws the baby out with the bathwater though, doesn't it? Sure you no longer get the error, but you also don't get tool calls, significantly limiting Claude's agentic intelligence. No?

You're right. Today, I dealt with the issue again and the following solved the issue: mode = 'agentic',

...
opts = {
provider = 'claude',
claude = {
endpoint = 'https://api.anthropic.com',
model = 'claude-3-5-sonnet-20241022',
timeout = 30000,
temperature = 0,
max_tokens = 1024,
-- TRY THIS: More conservative tool handling
disable_tools = false,

)
},
-- IMPORTANT: Try 'agentic' mode - it handles tools better
mode = 'agentic', -- Better tool message handling than 'legacy'

...

awilcots · 1 year ago

I just ran into this error as well while using claude-3-7-sonnet-20250219. With help from this thread I was able to see where the error was in the logs. I ran into the error during an interactive claude session (installed via https://www.npmjs.com/package/@anthropic-ai/claude-code). It just kind of broke in the middle of processing a command. The output said "interrupted by user" and then I got the error on every following prompt.

I ended up fixing it, and keeping the context, by using the "undo" feature ( pressing escape twice ), and going to the command before the one that broke it. After that it worked just fine again. Feels like it broke during processing but moving back to before the problem made claude .. forget(?)? Whats strange is that I still see the affected blocks in the log.

I'm unsure if my situation is or will be similar to anyone else's, but that's what happened with me.

erg · 1 year ago

Ran into this on claude code 1.10, did a /bug. maybe it will help you debug

> http://localhost:5173/users the button is too dark to read
  ⎿ API Error: 400 {"type":"error","error":{"type":"invalid_request_error","message":"messages.23: `tool_use` ids were found without
    `tool_result` blocks immediately after: toolu_017HUZ46a25U7fc75Qt2JheW. Each `tool_use` block must have a corresponding `tool_result`
    block in the next message."}}

> http://localhost:5173/users the button is too dark to read
  ⎿ API Error: 400 {"type":"error","error":{"type":"invalid_request_error","message":"messages.23: `tool_use` ids were found without
    `tool_result` blocks immediately after: toolu_017HUZ46a25U7fc75Qt2JheW. Each `tool_use` block must have a corresponding `tool_result`
    block in the next message."}}

│ Submit Bug Report                                                                                                                              │
│                                                                                                                                                │
│ Thank you for your report!                                                                                                                     │
│ Feedback ID: e41c0453-fd44-423d-b702-c6c7f1b08bce                                                                                              │
│                                                                                                                                                │
│ Press Enter to also create a GitHub issue, or any other key to close.                                                                          │
│                                                                                                                                                │
jounih · 1 year ago

also getting this and no way to recover in the claude code session

API Error: 400 {"type":"error","error":{"type":"invalid_request_error","message":"messages.92: tool_use
ids were found without
tool_result blocks immediately after: toolu_01S1bUuuq1FAWEg8FEJsXFaG. Each
tool_use block must have a corresponding tool_result block in the next message."}}

jounih · 1 year ago
I ended up fixing it, and keeping the context, by using the "undo" feature ( pressing escape twice ), and going to the command before the one that broke it. After that it worked just fine again. Feels like it broke during processing but moving back

Thank you, this (double escape and choose an earlier history checkpoint) worked for me to recover

robsonfelix · 1 year ago

This happens to me all the time if I press [ESC] while it is trying to do something...

VPhung24 · 1 year ago

Also happened to me twice now (once was after pasting logs) and wasn't able to recover the session. Double ESC works -- thanks everyone!

dhirajsb · 1 year ago

Welp, I ran into this too, but I was able to recover the session with the following:

  1. Copy the tool call id it complains about, which doesn't have a return block
  2. First backup and then edit the session file ~/.claude/projects/<project-path-name>/<session-uuid>.jsonl
  3. Remove the entries from the problematic tool id in step 1 above
  4. Recover the session with the uuid from step 3 with claude --resume <session-uuid>

Again, remember to backup the session file first!

abhagsain · 1 year ago
Welp, I ran into this too, but I was able to recover the session with the following: 1. Copy the tool call id it complains about, which doesn't have a return block 2. First backup and then edit the session file ~/.claude/projects/<project-path-name>/<session-uuid>.jsonl 3. Remove the entries from the problematic tool id in step 1 above 4. Recover the session with the uuid from step 3 with claude --resume <session-uuid> Again, remember to backup the session file first!

@dhirajsb
how did you find the session id?

mkXultra · 1 year ago

@abhagsain

> Welp, I ran into this too, but I was able to recover the session with the following: > > 1. Copy the tool call id it complains about, which doesn't have a return block > 2. First backup and then edit the session file ~/.claude/projects/<project-path-name>/<session-uuid>.jsonl > 3. Remove the entries from the problematic tool id in step 1 above > 4. Recover the session with the uuid from step 3 with claude --resume <session-uuid> > > Again, remember to backup the session file first! @dhirajsb how did you find the session id?

use --output-format json option.
like claude -c -p --output-format json "hello"| jq

refs: https://docs.anthropic.com/en/docs/claude-code/sdk#json-output

abhagsain · 1 year ago
@abhagsain > > Welp, I ran into this too, but I was able to recover the session with the following: > > > > 1. Copy the tool call id it complains about, which doesn't have a return block > > 2. First backup and then edit the session file ~/.claude/projects/<project-path-name>/<session-uuid>.jsonl > > 3. Remove the entries from the problematic tool id in step 1 above > > 4. Recover the session with the uuid from step 3 with claude --resume <session-uuid> > > > > Again, remember to backup the session file first! > > > @dhirajsb how did you find the session id? use --output-format json option. like claude -c -p --output-format json "hello"| jq refs: https://docs.anthropic.com/en/docs/claude-code/sdk#json-output

I don't know what's wrong but whenever I try to resume my session the claude memory spikes up and after 1-2 minute the system restarts itself, so probably I lost the context? :(

!Image

!Image

abhagsain · 1 year ago
> @abhagsain > > > Welp, I ran into this too, but I was able to recover the session with the following: > > > > > > 1. Copy the tool call id it complains about, which doesn't have a return block > > > 2. First backup and then edit the session file ~/.claude/projects/<project-path-name>/<session-uuid>.jsonl > > > 3. Remove the entries from the problematic tool id in step 1 above > > > 4. Recover the session with the uuid from step 3 with claude --resume <session-uuid> > > > > > > Again, remember to backup the session file first! > > > > > > @dhirajsb how did you find the session id? > > > use --output-format json option. like claude -c -p --output-format json "hello"| jq > refs: https://docs.anthropic.com/en/docs/claude-code/sdk#json-output I don't know what's wrong but whenever I try to resume my session the claude memory spikes up and after 1-2 minute the system restarts itself, so probably I lost the context? :( !Image !Image

This tool issue is happening when Claude is doing something and you hit ESC. You'll see the message "Interrupted by the user" in the console. After that, you'll get the tool call issue.
My memory spike issue was happening because to edit this JSON lines file I was opening it in WindSurf because the content was not readable.
I set the language mode of the editor to JSON so I can read the content, and the editor formatted the file.
When you format the file to a JSON type, it will ad new lines, spacing etc, in the file

!Image

maze1377 · 1 year ago

I’m running into the same issue.

Environment details:

  • Running Claude Code inside Docker (custom image based on node:18-slim)
  • Installed @anthropic-ai/claude-code globally via npm
  • Using a non-root user for execution
  • Entrypoint runs a shell script that calls:

``sh
claude --dangerously-skip-permissions --model opus -p "$(cat "$prompt_file")";
``

  • Project workspace is mounted to /workspace

and i got this:
API Error: 400 {"type":"error","error":{"type":"invalid_request_error","message":"messages.97: tool_use ids were found without tool_result blocks immediately after: toolu_018TaGiocJstYpjX5biVRdDu. Each tool_use block must have a corresponding tool_result block in the next message."}}

Let me know if any extra logs or configs would help—happy to provide more info.

dhirajsb · 1 year ago
> Welp, I ran into this too, but I was able to recover the session with the following: > > 1. Copy the tool call id it complains about, which doesn't have a return block > 2. First backup and then edit the session file ~/.claude/projects/<project-path-name>/<session-uuid>.jsonl > 3. Remove the entries from the problematic tool id in step 1 above > 4. Recover the session with the uuid from step 3 with claude --resume <session-uuid> > > Again, remember to backup the session file first! @dhirajsb how did you find the session id?

Luckily, I just had one session at the time, but if you do get an error with a tool call id, you can grep for it in your sessions and find the session id from the jsonl file name.

mrThomasTeller · 1 year ago
Welp, I ran into this too, but I was able to recover the session with the following: 1. Copy the tool call id it complains about, which doesn't have a return block 2. First backup and then edit the session file ~/.claude/projects/<project-path-name>/<session-uuid>.jsonl 3. Remove the entries from the problematic tool id in step 1 above 4. Recover the session with the uuid from step 3 with claude --resume <session-uuid> Again, remember to backup the session file first!

It works, thank you!

Zenetusken · 1 year ago
Welp, I ran into this too, but I was able to recover the session with the following: 1. Copy the tool call id it complains about, which doesn't have a return block 2. First backup and then edit the session file ~/.claude/projects/<project-path-name>/<session-uuid>.jsonl 3. Remove the entries from the problematic tool id in step 1 above 4. Recover the session with the uuid from step 3 with claude --resume <session-uuid> Again, remember to backup the session file first!

I tried this and no go. Solution = edit the request using a different AI altogether. Sorry but this is a workflow breaking critical issue that is still ongoing across various "API calls"

abhagsain · 1 year ago
> Welp, I ran into this too, but I was able to recover the session with the following: > `` > 1. Copy the tool call id it complains about, which doesn't have a return block > > 2. First backup and then edit the session file ~/.claude/projects/<project-path-name>/<session-uuid>.jsonl > > 3. Remove the entries from the problematic tool id in step 1 above > > 4. Recover the session with the uuid from step 3 with claude --resume <session-uuid> > `` > > > > > > > > > > > > Again, remember to backup the session file first! I tried this and no go. Solution = edit the request using a different AI altogether. Sorry but this is a workflow breaking critical issue that is still ongoing across various "API calls"

This is why, I always keep an editor open in the claude conversation history directory so whenever I face the issue, I can search the last message, remove the tool calls error and resume the session.

It's a hassle, but it works. I wish Anthropic solves this quickly and lately I'm getting these APi errors 🙄

!Image

jslitzkerttcu · 1 year ago

I just linked several duplicate issues for the same bug. It seems the latest release has been causing this to happen more frequently. In #1776 @illusivejosiah has an additional work around suggestion, stating:

_Note that if you fork the conversation (tap esc twice and select a previous message before the error, you can bypass it._
dhirajsb · 1 year ago

The double escape solution to fork the session might be the easiest workaround I've seen so far. That's assuming you didn't quit out of frustration like I had and had to resort to hand editing the session logs. :(

Mitch515 · 1 year ago

Fix for Claude Code CLI "tool_use without tool_result" Error

The Problem

If you're encountering this error with Claude Code CLI:

API Error: 400 {"type":"error","error":{"type":"invalid_request_error","message":"messages.X: `tool_use` ids were found without `tool_result` blocks immediately after: toolu_XXXXX. Each `tool_use` block must have a corresponding `tool_result` block in the next message."}}

This happens when Claude's session history contains tool_use messages that don't have corresponding tool_result messages immediately following them. This can occur due to interrupted sessions, network issues, or other edge cases.

The Solution

I've created a Python script that automatically fixes these corrupted session files by:

  1. Creating a backup of your original session
  2. Identifying unmatched tool_use entries
  3. Removing the problematic messages while preserving the rest of your conversation
  4. Cleaning up related API error messages

The Script

#!/usr/bin/env python3
"""
Fix Claude session file by removing messages that cause tool_use/tool_result errors
"""
import json
import sys
import os
from datetime import datetime

def fix_session_file(filename, backup=True):
    """Fix a session file by ensuring all tool_use have matching tool_result"""
    
    # Create backup if requested
    if backup:
        backup_file = f"{filename}.backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
        os.rename(filename, backup_file)
        print(f"Created backup: {backup_file}")
        
        # Read from backup
        with open(backup_file, 'r') as f:
            lines = f.readlines()
    else:
        with open(filename, 'r') as f:
            lines = f.readlines()
    
    # Parse all lines
    messages = []
    for i, line in enumerate(lines):
        try:
            data = json.loads(line.strip())
            messages.append((i, data, line))
        except:
            print(f"Warning: Could not parse line {i+1}")
    
    # Find problematic tool_use messages
    fixed_messages = []
    skip_next = False
    
    for i in range(len(messages)):
        if skip_next:
            skip_next = False
            continue
            
        line_num, data, raw_line = messages[i]
        
        # Check if this is an assistant message with tool_use
        if (data.get('type') == 'assistant' and 
            'message' in data and 
            'content' in data['message'] and
            isinstance(data['message']['content'], list)):
            
            has_tool_use = False
            for item in data['message']['content']:
                if isinstance(item, dict) and item.get('type') == 'tool_use':
                    has_tool_use = True
                    tool_id = item.get('id')
                    break
            
            if has_tool_use:
                # Check if next message has matching tool_result
                has_matching_result = False
                if i + 1 < len(messages):
                    next_data = messages[i + 1][1]
                    if (next_data.get('type') == 'user' and
                        'message' in next_data and
                        'content' in next_data['message'] and
                        isinstance(next_data['message']['content'], list)):
                        
                        for item in next_data['message']['content']:
                            if (isinstance(item, dict) and 
                                item.get('type') == 'tool_result' and
                                item.get('tool_use_id') == tool_id):
                                has_matching_result = True
                                break
                
                if not has_matching_result:
                    print(f"Removing unmatched tool_use at line {line_num + 1}, tool_id: {tool_id}")
                    # Skip this message and potentially the next one if it's an error
                    if (i + 1 < len(messages) and 
                        messages[i + 1][1].get('isApiErrorMessage')):
                        skip_next = True
                    continue
        
        # Check for API error messages about tool_use/tool_result
        if data.get('isApiErrorMessage'):
            content = str(data.get('message', {}).get('content', ''))
            if 'tool_use' in content and 'tool_result' in content:
                print(f"Removing API error message at line {line_num + 1}")
                continue
        
        fixed_messages.append(raw_line)
    
    # Write fixed file
    with open(filename, 'w') as f:
        f.writelines(fixed_messages)
    
    print(f"Fixed {filename} - removed {len(lines) - len(fixed_messages)} lines")
    print(f"Original lines: {len(lines)}, Fixed lines: {len(fixed_messages)}")

if __name__ == "__main__":
    if len(sys.argv) > 1:
        filename = sys.argv[1]
    else:
        # Default to a common location - adjust as needed
        print("Usage: python3 fix_claude_session.py <path_to_session_file>")
        sys.exit(1)
    
    fix_session_file(filename)

How to Use

  1. Find your problematic session file:

``bash
# Search for session files with the error
grep -l "tool_use.*ids were found without.*tool_result" ~/.claude/projects/*/*.jsonl
``

  1. Save the script:

``bash
# Save the script above to a file
nano ~/fix_claude_session.py
# Make it executable
chmod +x ~/fix_claude_session.py
``

  1. Run the fix:

``bash
python3 ~/fix_claude_session.py /path/to/your/problematic/session.jsonl
``

  1. Continue your conversation:

``bash
claude -c
``

Finding Session Files

You can use Claude Code to help identify recent conversations:

# List recent conversations
claude -r

Claude Code stores session files in:

  • ~/.claude/projects/[project-path]/[session-id].jsonl

The project path is your working directory with slashes replaced by dashes. For example:

  • Working in /home/user/my-project~/.claude/projects/-home-user-my-project/

What the Script Does

  1. Backs up your original file with a timestamp
  2. Parses each message in the session
  3. Identifies tool_use messages without matching tool_result
  4. Removes problematic entries while keeping valid conversation history
  5. Cleans up API error messages related to this issue

Example Output

Created backup: /home/user/.claude/projects/-my-project/session.jsonl.backup_20250608_230625
Removing unmatched tool_use at line 68, tool_id: toolu_01ArHiZgqv4zt35BMt95N5RD
Removing API error message at line 73
Fixed /home/user/.claude/projects/-my-project/session.jsonl - removed 2 lines
Original lines: 75, Fixed lines: 73

---

This solution was discovered and implemented using Claude Code itself! When I encountered this error, I asked Claude to help me understand the issue and create a fix. Claude analyzed the session file structure, identified the pattern causing the error, wrote this script to automatically repair corrupted sessions, AND even helped me write this GitHub comment explaining how to fix it. Talk about self-healing AI helping itself! 🤖

If this helps you, please give it a thumbs up. If you encounter any issues or have improvements, feel free to comment below.

RobertDudus · 1 year ago

This needs a solid fix. It destroys my sessions.

igorkofman collaborator · 1 year ago

We've resolve the root cause for this issue in 1.0.21 (claude update and claude --version).
To recover a stuck session hit "esc" twice and rewind back to before the error.

vedantrathore · 1 year ago

Still facing the issue after updating to 1.0.22, session becomes irrecoverable

superhappychris · 1 year ago

same here after updating to 1.0.22

persiyanov · 1 year ago

1.0.25 – still experiencing the issue. Rewinding ("esc" twice) doesn't help.

DubbaThony · 1 year ago

1.0.27 - was working for few days stable (I just got into claude code few days ago), and for past hour I started getting this error few times.

igorkofman collaborator · 1 year ago

One of the folks still hitting this issue, could you share more details on the session (screen shot or some sense of what was happening)? Ideally you'd load an affected session with claude --resume and then use /bug to share it with us for debugging. Would love to track any remaining issues here down.

eagle-25 · 1 year ago

1.0.29 - still experiencing.

Submitted the bug report as 9270c693-f07d-41e8-83be-1d8a101f2e32

dbtreasure · 1 year ago

1.0.34 and still experiencing

proBhavesh · 1 year ago

1.0.35 - still experiencing

glasser · 1 year ago

@igorkofman (hi! been a while!) — submitted a /bug for 81488219-6078-4013-883c-e8e1ffea57d3

I had been seeing this pretty frequently a few weeks ago but it had gone away until today.

praneybehl · 1 year ago

Same, seeing it frequently, It always triggers when asked to conduct web search. Web searches for me fail about ~60% of the time if not more.

AndrewAltimit · 1 year ago

v1.0.38 - still experiencing.

Perhaps Claude Code just doesn't exit gracefully when encountering an improper image (bad curl, different platforms modifying the image differently, etc). Another possibility is outages on the backend for image processing.

I often have to caution Claude to avoid image analysis otherwise the session gets locked up until I run /clear .

zazer0 · 1 year ago

I had the issue almost daily for a month - but as of v1.0.40, it's stopped occurring for me.

thomreck · 1 year ago

I haven't had the issue before, though after the release of v1.0.40 it's happened several times.

yokasaka · 1 year ago
% claude -v
1.0.43 (Claude Code)

I saw this issue today.

rhlarora84 · 1 year ago

I am using claude code with bedrock. Same issue.

bitflorist · 1 year ago

it happens irregularly no matter what version I have this since version 1.0.10

SolsticeSpectrum · 1 year ago

It happens on version 1.0.44 when I use claude --continue in one project, not even pressing esc twice helps, I can rollback as far as I can and it won't budge. I have submitted /bug with this ID 1421edcf-5be3-4dcc-8723-6259a5ab1e42

henricook · 1 year ago

Yep, the issue seems to be back with a vengeance today.

I've seen a few "Interrupted by user" when I didn't press anything - so I wonder if that's got anything to do with it?

rv64m · 12 months ago

Hey guys, I fix this bug with reorder messages, this is my idea:

    def _reorder_messages_for_claude(
        self, messages: List[BaseMessage]
    ) -> List[BaseMessage]:
        # Separate tool messages and other messages
        tool_messages_map: Dict[str, ToolMessage] = {}
        other_messages = []
        for m in messages:
            if isinstance(m, ToolMessage):
                tool_messages_map[m.tool_call_id] = m
            else:
                other_messages.append(m)

        # If there are no tool messages, no need to reorder
        if not tool_messages_map:
            return messages

        # Rebuild the list with tool messages placed correctly
        reordered_messages: List[BaseMessage] = []
        for m in other_messages:
            reordered_messages.append(m)
            if isinstance(m, AIMessage) and m.tool_calls:
                # Find all corresponding tool messages and add them immediately after
                for tc in m.tool_calls:
                    if tc["id"] in tool_messages_map:
                        reordered_messages.append(tool_messages_map[tc["id"]])
                        del tool_messages_map[tc["id"]]
                    else:
                        # HACK: Inject a synthetic error message if a tool result is missing
                        self.logger.warning(
                            f"Missing tool message for tool_call_id: {tc['id']}. "
                            f"Injecting a synthetic error message for Claude API compatibility."
                        )
                        reordered_messages.append(
                            ToolMessage(
                                tool_call_id=tc["id"],
                                content="The tool call result was not available.",
                            )
                        )

        return reordered_messages
AzyCrw4282 · 11 months ago
# Fix for Claude Code CLI "tool_use without tool_result" Error ## The Problem If you're encountering this error with Claude Code CLI: `` API Error: 400 {"type":"error","error":{"type":"invalid_request_error","message":"messages.X: tool_use ids were found without tool_result blocks immediately after: toolu_XXXXX. Each tool_use block must have a corresponding tool_result block in the next message."}} ` This happens when Claude's session history contains tool_use messages that don't have corresponding tool_result messages immediately following them. This can occur due to interrupted sessions, network issues, or other edge cases. ## The Solution I've created a Python script that automatically fixes these corrupted session files by: 1. Creating a backup of your original session 2. Identifying unmatched tool_use entries 3. Removing the problematic messages while preserving the rest of your conversation 4. Cleaning up related API error messages ## The Script #!/usr/bin/env python3 """ Fix Claude session file by removing messages that cause tool_use/tool_result errors """ import json import sys import os from datetime import datetime def fix_session_file(filename, backup=True): """Fix a session file by ensuring all tool_use have matching tool_result""" # Create backup if requested if backup: backup_file = f"{filename}.backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}" os.rename(filename, backup_file) print(f"Created backup: {backup_file}") # Read from backup with open(backup_file, 'r') as f: lines = f.readlines() else: with open(filename, 'r') as f: lines = f.readlines() # Parse all lines messages = [] for i, line in enumerate(lines): try: data = json.loads(line.strip()) messages.append((i, data, line)) except: print(f"Warning: Could not parse line {i+1}") # Find problematic tool_use messages fixed_messages = [] skip_next = False for i in range(len(messages)): if skip_next: skip_next = False continue line_num, data, raw_line = messages[i] # Check if this is an assistant message with tool_use if (data.get('type') == 'assistant' and 'message' in data and 'content' in data['message'] and isinstance(data['message']['content'], list)): has_tool_use = False for item in data['message']['content']: if isinstance(item, dict) and item.get('type') == 'tool_use': has_tool_use = True tool_id = item.get('id') break if has_tool_use: # Check if next message has matching tool_result has_matching_result = False if i + 1 < len(messages): next_data = messages[i + 1][1] if (next_data.get('type') == 'user' and 'message' in next_data and 'content' in next_data['message'] and isinstance(next_data['message']['content'], list)): for item in next_data['message']['content']: if (isinstance(item, dict) and item.get('type') == 'tool_result' and item.get('tool_use_id') == tool_id): has_matching_result = True break if not has_matching_result: print(f"Removing unmatched tool_use at line {line_num + 1}, tool_id: {tool_id}") # Skip this message and potentially the next one if it's an error if (i + 1 < len(messages) and messages[i + 1][1].get('isApiErrorMessage')): skip_next = True continue # Check for API error messages about tool_use/tool_result if data.get('isApiErrorMessage'): content = str(data.get('message', {}).get('content', '')) if 'tool_use' in content and 'tool_result' in content: print(f"Removing API error message at line {line_num + 1}") continue fixed_messages.append(raw_line) # Write fixed file with open(filename, 'w') as f: f.writelines(fixed_messages) print(f"Fixed {filename} - removed {len(lines) - len(fixed_messages)} lines") print(f"Original lines: {len(lines)}, Fixed lines: {len(fixed_messages)}") if __name__ == "__main__": if len(sys.argv) > 1: filename = sys.argv[1] else: # Default to a common location - adjust as needed print("Usage: python3 fix_claude_session.py <path_to_session_file>") sys.exit(1) fix_session_file(filename) ## How to Use 1. **Find your problematic session file**: # Search for session files with the error grep -l "tool_use.*ids were found without.*tool_result" ~/.claude/projects/*/*.jsonl 2. **Save the script**: # Save the script above to a file nano ~/fix_claude_session.py # Make it executable chmod +x ~/fix_claude_session.py 3. **Run the fix**: python3 ~/fix_claude_session.py /path/to/your/problematic/session.jsonl 4. **Continue your conversation**: claude -c ## Finding Session Files You can use Claude Code to help identify recent conversations: # List recent conversations claude -r Claude Code stores session files in: * ~/.claude/projects/[project-path]/[session-id].jsonl The project path is your working directory with slashes replaced by dashes. For example: * Working in /home/user/my-project~/.claude/projects/-home-user-my-project/ ## What the Script Does 1. **Backs up your original file** with a timestamp 2. **Parses each message** in the session 3. **Identifies tool_use messages** without matching tool_result 4. **Removes problematic entries** while keeping valid conversation history 5. **Cleans up API error messages** related to this issue ## Example Output ` Created backup: /home/user/.claude/projects/-my-project/session.jsonl.backup_20250608_230625 Removing unmatched tool_use at line 68, tool_id: toolu_01ArHiZgqv4zt35BMt95N5RD Removing API error message at line 73 Fixed /home/user/.claude/projects/-my-project/session.jsonl - removed 2 lines Original lines: 75, Fixed lines: 73 `` _This solution was discovered and implemented using Claude Code itself! When I encountered this error, I asked Claude to help me understand the issue and create a fix. Claude analyzed the session file structure, identified the pattern causing the error, wrote this script to automatically repair corrupted sessions, AND even helped me write this GitHub comment explaining how to fix it. Talk about self-healing AI helping itself! 🤖_ _If this helps you, please give it a thumbs up. If you encounter any issues or have improvements, feel free to comment below._

on step 4, if you run this, wont you be getting a new session? I checked with /status and i see a new session id altogether. i ran it with --resume it works but its constantly arising one after the other.

bcherny collaborator · 10 months ago

This should be fixed in the latest version. Make sure claude update, and let us know if you're still hitting this.

ohmantics · 10 months ago

Hitting this with 1.0.89 today. My session last night was stopped by Claude's own 5 hour cutoff.

This should be self-healing.

EDIT: although the script above makes changes and seems satisfied, I still get the error resuming that session. @bcherny

github-actions[bot] · 10 months ago

This issue has been automatically locked since it was closed and has not had any activity for 7 days. If you're experiencing a similar issue, please file a new issue and reference this one if it's relevant.