How to handle tool errors in the Claude API with is_error

Day 5, 30 minutes · beginner

Goal of this lessonReturn failed tool calls to Claude with is_error, cap the retries, catch API errors and switch on strict tool use for your tools.

Why it matters

Tools fail. A customer asks for a plant Margriet does not sell, Claude sends an input your function does not expect, or the request you build has a mistake in it. Until now, any of those would crash your script. A helper that crashes on the first odd question is not one Margriet can use.

Today you learn the two kinds of error in tool use and what to do with each. A failed tool goes back to Claude as a result marked as an error, so Claude can try again or explain. A broken request comes back from the API as an error you catch in your code. At the end you have a script that survives a plant Margriet does not sell, and you have seen the most common tool use error on purpose.

Two kinds of error

A tool fails The request is wrong
Example unknown plant, wrong input, a lookup that times out a tool_result is missing or in the wrong place
Who notices your code, while running the tool the API, before Claude reads anything
What you get an exception in your own function an HTTP error such as 400
What you do send a tool_result with is_error set to true fix your code; catch the error so the script stops cleanly

When a tool fails: is_error

You do not hide a failed tool from Claude. You send its tool_result like any other, with the error message as content and "is_error": true:

{
  "type": "tool_result",
  "tool_use_id": "toolu_...",
  "content": "Error: Unknown plant 'bird of paradise'. Copperleaf sells: monstera, pothos, snake plant, peace lily.",
  "is_error": true
}

Claude reads that and can call the tool again with a better input, or tell the customer what happened. Three tips from the docs:

  • Write error messages that help. Not just "failed", but what went wrong and what to try instead. That is why Margriet's functions list the plants she does sell.
  • Limit the retries. Claude may call the tool again after an error, so put a maximum on the number of rounds.
  • An unknown tool name or a missing input gets the same treatment: an is_error result. The docs add that during development, a missing input usually means your description needs more detail.

Today make_tool_results does this for every tool call: it runs the tool, catches any exception and turns it into an error result. Your script keeps going and Claude gets to decide what to say.

When the request is wrong: API errors

