Tool Errors
Part of the Tools and Agents section of Coddy's AI Engineering journey. Lesson 8 of 22.
Tools fail: a product is unknown, a service is down, an argument is out of range. If the exception escapes, your program crashes and the conversation is lost. Catch it and send the failure back as a result instead, with "is_error": True:
try:
output = get_forecast(**block.input)
except ValueError as error:
return {"type": "tool_result", "tool_use_id": block.id, "content": str(error), "is_error": True}
return {"type": "tool_result", "tool_use_id": block.id, "content": output}The flag tells the model the call did not work, and the content tells it why. Write a message a person could act on, such as Unknown city: Atlantis, never Error 17. A real model reads it and may retry with a better input or explain the problem to the user. The stand-in reports it: its answer becomes Sorry, I could not finish: and your message. Without the flag, the model takes the message as a normal result and may present an error as an answer.
Challenge
MediumThe stock agent in the starter crashes when a product is unknown, because check_stock raises a ValueError. Change run_tool so it never crashes.
- Wrap the
check_stockcall intryand catchValueError. - On an error, print
Tool:, the name, a space, the input,-> error:and the error's message, then return atool_resultwhose content is the message and whoseis_errorisTrue. - When the call works, keep printing and returning the result as the starter does.
For example, for the input Check stock for the monitor stand and for the desk fan the program prints:
Tool: check_stock {'product': 'monitor stand'} -> monitor stand: 3 in stock
Tool: check_stock {'product': 'desk fan'} -> error: Unknown product: desk fan
Answer: Sorry, I could not finish: Unknown product: desk fanTry it yourself
import coddy_ai as anthropic # in production: import anthropic
client = anthropic.Anthropic()
STOCK = {"desk lamp": 12, "office chair": 0, "bookshelf": 5, "monitor stand": 3}
def check_stock(product):
if product not in STOCK:
raise ValueError(f"Unknown product: {product}")
return f"{product}: {STOCK[product]} in stock"
TOOLS = [
{
"name": "check_stock",
"description": "Check how many units of a product are in stock",
"input_schema": {
"type": "object",
"properties": {"product": {"type": "string", "description": "The product name"}},
"required": ["product"],
},
}
]
def run_tool(block):
# Catch the ValueError: print "-> error: <message>" and return an error result
output = check_stock(**block.input)
print(f"Tool: {block.name} {block.input} -> {output}")
return {"type": "tool_result", "tool_use_id": block.id, "content": output}
request = input()
messages = [{"role": "user", "content": request}]
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)
while response.stop_reason == "tool_use":
messages.append({"role": "assistant", "content": response.content})
results = [run_tool(block) for block in response.content if block.type == "tool_use"]
messages.append({"role": "user", "content": results})
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)
for block in response.content:
if block.type == "text":
print("Answer: " + block.text)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Tools and Agents
Practice on your own: Online Python compiler