Skip to content
LearnAI

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.

⏱ 12 minIntermediate

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.

ANALOGY· A chef who can't leave the kitchen

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.

INTERACTIVEAgent loop step-through
Scenario
1/7 · system prompt + tool schemas
UserYour appLLMToolssystem prompt + tool schemas
What happens at this step

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.

model calls
0
context now
~202 tok
input tokens billed
~0

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).

Context window (message list)
tools (JSON schemas)~182 tok
get_weather(city), convert_units(value, from, to)
system~20 tok
You are a helpful assistant. Use tools when you need live data. Answer concisely.

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.

A scripted agent answers a weather question with two tools. Step through and watch who acts, the JSON that flows, and how the context grows. Then try the 'Tool error & recovery' scenario.

Things to notice:

  1. The model’s turn ends at the tool call. It literally cannot continue until your app returns a result.
  2. 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.)
  3. 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.
  4. The loop ends when the model stops asking. end_turn with 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 eval model 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 BB tokens and every step adds mm tokens (a tool call plus its result). Call ii (counting from 0) sends B+i mB + i\,m input tokens, so nn calls send

T(n)=∑i=0n−1(B+i m)=nB+m n(n−1)2.T(n) = \sum_{i=0}^{n-1} (B + i\,m) = nB + m\,\frac{n(n-1)}{2}.

With B=1,000B = 1{,}000 and m=300m = 300: 3 calls cost 3,000+300⋅3=3,9003{,}000 + 300\cdot3 = 3{,}900 input tokens, but 10 calls cost 10,000+300⋅45=23,50010{,}000 + 300\cdot45 = 23{,}500, and 30 calls cost 30,000+300⋅435=160,50030{,}000 + 300\cdot435 = 160{,}500. 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 pp, a task needing nn correct steps succeeds with probability pnp^n:

per-step success pp5 steps10 steps30 steps
0.900.5900.3490.042
0.950.7740.5990.215
0.990.9510.9040.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)
COMMON MISCONCEPTIONS
  • “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

0/4 answered
  1. Q1.During function calling, who actually executes get_weather?

  2. Q2.A tool call fails because the model passed an invalid unit. What's the best response from your app?

  3. 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×?

  4. 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

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.