These come back as an HTTP error, and the Python SDK raises an exception for them. The ones you will meet with tools:

  • 400 invalid_request_error, anthropic.BadRequestError in Python: something is wrong with your request. With tools, the most common message is that tool_use ids were found without tool_result blocks immediately after. Check that every tool_use has a tool_result and that the results come first in the next user message. Forcing a tool on a model that does not support it (lesson 4) is also a 400.
  • 401, 429, 500, 529: the same as in any request (wrong key, too many requests, a problem on Anthropic's side, overloaded). The beginners course covered those.

Every API error has a request ID. Print it: support needs it to look at a request.

Strict tool use: fewer bad inputs

Without help, Claude might send "2" where your code wants the number 2, or leave out a required field. The docs offer strict tool use: add "strict": true to a tool definition and the inputs are guaranteed to match your schema. It works on every model. Your schemas from lesson 2 already have "additionalProperties": false, as the docs' strict examples do, so you only need to add the switch.

Strict mode does not replace is_error. A plant name can be a perfectly valid string and still not be in Margriet's shop.

One warning: results are data, not orders

Tool results can carry text from places you do not control, such as web pages or emails. The docs warn that someone could hide instructions in that text. Keep outside content inside tool_result blocks, and put your own instructions in your messages or system prompt, never inside a tool result.

The steps

  1. Add make_tool_results to shop.py: it runs every tool call and turns any failure into an error result.
  2. Create handle_errors.py with a limit of three rounds, and ask for a plant Margriet does not sell.
  3. Cause a 400 error on purpose and read its status, message and request ID.
  4. Switch on strict tool use for all three tools and run the error script again.

Follow the steps below.

Today's actions

Ticks are not saved without an account

Do it in Claude API

Claude API

  1. Open a terminal in your copperleaf-tools folder and turn on the virtual environment as in lesson 2.
  2. Add this to the end of shop.py. It runs every tool call of a response. When a tool fails, it sends the error text back with is_error set to true instead of crashing.
    def make_tool_results(content):
        """Run every tool_use block of a response. Return one tool_result for each."""
        results = []
        for block in content:
            if block.type != "tool_use":
                continue
            result = {"type": "tool_result", "tool_use_id": block.id}
            try:
                result["content"] = run_tool(block.name, block.input)
            except Exception as exc:
                result["content"] = f"Error: {exc}"
                result["is_error"] = True
            print(f"  {block.name}({block.input}) -> {result['content']}")
            results.append(result)
        return results
  3. Create handle_errors.py with this code. It asks for a plant Margriet does not sell and allows at most three rounds.
    from dotenv import load_dotenv
    import anthropic
    from shop import make_tool_results
    from tools import TOOLS
    
    load_dotenv()
    client = anthropic.Anthropic()
    MODEL = "claude-opus-5-5"
    MAX_ROUNDS = 3
    
    question = "Do you have a bird of paradise in stock? And what does a monstera cost?"
    messages = [{"role": "user", "content": question}]
    
    for round_number in range(1, MAX_ROUNDS + 1):
        response = client.messages.create(
            model=MODEL, max_tokens=1024, tools=TOOLS, messages=messages
        )
        print(f"round {round_number}: stop_reason {response.stop_reason}")
        if response.stop_reason != "tool_use":
            break
        messages.append({"role": "assistant", "content": response.content})
        messages.append({"role": "user", "content": make_tool_results(response.content)})
    
    if response.stop_reason == "tool_use":
        print(f"Stopped after {MAX_ROUNDS} rounds: Claude still wanted a tool.")
    print("".join(b.text for b in response.content if b.type == "text"))
  4. Run python handle_errors.py. Look for the line with Error: Unknown plant. In the next round Claude uses that error: it tells the customer which plants Copperleaf does sell, or tries again.
  5. Create break_on_purpose.py with this code. It leaves out the tool_result on purpose, so the API refuses the second request.
    from dotenv import load_dotenv
    import anthropic
    from tools import TOOLS
    
    load_dotenv()
    client = anthropic.Anthropic()
    MODEL = "claude-opus-5-5"
    
    messages = [{"role": "user", "content": "Is the monstera in stock?"}]
    response = client.messages.create(model=MODEL, max_tokens=1024, tools=TOOLS, messages=messages)
    if response.stop_reason != "tool_use":
        raise SystemExit("Claude did not call a tool this time. Run the script again.")
    
    messages.append({"role": "assistant", "content": response.content})
    # Wrong on purpose: plain text instead of a tool_result block.
    messages.append({"role": "user", "content": "Never mind, just tell me."})
    
    try:
        client.messages.create(model=MODEL, max_tokens=1024, tools=TOOLS, messages=messages)
    except anthropic.BadRequestError as e:
        print("Status:", e.status_code)
        print("Message:", e)
        print("Request ID:", e.request_id)
  6. Run python break_on_purpose.py. You see status 400, a message that says tool_use ids were found without tool_result blocks immediately after, and a request ID. Write them down.
  7. Switch on strict tool use: add these lines to the end of tools.py. Then run python handle_errors.py again. The unknown plant still comes back as an error, because it is valid text that is not in the shop.
    # Strict tool use: the input Claude sends always matches the schema.
    for tool in TOOLS:
        tool["strict"] = True

Note: If the first request in break_on_purpose.py gets no tool call, the script says so: just run it again. The Python SDK raises anthropic.BadRequestError for a 400; catch anthropic.APIStatusError to handle every error status at once.

Paid planPay as you go: buy prepaid credits in the Claude Console (minimum 5 US dollars). There is no free tier. Max, Ultra and Team plans include monthly API credits.

Checked on 4 December 2026 · Source: Claude API docs: Handle tool calls (opens in a new tab)

Create a free account to save your progress. Sign in or sign up