How to Write a Minimal Agent Loop With Tool Dispatch
How to write a small AI agent loop in code: call the model, dispatch each tool safely, feed results back and stop at a limit, explained for your AI interview.
In short
A minimal agent loop calls the model, runs the one tool it names through a lookup table, sends the result back, and stops at a step cap. Unknown or badly formed calls come back as error text, so the model can recover instead of your service crashing.
12 min readIntermediateCommon · estimateFacts checked 27 November 2026
Say it out loud
Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.
An agent loop is a short program that keeps the model working. The model asks for a tool by name, or several at once, and my code looks each name up in a table and runs it. Then the result goes back to the model. Anything not in the table is refused with an error text. A step cap ends runs that never settle, and the case goes to a person. I write the loop against a scripted model first, so I can check every path.
The model asks for a tool by name and gives the arguments. My code is the loop, and that code does the running. It sends the messages so far to the model, reads the reply, and if the reply asks for a tool, it runs that tool and adds the result to the history. Then it asks the model again. When the reply is a final answer, the loop ends.
The middle part is dispatch. I keep a table that maps each tool name to a function. A name in the table runs. A name that is not in the table is never guessed at. It comes back as an error text, and the model can choose another step. Bad arguments work the same way: the tool raises an error, and the loop sends that text back instead of crashing.
Then the limits. A step cap stops a loop that never settles, and the case goes to a person with the steps so far. Tool output is untrusted, because a web page or file can hide instructions that try to redirect the model. Anthropic's guide says agents are typically just LLMs using tools in a loop, and that stopping conditions such as a maximum number of iterations are common, to keep control.
I write the loop first against a scripted model, so every path is fixed and the output is the same on every run. Only then do I connect a real model, and I test it in a sandbox.
What is an agent loop, in plain words?
An AI model can't run anything itself. It can only ask for a tool by name and give the inputs. An agent loop is the code that does the rest: it runs the tool, sends back what came out, and asks the model again.
Dispatch is the middle step. It is a lookup table from tool names to functions. If the name is in the table, the function runs. If it isn't, the call is refused with an error text, and the loop carries on. That table is the only list of what the agent can do.
Picture a call-centre agent with a printed list of approved screens: balance, card block, fee lookup. The agent reads the caller's request, opens one screen, reads the answer, and decides the next step. If the request needs a screen that is not on the list, the agent passes it to a supervisor. A bank's support assistant works the same way, and the code is the printed list.
Key words
- Tool
- A function your code runs for the model, such as get_balance.
- Dispatch
- Looking up a tool name in a table and running the matching function.
- Step cap
- A maximum number of passes, so a loop can't run forever.
- Tool result
- The text a tool returns, or an error text, which goes back to the model.
How does one pass of the loop run?
Each pass repeats the same four steps. Anthropic's tool-use docs describe the same shape: the loop repeats while the model's reply asks for a tool, and it ends on any other stop reason, such as end_turn.
- 1
Ask the model
Send the messages so far, plus the list of tools, to the model.
- 2
Look up the name
Read the reply. If it asks for a tool, find that name in your table. Not there? Make an error text.
- 3
Run it and catch errors
Call the function with the arguments. If it raises an error, turn that error into text.
- 4
Add the result and repeat
Add the result to the history and go back to the first step, until the reply is a final answer or the step cap is hit.
One pass of the agent loop
Model
asks for one or more calls
Your code
Name on our list?
only registered tools can run
Run the tool
errors are caught, not crashed
Text for the model
a result or an error message
- 1The model asks for one or more calls, each with a name and arguments.
- 2The name is on the list, so the call goes on to run.
- 3The name is not on the list, so an error text goes back at once.
- 4The tool runs, and its result or its error goes back.
- 5The text is added to the history, and the model decides the next step.
Two facts from Anthropic's docs make this design sound. The model sees the tool's schema and the results you return, never your code. And each tool call has an id that its result must name back.
What does a small version look like?
Here is one in 28 lines of plain Python. The tool is a made-up bank support lookup, and the model is a scripted stand-in, so the output is fixed. The AI is swapped for a list of calls on purpose, so you can check the loop without a model.
# A scripted stand-in for the model: the loop and the dispatch are real, the AI is not.
def get_balance(args):
if "account" not in args:
raise ValueError("account is required")
return "balance 1820.40 on account " + args["account"]
TOOLS = {"get_balance": get_balance}
def dispatch(call):
fn = TOOLS.get(call["tool"]) # only registered tools can run
if fn is None:
return "error: unknown tool " + call["tool"]
try:
return fn(call["args"])
except Exception as err: # any tool error goes back as text, so the model can retry
return "error: " + str(err)
def run_agent(model_calls, max_steps):
results = []
for _ in range(max_steps): # the step cap stops a loop that never ends
call = next(model_calls) # the model only picks the next call
if "final" in call:
return "DONE: " + call["final"]
results.append(dispatch(call))
print(call["tool"], "->", results[-1])
return "STOPPED: step cap reached, send to a person"
lookup = {"tool": "get_balance", "args": {"account": "77-1043"}}
print(run_agent(iter([{"tool": "get_balance", "args": {}},
{"tool": "send_refund", "args": {"amount": 900}}, lookup,
{"final": "Balance is 1820.40. The refund needs a person."}]), 5))
print(run_agent(iter([lookup] * 3), 2))Output
get_balance -> error: account is required send_refund -> error: unknown tool send_refund get_balance -> balance 1820.40 on account 77-1043 DONE: Balance is 1820.40. The refund needs a person. get_balance -> balance 1820.40 on account 77-1043 get_balance -> balance 1820.40 on account 77-1043 STOPPED: step cap reached, send to a person
Read it top to bottom. The first call leaves out the account, so the tool raises an error and the error text goes back. The model then asks for send_refund, which is not in the table, so it is refused. The third call works, and the fourth is a final answer that ends the loop. The second run has a cap of 2, so it stops after two calls and goes to a person.
Tip
Real model APIs add a little more structure. Each tool call carries an id, and each result names that id back. A failed result is flagged as an error, so the model knows to try again or stop.
What goes wrong, and how do you handle it?
Four things break most small loops. Plan for each one before the first demo.
The model invents a tool name
Refuse it in code and send an error text back. Never guess which tool was meant.
Arguments are missing or wrong
Check them inside the tool, raise an error, and return the text so the model can fix the call.
The loop never settles
Set a step cap. When it is hit, stop and send the case to a person, with the steps so far.
A tool result carries an order
A web page or an email can hold a line that reads like an instruction. Treat tool output as data, never as orders.
“The model never runs anything on its own.”
Anthropic, tool use
“Set to true if the tool failed or the call was invalid.”
Anthropic, handle tool calls
“The task often terminates upon completion, but it's also common to include stopping conditions (such as a maximum number of iterations) to maintain control.”
Anthropic, Building Effective Agents
Anthropic's team also recommends extensive testing in sandboxed environments, with the right guardrails in place. A loop with a cap, a table and a scripted run is the cheapest place to start that testing.
How would you run this for a real bank?
Say the assistant can read balances and issue refunds. A customer types: "Can you refund the $900 charge and tell me my balance?" The model may ask for two tools in a row. The demo above has a step cap and a tool table, but no limit on amounts and no person in the loop.
- Demo
Any amount, no person
No limit on refund amounts and no person checks a large one. One confused reply can send a refund again.
- Production
Only what the table allows
Each tool has a fixed scope. Refunds above a set limit wait for a person, and every run stops at the step cap.
What does the interviewer want to hear?
A strong answer covers
- The model only asks for a call. Your code runs it.
- A lookup table from names to functions, with unknown names refused.
- Errors go back as text, so the model can retry or stop.
- A step cap, so the loop can't run forever.
- Tool output is data to read, never a rule to obey.
- A scripted run first, then a real model in a sandbox.
Common traps
Trap"The model will know when to stop, so no cap is needed."
BetterModels can loop. Keep a step cap, and send the case to a person when it is hit.
Trap"Any function name the model gives can run."
BetterOnly names in your table run. Anything else gets an error text back.
Trap"If a tool fails, retry it until it works."
BetterRetry a few times at most. Then return the error, so the model or a person can decide.
Can you spot the fault in the loop?
Spot the fault
Your refund agent keeps calling get_balance with the same account on every turn, and the token bill climbs. Which line stops it?
Quick check
The model asks for send_refund, which is not in your table. What should the code do?
Can you answer these from memory?
Flash cards · tap a card to flip it
What will they ask next?
Learn it in depth
Last updated on 27 November 2026
Building an agent that calls your own systems?
I design and build AI agents, the interface and the system behind them, including the tool layer and its limits. Book a short call and tell me which tools your agent needs.