What this is
How does a program talk to a language model?
A program talks to an AI language model by sending it the whole conversation so far, as a list of messages, and getting one message back. The language model keeps nothing between calls, so every request carries the full history. The reply is either an answer or a request to run one of the functions the program offered it, such as a weather lookup. That request is a tool call. The language model never runs anything itself: the program runs the function and sends the result back in its next request.
Why it matters: Every program built on a language model makes this exchange. You need tool calling the moment the language model has to look something up, run a query or change a record, and the tell is code that reads its prose to decide which function to call.
At a glance
Key takeaways
- A call to a language model sends the whole conversation as a list of messages and gets one message back. The model keeps nothing between calls.
- A tool call is a structured request (
tool_use). Your code validates it, runs it, and returns atool_resultwith the matching id. The model executes nothing. stop_reasontells you what to do next:tool_usemeans run tools and call again,end_turnmeans done.- Every call re-sends the whole history, so the input billed for a loop grows with the square of its number of steps.
How it works, from scratch
Think of the model as a consultant who works only by post and keeps no files. Each time you write, you send the whole correspondence so far, and you get one letter back. That letter is either an answer or a filled-in request form: "please look up the weather in Paris and send me the result." The consultant never makes the call. You decide whether to carry out the request, and if you do, you post the result back with the whole correspondence again.
In a program, each letter is a message: your code sends the list of messages so far and gets one back. The request form is a tool call, a request to run one of the functions, called tools, that your code offered the model. Two facts follow:
- The model executes nothing. A tool call is only a request, so your code is the only thing that acts, and the checks belong there.
- Every call resends everything. Each request carries the full history, so a long conversation costs more on every turn.
Chapter 1
One tool call, traced
Here is the first fact at work. A user asks "What's the weather in Paris?",
and the application offers the model one tool, get_weather. The answer
takes four messages and two calls to the model:
| # | Role | Content | Who produced it |
|---|---|---|---|
| 1 | user | "What's the weather in Paris?" | the user |
| 2 | assistant | tool_use id=toolu_1, name=get_weather, input={"city": "Paris"} |
the model (1st call) |
| 3 | user | tool_result for toolu_1: "18°C, sunny" |
your code, after running the tool |
| 4 | assistant | "It's 18°C and sunny in Paris." | the model (2nd call) |
Message 3 has the role user although no person typed it, because tool
results always go back in the user's turn. Its tool_use_id repeats the id
from message 2. When the model asks for several tools at once, those ids tell
it which result answers which request.
Figure 1 · Diagram
sequenceDiagram
participant U as User
participant A as Your code
participant M as Model
participant T as get_weather tool
U->>A: What's the weather in Paris?
A->>M: messages [1] + tool definitions
M-->>A: tool_use get_weather {city: Paris} (stop_reason: tool_use)
A->>A: validate the arguments, check permissions
A->>T: get_weather("Paris")
T-->>A: 18°C, sunny
A->>M: messages [1, 2, 3 = tool_result]
M-->>A: It's 18°C and sunny in Paris. (stop_reason: end_turn)
A-->>U: It's 18°C and sunny in Paris.
get_weather comes from your code, never
from the model, and the arrow that loops back on your code is where your
checks run. Compare the two arrows into the model: the second carries
messages 1 to 3, not only the new result, because the model kept nothing from
the first call.In code: trace_tool_call_round_trip() produces this transcript.
ToolCall holds the request in message 2, and tool_result_block builds the
reply in message 3. View source
Chapter 2
The message format
The trace began with your code offering get_weather. That offer is a tool
definition: a name, a description, and a JSON Schema listing the input's
fields and their types. The model picks a tool by reading the descriptions,
so writing them well is prompt engineering (see Tools).
The messages follow Anthropic's Messages API, so the same fields appear in production code. Here is a second exchange, a lookup in an HR knowledge base, in full:
{"role": "user", "content": "What's our PTO policy?"}
{"role": "assistant", "content": [
{"type": "text", "text": "Let me look that up."},
{"type": "tool_use", "id": "toolu_1", "name": "search_kb", "input": {"query": "PTO"}},
]}
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "toolu_1", "content": "hr-001: ..."},
]}
| Field | Meaning |
|---|---|
role |
user (the human, or your code returning tool results) or assistant (the model) |
content |
a plain string, or a list of content blocks |
text block |
ordinary words |
tool_use block |
the model asking for a tool: id, name, and input (a JSON object matching the tool's schema) |
tool_result block |
your answer to one tool_use, matched by tool_use_id; set is_error: true when the tool failed |
stop_reason |
why the reply ended: end_turn (finished), tool_use (wants a tool), max_tokens (ran out of room), refusal (declined) |
In code: LLMResponse holds one reply in this format, and
content_blocks, last_user_text, tool_results and tool_calls_so_far
read a conversation written in it. View source
Chapter 3
A scripted model for testing
Since the exchange is messages in and one message out, anything that takes the messages and returns a message can stand in for the model. Agent code can call one small interface, a single method that takes the system prompt, the messages and the tools, without knowing what answers it: a script, where a function you write decides each reply, or the real model.
The script is for tests. A test can make it loop, call the wrong tool or follow an instruction injected into a document, which a real model rarely does on cue, and then check that your code copes.
Figure 2 · Diagram
flowchart LR L["LLM interface<br/>complete(system, messages, tools)"] L --> S["ScriptedLLM<br/>a Python function decides the reply<br/>offline, instant, deterministic"] L --> C["ClaudeLLM<br/>the real model via the anthropic SDK<br/>needs an API key"] S --> D["demos and tests<br/>reproduce any failure on purpose"] C --> P["production<br/>same agent code, real behaviour"]
In code: the interface is LLM, with the one method
LLM.complete(system=..., messages=..., tools=...). ScriptedLLM and
ClaudeLLM implement it, and OllamaLLM is a third, text-only
implementation for a local open model. View source
Chapter 4
Cost: every call pays for the whole conversation
The second fact, that every call resends everything, has a price. Input tokens are billed on everything a call sends, so the history is billed again on every call. Take an agent loop, which calls the model, runs the tool it asks for and calls again until the task is done. If it makes calls, the first request holds tokens and each call adds about more, the total input billed is:
The formula and its symbols
Symbols
| Symbol | Meaning here | In the example |
|---|---|---|
| number of model calls in the loop | 10 | |
| tokens in the first request (system prompt, tools, question) | 2,000 | |
| tokens each step adds (the model's tool call plus the tool's result) | 500 | |
| which call we're on, 1 to | ||
| add up the cost of every call | ||
| 0 + 1 + … + (n − 1): how many "steps of history" pile up in total | 45 |
In words: "each call pays for the starting prompt plus everything added so far, so the history term grows with the square of the number of steps."
With the numbers: 10 × 2,000 + 500 × 45 = 20,000 + 22,500 = 42,500 input tokens for a task whose final conversation is only 7,000 tokens long: the tenth call re-sends 6,500 tokens, and its own 500-token step brings the history to 7,000.
In Python
n, h_0, t = 10, 2000, 500
# call i re-sends h_0 and i - 1 steps
calls = [h_0 + (i - 1) * t for i in range(1, n + 1)]
calls[0], calls[-1] # → (2000, 6500)
# Σ over every call
sum(calls) # → 42500
# the shortcut on the right agrees
n * h_0 + t * n * (n - 1) // 2 # → 42500
New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.
Figure 3 · Chart
Ten calls bill 42,500 input tokens in total, six times the 7,000-token conversation they end with, because every call re-sends the history
In code: loop_input_tokens lists the tokens billed on each call of
such a loop, and estimate_tokens is the rule of thumb of four characters
per token. View source
Test yourself
5 questions
Answer each one out loud or on paper before you open it.
Question 1What exactly happens when a model "uses a tool"?Think it through, then reveal
You send tool definitions (name, description, JSON Schema) with the
messages. The model replies with a tool_use block and stop_reason: tool_use. Your code validates the arguments, runs the function, and sends a
new request with the history plus a tool_result block carrying the same
id. The model then answers or asks for another tool.
Question 2Why is the model never a security boundary for tool use?Think it through, then reveal
It only produces requests. Everything that actually happens goes through your code, so validation, permissions, approvals and rate limits all belong there, and a manipulated model can only ever ask.
Question 3The model asks for three tools in one reply. How do you send the results?Think it through, then reveal
Run them (concurrently if independent) and return all three tool_result
blocks in a single user message, each with its own tool_use_id. For one
that failed, return a tool_result with is_error: true and an actionable
message rather than dropping it.
Question 4A 20-step agent loop costs far more than 20 times a single call. Why?Think it through, then reveal
Each call re-sends the full, growing history, so the input billed is a sum that grows with the square of the number of steps. Caching the stable prefix and trimming tool outputs attack exactly this.
Question 5Why test agents against a scripted model at all?Think it through, then reveal
Real models are non-deterministic and rarely misbehave on cue. A scripted model reproduces loops, bad arguments and injected instructions exactly, so the code that must handle them can be tested every time.
Primary sources
The papers behind this lesson
Showed a model can learn when to call external tools and how to use their results.
Read on rumblr →The paperThe pattern of interleaving reasoning with tool calls that modern agent loops descend from.
Read on rumblr →The paperResearcher's shelf
Further reading
- Tool use overview: https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview
- Implementing tool use: https://docs.claude.com/en/docs/agents-and-tools/tool-use/implement-tool-use
- Messages API reference: https://docs.claude.com/en/api/messages
- Python SDK: https://github.com/anthropics/anthropic-sdk-python
- Anthropic, Building effective agents: https://www.anthropic.com/engineering/building-effective-agents
About this lesson. This lesson is built from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it. Its hand-built interactive figures are still to come: the status page shows which lessons have them.