Topic 1 of 4 · 4 min read
Why code beats one call per turn
Goal: Identify a multi-step tool task where a code action cuts round trips and context size, and estimate the saving.
When a task needs many tool calls, let the agent write one script that makes them, instead of spending a model turn on each call. The script runs outside the model. Only what it prints comes back into the context.
Check yourself · 1 of 3
An agent must check 120 order IDs against a shipping API. Why is one script usually better than 120 separate tool-call turns?
Why it matters
In the classic tool loop, every call is a round trip: the model emits a call, your code runs it, the full result is appended to the conversation, and the model reads everything again before its next step. Three costs grow together. Latency grows with the number of turns. Cost grows because each turn re-reads the history. And context fills with raw data the model only needed for a moment, such as 500 rows it will reduce to a count.
Code removes all three for a certain shape of task. A loop is one action instead of fifty. A filter runs on the machine, not in the model's head. Results can be joined, sorted and totalled by code that is exact, where a model doing arithmetic over a long list is not.
How to spot a task that fits
Ask four questions:
- Is the number of calls large or unknown in advance (one per customer, per file, per page)?
- Is each call independent of the others, so a loop can run them?
- Is the raw output far bigger than the answer you need?
- Is the reduction mechanical: filter, group, count, compare?
Yes to most means a code action. If each step depends on reading and judging the previous result, such as debugging an unfamiliar error, separate turns are better, because the model's judgement is the point.
Before and after
Task: "Which of our 200 customers have an unpaid invoice older than 30 days?"
One call per turn: the model calls list_customers, then get_invoices for customer 1, then customer 2, and so on. That is 201 turns, with every invoice list pasted into context.
As one code action:
late = []
for c in list_customers():
for inv in get_invoices(c["id"]):
if inv["status"] == "unpaid" and inv["age_days"] > 30:
late.append((c["name"], inv["id"], inv["age_days"]))
print(len(late), late[:10])
One turn to write it, one to read a short printed result. The saving is roughly the number of calls you replaced, and the context holds ten lines instead of two hundred invoice lists. Estimate it before you build: calls avoided, and rows kept out of context.
What goes wrong
- Using code where judgement is needed. A script cannot decide that an error message looks suspicious.
- Printing too much. If the script prints the whole list, the context saving is gone.
- Hiding a failure. A loop that skips customers whose call failed returns a confident, wrong total.
Examples
Counting open issues across repositories
An agent must report how many issues labelled bug are older than 90 days across 40 repositories. With one call per turn it makes 40 list calls and keeps every issue title in context. As a script it loops over the repositories, counts matches and prints one line per repository. The model reads 40 short lines.
A task that should stay turn by turn
A build fails with an unfamiliar linker error. The next step depends on what the error says, then on what the file contains, then on what the fix changes. A script cannot plan that path ahead, so the agent works one action at a time and reads each result.
Key points
- Each tool call in the classic loop costs a model turn, and every turn re-reads the whole history.
- A code action runs loops, filters and totals outside the model, so only the printed result enters the context.
- Code fits tasks with many independent calls, bulky output and a mechanical reduction.
- Tasks where each step needs the model's judgement of the previous result still belong in separate turns.
- Estimate the saving before building: calls replaced and rows kept out of context.
Common mistakes
- Writing a script for a task with three calls, where the extra machinery saves nothing.
- Printing the full intermediate data, which puts the bulk back into the context.
- Assuming a loop is safe because it is short, without handling the calls that fail.
- Letting a script run the judgement steps, such as deciding what a vague error means.
Check yourself · 2 of 3
Which task is the weakest fit for a code action?
Check yourself · 3 of 3
A script fetches 400 rows and the agent wants only the count of rows over a limit. What should the script print?
Practice items, not counted towards your mastery.
Start here
- Executable Code Actions Elicit Better LLM Agents (CodeAct) (opens in a new tab)PaperFree
The research paper behind code as an agent's action, compared with JSON tool calls.
- Code execution with MCP (Anthropic) (opens in a new tab)ArticleFree
How code actions cut tool-definition and result tokens, and what sandboxing they need.
- Programmatic tool calling (Claude API docs) (opens in a new tab)DocsFree
How Claude calls your tools from code it writes, and what the host must provide.