Tool Use (Function Calling) with the Claude API: A Complete Example
Tool use (also called function calling) lets a model request that your code run a function. The model never runs code itself; it returns a structured request and waits for your result.
1. Describe the tools
tools = [
{
"name": "search_products",
"description": "Search the product catalogue. Returns up to 5 matching products with price and stock.",
"input_schema": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search words, e.g. 'usb-c charger'"},
"max_price": {"type": "number", "description": "Optional price ceiling in INR"},
},
"required": ["query"],
},
},
]
2. Call the model and handle tool requests
import json
import anthropic
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Find me a USB-C charger under 1500 rupees"}]
while True:
response = client.messages.create(
model="claude-opus-5-5", max_tokens=16000, tools=tools, messages=messages
)
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
break
results = []
for block in response.content:
if block.type == "tool_use":
output = search_products(**block.input) # your real function
results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(output),
})
messages.append({"role": "user", "content": results})
print(next(b.text for b in response.content if b.type == "text"))
The message flow
- user: "Find me a USB-C charger under 1500 rupees"
- assistant:
tool_usesearch_products({"query": "usb-c charger", "max_price": 1500}) - user:
tool_result[{...product data...}] - assistant: "Here are two good options..."
Rules that prevent errors
- Append the assistant's full
content(not just its text) before sending tool results. - Every
tool_useblock needs a matchingtool_resultwith the sametool_use_id. - Return all tool results for one assistant turn in a single user message.
- On failure, return a result with
"is_error": Trueand a helpful message instead of crashing.
Getting guaranteed-valid arguments
Add "strict": True to a tool definition (with additionalProperties: false in the schema) and the arguments are guaranteed to match the schema exactly.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.