little cups of claude

tips and techniques for Claude and Claude Code

#29: Tool Use Basics πŸ”§

Today we'll begin looking at tool use in the Claude API, which lets Claude call functions that we define and run in our own code.

We describe a tool with a name, a description, and a JSON Schema for its input. When Claude decides it needs the tool, it stops and asks us to run it, and then uses our result to finish its answer. Let's get started.

Defining A Tool

Tools go in a tools array on the request. Here's one that reports on our ship's systems:

const tools: Anthropic.Tool[] = [
  {
    name: "get_ship_status",
    description: "Get the current status of one ship system, like life support or the pod bay doors.",
    input_schema: {
      type: "object",
      properties: {
        system: { type: "string", description: "Name of the ship system" },
      },
      required: ["system"],
    },
  },
];

The same definition in Python is a plain dictionary:

tools = [
    {
        "name": "get_ship_status",
        "description": "Get the current status of one ship system, like life support or the pod bay doors.",
        "input_schema": {
            "type": "object",
            "properties": {
                "system": {"type": "string", "description": "Name of the ship system"},
            },
            "required": ["system"],
        },
    }
]

The description does a lot of the work here. It's how Claude decides whether a question maps to this tool at all.

Claude Asks For A Call

We pass tools along with our messages. When Claude wants the tool, the response comes back with stop_reason: "tool_use" and a tool_use block:

{
  "stop_reason": "tool_use",
  "content": [
    { "type": "text", "text": "Let me check the doors." },
    {
      "type": "tool_use",
      "id": "toolu_01A09q90qw90lq917835lq9",
      "name": "get_ship_status",
      "input": { "system": "pod bay doors" }
    }
  ]
}

Claude hasn't run anything. It named the tool and filled in arguments that match our schema, and the actual work is up to us.

Sending The Result Back

We run our function, then make a new request with three changes: the assistant's content added unchanged, a user message with a tool_result block, and the same tools as before:

const toolUse = response.content.find((b) => b.type === "tool_use")!;
const status = await getShipStatus(toolUse.input);

messages.push(
  { role: "assistant", content: response.content },
  {
    role: "user",
    content: [{ type: "tool_result", tool_use_id: toolUse.id, content: status }],
  },
);

The tool_use_id ties our result to the exact call Claude made. With the result in hand, Claude answers the original question in plain text. Neat!

Making It A Loop

Claude often wants more than one call, and a single response can hold several tool_use blocks at once. So we keep going while the stop reason says so, and answer every block:

while response.stop_reason == "tool_use":
    results = [
        {
            "type": "tool_result",
            "tool_use_id": block.id,
            "content": run_tool(block.name, block.input),
        }
        for block in response.content
        if block.type == "tool_use"
    ]
    messages += [
        {"role": "assistant", "content": response.content},
        {"role": "user", "content": results},
    ]
    response = client.messages.create(
        model="claude-opus-5-5", max_tokens=1024, tools=tools, messages=messages
    )

The docs say every tool_use block gets its own tool_result, even when the tool failed.

When A Tool Fails

For failures, we still send a tool_result, with is_error set to true and a useful message:

{
  "type": "tool_result",
  "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
  "content": "Sensor array offline. Retry in 60 seconds.",
  "is_error": true
}

Claude can then try again or explain what happened. The docs recommend messages that say what went wrong and what to try next, rather than a bare "failed". Since Claude might retry, it's worth capping how many rounds our loop allows.

Watch Out

Ordering matters. The tool_result blocks have to come in the message right after the assistant's tool_use message, with nothing in between, and they have to come first in that message's content. Any text we want to add goes after them. Getting this wrong produces an error about tool_use ids found without tool_result blocks.

Once the manual loop makes sense, both SDKs also have a beta tool runner (client.beta.messages.toolRunner() in TypeScript, client.beta.messages.tool_runner() in Python) that runs our tools and sends the results back for us.

More info about tool use can be found at the Claude API docs.

Share

Share on Threads

Similar Cups