~/academy $ claude learn tool-use-basics
Tool use: let Claude call your functions
How to define a tool with a JSON schema, run the Claude tool use loop in Python, return results and errors, and when to let the SDK tool runner do it. 9 min
Watch it done: let Claude call your own function
Step 1 of 5
Start from the same setup as your first API call: the SDK installed in a virtual environment and your own key in this variable.
- Start from the same setup as your first API call: the SDK installed in a virtual environment and your own key in this variable. Type: export ANTHROPIC_API_KEY="your-api-key-here".
- Create tools.py. The definition tells Claude what the tool does, when to use it and what it returns. The function is the code that really runs. Create tools.py containing: ORDERS = {"ORD-10442": {"status": "dispatched", "expected": "2026-11-20"}} tools = [{ "name": "get_order_status", "description": ( "Look up the delivery status of one customer order by its order number. " "Use it whenever a customer asks where an order is or when it will arrive. " "It returns the status and expected delivery date only, never prices or addresses." ), "input_schema": { "type": "object", "properties": { "order_number": {"type": "string", "description": "The order number, for example ORD-10442"} }, "required": ["order_number"], }, }] def get_order_status(order_number): return ORDERS[order_number] # raises KeyError for an unknown order
- Create ask.py. While stop_reason is tool_use, it runs each call, adds Claude's turn unchanged, then sends one tool_result per call in the next user message. Create ask.py containing: import json import sys import anthropic from tools import tools, get_order_status client = anthropic.Anthropic() messages = [{"role": "user", "content": sys.argv[1]}] for _ in range(5): # never loop forever response = client.messages.create( model="claude-opus-5-5", max_tokens=4096, tools=tools, messages=messages ) if response.stop_reason != "tool_use": break messages.append({"role": "assistant", "content": response.content}) results = [] for block in response.content: if block.type == "tool_use": try: output, failed = json.dumps(get_order_status(**block.input)), False except KeyError: output, failed = "No order with that number. Ask the customer to check it.", True results.append({"type": "tool_result", "tool_use_id": block.id, "content": output, "is_error": failed}) messages.append({"role": "user", "content": results}) print("".join(b.text for b in response.content if b.type == "text"))
- Ask about an order that exists. Claude decides to call the tool, and your loop does the rest. Type: python ask.py "Where is order ORD-10442?". Claude calls get_order_status with ORD-10442, gets the result back and replies that the order is dispatched and due on 20 November.
- Try an order that does not exist. A clear error with a next step lets Claude recover instead of guessing. Type: python ask.py "Where is order ORD-99999?". the lookup fails, so Claude receives a result marked is_error with your message, and tells the customer to check the number.
Code from the official Claude API tool use docs (overview, define tools and handle tool calls), checked 18 November 2026. The order data is made up. Lines marked Note describe what happens and are not real output.
$ Read
What a tool is
Tool use (also called function calling) lets Claude ask your code to do something it cannot do alone, such as look up an order. You describe each tool with a name, a plain-language description and an input_schema written in JSON Schema. Claude decides when to call it.
There are two kinds. Client tools run in your application: Claude replies with stop_reason: "tool_use" and a tool_use block, you run the function and send back a tool_result. Server tools, such as web search, run on Anthropic's side and need no handler code (lesson 12).
The description matters more than anything else. The docs recommend at least three or four sentences: what the tool does, when to use it and when not to, what each parameter means and what it does not return. Names must match ^[a-zA-Z0-9_-]{1,128}$.
tools = [{
"name": "get_order_status",
"description": (
"Look up the delivery status of one customer order by its order number. "
"Use it whenever a customer asks where an order is or when it will arrive. "
"It returns the status and expected delivery date only, never prices or addresses. "
"Do not guess an order number: ask the customer if they have not given one."
),
"input_schema": {
"type": "object",
"properties": {
"order_number": {"type": "string", "description": "The order number, for example ORD-10442"}
},
"required": ["order_number"],
},
}]Lesson notes: Tool use: let Claude call your functions
Everything in this lesson as text, for revision or to read without the interactive steps. By the end you will be able to: You give Claude a function from your own system and handle the full call, run, return loop correctly.
Step 1 of 6 · Read
What a tool is
Tool use (also called function calling) lets Claude ask your code to do something it cannot do alone, such as look up an order. You describe each tool with a
name, a plain-languagedescriptionand aninput_schemawritten in JSON Schema. Claude decides when to call it.There are two kinds. Client tools run in your application: Claude replies with
stop_reason: "tool_use"and atool_useblock, you run the function and send back atool_result. Server tools, such as web search, run on Anthropic's side and need no handler code (lesson 12).The description matters more than anything else. The docs recommend at least three or four sentences: what the tool does, when to use it and when not to, what each parameter means and what it does not return. Names must match
^[a-zA-Z0-9_-]{1,128}$.A tool definition tools = [{ "name": "get_order_status", "description": ( "Look up the delivery status of one customer order by its order number. " "Use it whenever a customer asks where an order is or when it will arrive. " "It returns the status and expected delivery date only, never prices or addresses. " "Do not guess an order number: ask the customer if they have not given one." ), "input_schema": { "type": "object", "properties": { "order_number": {"type": "string", "description": "The order number, for example ORD-10442"} }, "required": ["order_number"], }, }]Step 2 of 6 · Read
The tool use loop
Each
tool_useblock has anid, anameand aninputobject that follows your schema. Run the tool, then send a new request with the earlier messages, Claude's response added unchanged as anassistantmessage, and ausermessage holding onetool_resultpertool_use. Keep the sametools. Repeat whilestop_reasonistool_use.Put a cap on the loop. If a tool fails, still send a result with
is_errorset to true and a message that says what went wrong and what to try next: Claude can then retry or explain the problem to the user.Full loop in Python import json import anthropic client = anthropic.Anthropic() def get_order_status(order_number): # Replace with your real lookup return {"order_number": order_number, "status": "dispatched", "expected": "2026-11-20"} messages = [{"role": "user", "content": "Where is order ORD-10442?"}] for _ in range(10): # never loop forever response = client.messages.create( model="claude-opus-5-5", max_tokens=4096, tools=tools, messages=messages ) messages.append({"role": "assistant", "content": response.content}) if response.stop_reason == "tool_use": results = [] for block in response.content: if block.type == "tool_use": try: output = json.dumps(get_order_status(**block.input)) results.append({"type": "tool_result", "tool_use_id": block.id, "content": output}) except Exception as err: results.append({"type": "tool_result", "tool_use_id": block.id, "content": f"Lookup failed: {err}. Ask the customer to check the number.", "is_error": True}) messages.append({"role": "user", "content": results}) else: break print("".join(b.text for b in response.content if b.type == "text"))Step 3 of 6 · Read
Rules that trip people up
Order matters. Tool results must come in the message straight after the assistant's tool use, and the
tool_resultblocks must be first in that user message. Any extra text goes after them. Claude can call several tools in one turn: return every result together in that one message.No forced tool calls on the newest models.
tool_choiceofanyortoolreturns a 400 error on Claude Opus 5.5, Sonnet 5.5 and Fable 5.2 (checked 18 November 2026). Use the defaultauto, name the tool in your prompt, and addstrict: trueto the tool if its inputs must match the schema exactly.Tool results are untrusted. A web page or email returned by a tool can contain instructions aimed at Claude. Keep that content inside
tool_resultblocks, not your system prompt. Tools also cost tokens: their definitions count as input, plus a tool use system prompt of 286 tokens on Opus 5.5.Step 4 of 6 · Improve a prompt
Rewrite a weak tool description
Claude keeps calling this stock tool at the wrong times and guessing product codes. Rewrite the description so it knows when to call it and what it gets back.
Starting prompt:
Gets stock.
Hint: Cover what it does, when to use it and when not to, what the input means with an example, and what it does not return.
Show a strong version
Returns the number of units in stock for one product at our Leeds warehouse, using the product SKU. Use it when a customer or colleague asks whether an item is available or how many are left. The SKU is an 8-character code such as LB-20431 printed on the product page; if the user has not given one, ask for it rather than guessing. It returns only the current unit count and the time of the last stock check. It does not return prices, delivery dates or stock at other sites.
Step 5 of 6 · Quiz
Check your understanding
Claude calls two tools in one turn: `get_order_status` and `get_refund_policy`. How do you send the results back?
- Two separate user messages, one per result.
- One user message containing both `tool_result` blocks first, each with its matching `tool_use_id`.
- Only the first result, then ask Claude to call the second again.
- Put both results in the system prompt.
Show the answer
One user message containing both `tool_result` blocks first, each with its matching `tool_use_id`. Every tool_use needs a tool_result, all in the next user message, before any text.
Step 6 of 6 · Read
Or let the SDK run the loop
For most apps you do not need to write the loop by hand. The Python SDK's tool runner (a beta helper) builds the schema from a decorated function, calls your tools when Claude asks and sends the results back until Claude is done.
Write the manual loop when you need full control, for example an approval step before a tool that changes data. Either way, keep tools few and focused, and return only the fields Claude needs for its next step.
Tool runner import json from anthropic import Anthropic, beta_tool client = Anthropic() @beta_tool def get_order_status(order_number: str) -> str: """Look up the delivery status of one order. Args: order_number: The order number, for example ORD-10442 """ return json.dumps({"status": "dispatched", "expected": "2026-11-20"}) runner = client.beta.messages.tool_runner( model="claude-opus-5-5", max_tokens=4096, tools=[get_order_status], messages=[{"role": "user", "content": "Where is order ORD-10442?"}], ) for message in runner: print(message)