Anthropic Tool Use Intermediate

Anthropic's Claude models support tool use through a content-block-based API. Claude can request tool calls by including tool_use content blocks in its response, and you return results via tool_result content blocks.

Defining Tools

Python
import anthropic

client = anthropic.Anthropic()

tools = [
    {
        "name": "get_weather",
        "description": "Get current weather for a given location.",
        "input_schema": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "City name, e.g. 'San Francisco'"
                }
            },
            "required": ["location"]
        }
    }
]
Key Difference from OpenAI: Anthropic uses input_schema instead of parameters, and tools are defined at the top level (not nested under a function key).

Making a Tool Use Request

Python
response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    tools=tools,
    messages=[
        {"role": "user", "content": "What's the weather in San Francisco?"}
    ]
)

# Check stop reason
if response.stop_reason == "tool_use":
    # Find tool_use blocks in the response content
    for block in response.content:
        if block.type == "tool_use":
            print(f"Tool: {block.name}")
            print(f"Input: {block.input}")
            print(f"ID: {block.id}")

Returning Tool Results

Python
# Build the full conversation with tool results
messages = [
    {"role": "user", "content": "What's the weather in San Francisco?"},
    {"role": "assistant", "content": response.content},  # Includes tool_use block
    {
        "role": "user",
        "content": [
            {
                "type": "tool_result",
                "tool_use_id": tool_use_block.id,
                "content": '{"temp": "18C", "condition": "Foggy"}'
            }
        ]
    }
]

# Get the final response
final_response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    tools=tools,
    messages=messages
)
print(final_response.content[0].text)

Tool Choice Options

Value Behavior
{"type": "auto"} Claude decides whether to use tools (default)
{"type": "any"} Claude must use at least one tool
{"type": "tool", "name": "..."} Claude must use the specified tool

Multi-Step Tool Chains

Claude can request multiple tool calls in sequence. After receiving the result of one tool call, it may decide to call another tool before giving the final answer. Your execution loop should continue until stop_reason is "end_turn" rather than "tool_use".

Important: Tool results must be sent as user role messages with tool_result content blocks. The tool_use_id must match the ID from the corresponding tool_use block in the assistant's response.