6.4Tool use, function calling & agents
How a text predictor books meetings and queries databases. Tool schemas, the agent loop, planning, memory, multi-agent setups, and when not to build an agent at all.
From talking to doing
A language model, on its own, can only produce text. It can’t check today’s weather, look up an order, run a SQL query or send an email. Everything it “knows” was frozen at training time, and arithmetic on long numbers is not its strong suit either.
Tool useTool use / function callingA model emits a structured call (name + arguments) that software executes, then the result is fed back to the model., also called function calling, bridges that gap with a simple contract. You describe some functions to the model. When the model decides one would help, it outputs a request in a precise format, like get_weather({"city": "Paris"}), and stops. Your code sees the request, runs the real function, and appends the result to the conversation. The model reads the result and continues: answering, or asking for another tool.
The model never touches the network or the database. It only writes structured text. Everything with real-world effects happens in your code, which is also where you keep control. Modern chat models are trained during post-training to produce these calls reliably; earlier research such as Toolformer (2023) showed models could even teach themselves when an API call helps.
Picture a skilled chef who is not allowed to leave the kitchen. When she needs something, she fills in an order slip from a pad of pre-printed forms (“Market run: item ___, quantity ___”), hands it to a runner, and waits. The runner goes out, comes back with the goods and the receipt, and drops both on the counter. She looks, decides what’s next, and writes another slip or plates the dish.
The chef is the LLM. The pre-printed forms are the tool schemas, the filled-in slip is a tool call, and the runner is your application that executes it. The receipt on the counter is the tool result, and the growing pile of slips and receipts is the context window. The chef never touches money or the outside world, which is exactly why you can decide which forms she gets and which slips the runner refuses to carry.
How function calling works
1. Describe the tools. Each tool has a name, a natural-language description, and a JSON Schema for its parameters:
{
"name": "get_weather",
"description": "Current weather for a city. Returns temperature in Celsius, conditions and precipitation probability (0-1).",
"input_schema": {
"type": "object",
"properties": { "city": { "type": "string", "description": "City name, e.g. Paris" } },
"required": ["city"]
}
}
The description is not decoration: it is the only thing the model knows about the tool. Say what it does, what it returns, units, and when not to use it.
2. The model emits a call. Given the tools and the conversation, the model may answer directly or respond with one or more tool calls. The API marks this, for example with stop_reason: "tool_use", and provides the parsed name and arguments. Many APIs let you force behavior with a “tool choice” setting (any tool, a specific tool, or none), and some models emit several independent calls at once to be run in parallel.
3. Your app executes it. Validate the arguments, check permissions, call the real function with a timeout, and catch errors.
4. Send back the result. Append a tool-result message linked to the call’s id. Errors go back too, as readable messages, because the model can often fix its own mistake.
5. Repeat until the model answers without requesting a tool.
Your application (the "harness") prepares the context: a system prompt and JSON-schema definitions of the tools the model may use. The model cannot run anything itself; these are just descriptions.
Every model call re-sends the whole message list, so input tokens billed grow roughly quadratically with the number of steps. Token counts are rough (≈ 4 characters per token).
A scripted run, not a live model. The message format follows the Anthropic Messages API; other providers use the same idea with different field names.
Things to notice:
- The model’s turn ends at the tool call. It literally cannot continue until your app returns a result.
- Every model call re-reads everything. The “input tokens billed” counter grows faster than the context, because each call pays again for all earlier messages. (Providers’ prompt caching reduces this cost; see the KV cache.)
- Errors are information. In the error scenario, a schema-violating argument comes back as a clear error and the model corrects itself on the next call.
- The loop ends when the model stops asking.
end_turnwith no tool calls is the termination signal.
The agent loop
An agentAgentAn LLM running in a loop that plans, calls tools, observes the results and continues until a goal is reached. is just this loop given a goal and some freedom: the model decides which tools to call, in what order, and when it’s done. The influential ReActReActReason + Act: an agent pattern where the model alternates between writing a thought, taking an action such as a tool call, and reading the observation that comes back. paper (Yao et al., 2022) framed it as interleaving reasoning traces with actions: Thought → Action → Observation → Thought → … The reasoning helps the model plan and interpret results; the actions ground it in real information instead of guesses.
Three ingredients separate a toy loop from a useful agent:
- Planning. For multi-step tasks, agents do better when they first sketch a plan (or a to-do list) and revise it as observations come in. Reasoning models do much of this internally and can think between tool calls.
- Memory. Short-term memory is the context window, and it fills up: tool outputs like web pages or logs are long. Long-running agents need context management: summarizing or “compacting” old turns, trimming bulky tool results, and writing notes to files they can re-read later. Long-term memory across sessions is usually an external store the agent reads and writes with tools, often via retrieval.
- Stopping and budgets. Cap the number of steps, tokens and dollars. Agents can loop on a failing approach far longer than a human would.
Multi-agent setups
A single agent’s context gets cluttered on big tasks. A common remedy is an orchestrator agent that splits the task and hands pieces to sub-agents, each with a fresh, focused context, then combines their reports. This parallelizes well for breadth-first work such as research. Anthropic reported that its multi-agent research system outperformed a single agent on its internal research evaluation, while using about 15 times more tokens than a chat interaction. Multi-agent designs pay off when the task is valuable and parallelizable, and are wasteful otherwise.
Workflows vs agents: start simple
Anthropic’s guide “Building effective agents” (December 2024) draws a useful line:
- Workflows are systems where LLMs and tools are orchestrated through predefined code paths. Your code decides the steps.
- Agents are systems where the LLM dynamically directs its own process and tool use.
The guide’s main advice is to find the simplest solution that works and add complexity only when needed. Often a single LLM call with retrieval and good examples is enough. When it isn’t, reach for workflow patterns before full autonomy:
- Prompt chaining: a fixed sequence of calls, each processing the previous output (outline → draft → polish), with checks in between.
- Routing: classify the input, then send it to a specialized prompt or model.
- Parallelization: run independent subtasks at once (sectioning) or the same task several times and vote.
- Orchestrator-workers: one LLM breaks down a task dynamically and delegates the pieces.
- Evaluator-optimizer: one call generates, another critiques, repeat.
Use an agent when the number and order of steps can’t be predicted in advance (open-ended coding, research, multi-system troubleshooting) and when you can afford the extra latency and cost and can tolerate, or catch, its mistakes.
The guide also stresses designing the agent-computer interface as carefully as a human interface: clear tool documentation with examples and edge cases, testing how the model actually uses each tool, and making mistakes hard to commit, for example by requiring absolute file paths rather than relative ones.
Guardrails
An agent is a program whose control flow is decided by a model that can be wrong or manipulated. Treat it accordingly:
- Least privilege. Give it only the tools and permissions the task needs: read-only database access if reading is all it does.
- Human in the loop for irreversible or costly actions: sending emails, payments, deleting data, deploying.
- Validate everything. Check arguments against schemas and business rules; never
evalmodel output. - Sandbox code execution and file access.
- Treat tool results as untrusted. A web page or email the agent reads can contain instructions aimed at it. This prompt injection risk grows with every tool that reads outside content and every tool that can send data out.
- Log and trace every step, so you can debug failures and audit behavior.
MATH CORNER · optionalWhy long agent runs get expensive and fragile
Cost grows quadratically. Suppose the base context (system prompt, tools, task) is tokens and every step adds tokens (a tool call plus its result). Call (counting from 0) sends input tokens, so calls send
With and : 3 calls cost input tokens, but 10 calls cost , and 30 calls cost . Ten times the steps, about forty times the tokens. Prompt caching and context compaction exist largely because of this term.
Reliability compounds. If each step independently succeeds with probability , a task needing correct steps succeeds with probability :
| per-step success | 5 steps | 10 steps | 30 steps |
|---|---|---|---|
| 0.90 | 0.590 | 0.349 | 0.042 |
| 0.95 | 0.774 | 0.599 | 0.215 |
| 0.99 | 0.951 | 0.904 | 0.740 |
Real agents beat this pessimistic model because they can notice errors and retry (as in the demo’s error scenario), which is exactly why clear error messages and verification steps matter so much. But the table explains why a small gain in per-step reliability makes a large difference to long tasks.
In code
The whole agent loop fits in a dozen lines. This sketch uses the Anthropic Python SDK; other SDKs differ mostly in field names.
import anthropic
client = anthropic.Anthropic()
TOOLS = [get_weather_schema, convert_units_schema] # JSON-schema dicts
IMPL = {"get_weather": get_weather, "convert_units": convert_units}
messages = [{"role": "user", "content": "Weather in Paris in °F? Umbrella?"}]
for step in range(10): # hard step budget
resp = client.messages.create(model=MODEL, max_tokens=1024, tools=TOOLS, messages=messages)
messages.append({"role": "assistant", "content": resp.content})
if resp.stop_reason != "tool_use":
break # final answer
results = []
for block in resp.content:
if block.type == "tool_use":
try:
out, err = IMPL[block.name](**block.input), False
except Exception as e: # errors go back to the model
out, err = f"Error: {e}", True
results.append({"type": "tool_result", "tool_use_id": block.id,
"content": str(out), "is_error": err})
messages.append({"role": "user", "content": results})
print(resp.content[-1].text)
- “With function calling, the model runs my functions.” The model only writes a request. Your code decides whether and how to execute it, which is your main point of control and safety.
- “Agents are always better than workflows.” Agents trade latency, cost and predictability for flexibility. For tasks with known steps, a workflow is cheaper, faster and easier to test.
- “More tools make an agent more capable.” Many overlapping tools confuse tool selection and bloat the context. A few well-described, distinct tools usually work better.
- “The context window is the agent’s memory, so a bigger window solves memory.” Long contexts are expensive on every call, and models use crowded contexts less reliably. Agents need deliberate summarization, note-taking and retrieval.
- “Tool outputs are trustworthy data.” Anything read from the web, email or files can carry injected instructions. Treat tool results as untrusted input.
Check your understanding
Q1.During function calling, who actually executes
get_weather?Q2.A tool call fails because the model passed an invalid unit. What's the best response from your app?
Q3.Each agent step adds about 300 tokens to the context. Why does going from 10 to 30 steps multiply input-token cost by far more than 3×?
Q4.You must turn support emails into tickets: classify, extract fields, then file via one API. Following 'Building effective agents', what should you build first?
Further reading
- blogBuilding effective agents — Anthropic (Dec 2024): workflows vs agents, the five workflow patterns, and tool-design advice.
- paperReAct: Synergizing Reasoning and Acting in Language Models — Yao et al.: the Thought / Action / Observation loop.
- paperToolformer: Language Models Can Teach Themselves to Use Tools — Schick et al.: self-supervised learning of when to call APIs.
- blogHow we built our multi-agent research system — Orchestrator and sub-agents in production, including the token costs.
- docsTool use with Claude (docs) — Reference for tool schemas, tool_use / tool_result blocks and tool choice.