Tool Use (Function Calling) with the Claude API: A Complete Example

A
Author
20 Sep, 2026 1 min read 422 views

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

  1. user: "Find me a USB-C charger under 1500 rupees"
  2. assistant: tool_use search_products({"query": "usb-c charger", "max_price": 1500})
  3. user: tool_result [{...product data...}]
  4. 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_use block needs a matching tool_result with the same tool_use_id.
  • Return all tool results for one assistant turn in a single user message.
  • On failure, return a result with "is_error": True and 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.

Leave a comment

Comments are reviewed before they appear.