Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← FoundationsAI guideIntermediate#foundations#tools#function-calling#agents
Frame · ai-engineering / foundations / 08-tool-and-function-calling.mdGuide 008 / 103

Tool and function calling

Tool calling is how a model stops being a text generator and starts doing things: looking up an order, querying a database, sending a message, running code. The key mental model is that the model never executes anything. It emits a structured request ("call get_order with {"id": "A123"}"), your code runs the function, and you send the result back. Every agent, from a simple support bot to a coding assistant, is built on this loop.

Why it matters

Tools fix the two biggest limits of a bare model: stale knowledge and no side effects. With a search tool the model can cite today's data; with a database tool it can answer questions about your users; with write tools it can take actions. They also give you a security boundary. Because your code executes the call, you decide what is allowed, what needs confirmation and what gets logged. Get the loop and the boundary right and you have the foundation for agents; get them wrong and you have an injection vector with API keys.

How it works

You describe each tool with a name, a natural language description and a JSON Schema for its inputs. The model reads these definitions as part of its context (they count toward input tokens on every call). When it decides a tool would help, it stops generating text and emits a tool call block with arguments. Your code executes the tool and appends a tool result message. The model then continues, possibly calling more tools, until it produces a final answer.

Rendering diagram…

Controlling tool use

Anthropic's tool_choice has four modes: auto (the default when tools are supplied, the model decides), any (must call some tool), tool (must call a named tool) and none. Forcing a tool prefills the assistant turn, so you will not get explanatory text before the call, and with extended thinking only auto and none are supported. OpenAI exposes a similar tool_choice, and both providers support strict: true on tool definitions so arguments conform to the schema (see structured outputs).

Models can also emit several tool calls in one turn (parallel tool use). Execute independent calls concurrently and return all results in the next message.

Server tools and MCP

Some tools run on the provider's side: OpenAI's Responses API has built-in web search and file search, and Anthropic offers server tools such as web search and code execution. For tools you own, the Model Context Protocol (MCP) has become the standard way to package them so any compatible client can use them. The current MCP spec version is dated 2026-07-28, a large revision that removed the protocol-level session and initialize handshake. MCP standardizes discovery and transport; the call-and-result loop underneath is the same.

Reference architecture

Rendering diagram…

Code

A complete manual tool loop with the Anthropic Python SDK. The SDKs also ship a tool runner helper that automates this, but writing the loop once shows you exactly what goes over the wire.

import json
import anthropic

client = anthropic.Anthropic()

TOOLS = [{
    "name": "get_order",
    "description": "Look up an order by id. Returns status, carrier and ETA. Use when the user asks about a specific order.",
    "input_schema": {
        "type": "object",
        "properties": {"order_id": {"type": "string", "description": "Order id such as A123"}},
        "required": ["order_id"],
    },
}]

def get_order(order_id: str) -> dict:
    fake_db = {"A123": {"status": "shipped", "carrier": "UPS", "eta": "2026-10-24"}}
    return fake_db.get(order_id, {"error": f"order {order_id} not found"})

messages = [{"role": "user", "content": "Where is my order A123?"}]

while True:
    response = client.messages.create(
        model="claude-sonnet-4-6", max_tokens=1024, 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 = get_order(**block.input)
            results.append({
                "type": "tool_result",
                "tool_use_id": block.id,
                "content": json.dumps(output),
                "is_error": "error" in output,
            })
    messages.append({"role": "user", "content": results})

print(response.content[-1].text)

Note that the whole assistant content, including the tool_use block, goes back into history, and each result references the tool_use_id it answers.

Trade-offs and pitfalls

  • Descriptions are prompts. The model chooses tools based on names and descriptions. Say when to use a tool and when not to, and describe what it returns.
  • Overlapping tools confuse models. Two tools that both "search" will be picked inconsistently. Merge or sharpen them.
  • Too many tools cost tokens and accuracy. Large catalogs inflate every request. Load tools dynamically or group them behind a search tool.
  • Return useful errors. A tool result like "order not found, ids look like A123" lets the model recover; a stack trace does not.
  • Confirm side effects. Anything that sends, pays, deletes or publishes should need user approval or a policy check, because tool arguments can be influenced by injected content in documents or web pages.
  • Loop limits. Cap iterations and total tokens per task so a confused model cannot spin forever.
  • Large results. Dumping a 50,000-token API response into context is expensive and hurts quality. Summarize, paginate or filter in the tool.

Checklist

  • Each tool has a clear name, a when-to-use description and a strict input schema.
  • Read-only and side-effecting tools are separated, and side effects require approval.
  • Tool errors are returned as informative results, not raised exceptions.
  • Parallel tool calls are executed concurrently when independent.
  • The loop has a maximum iteration and token budget.
  • Every tool call and result is logged with the request id.
  • Tool results are trimmed to what the model needs.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.