What Makes a Tool-Calling Loop Reliable?
The loop, the checks, the stop rules and the error handling that make an AI agent's tool calls safe to ship, explained simply for your AI interview.
In short
A reliable tool-calling loop checks every request the model makes before it runs, answers every call (even failed ones), and always has hard stop rules. Test it on realistic multi-step tasks before you ship.
13 min readAdvancedVery common · estimateFacts checked 26 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.
A tool-calling loop is the cycle where a model asks for a tool, your code runs it, and the result goes back. To ship one, I check every request in code before it runs: the arguments must match the schema, and the action must be allowed for this customer and this amount. Every call gets an answer, even a failed one, and retries are capped. The loop has a step cap and clear stop rules, so it cannot run forever. Then I test it on realistic multi-step tasks before anything goes live.
A tool-calling loop is how an agent gets work done in outside systems. The model asks for a tool, your code runs it, the result goes back, and the model decides what to do next. The model never runs anything itself.
Reliable means it keeps behaving when things go wrong. The model can send a wrong argument, a tool can time out, or the model can ask for something it should never do. So I check every request in code before anything runs. The arguments must match the schema, and the action must be allowed for this customer and this amount. Anything over a limit goes to a person.
Every call gets an answer, even when it failed, and failures are marked so the model knows. Retries are capped. The loop has a step cap and clear stop rules, so it cannot run forever. If it hits the cap, the case goes to a human with the log of what happened.
Last, I test the whole loop on realistic multi-step tasks in a sandbox, before and after each change. A call can match the schema and still be unsafe, so tests are how you find that gap.
What is a tool-calling loop, in plain words?
A tool-calling loop is the cycle an AI agent uses to get things done outside the chat. The model asks for a tool by name, with arguments, such as looking up a claim. Your code runs it, sends the result back, and the model decides the next step. The loop repeats until the model has its answer.
Reliable means it still behaves when things go wrong. Anthropic's engineers put the risk plainly: "Occasionally, an agent might hallucinate or even fail to grasp how to use a tool." To hallucinate means to produce an answer or action that sounds right yet has no basis in real data.
Key words
- Tool call
- The model's request to run one function, with a name and arguments.
- Tool result
- What your code sends back for that call, including an error if it failed.
- Schema
- The written rules for the arguments, such as a claim ID as text.
- Step cap
- A hard limit on how many rounds the loop may run.
Think of a claims clerk at an insurer working through a stack of files. Each time she needs a record, she writes a request slip and the records team fetches it. A good office checks each slip before acting on it, replies to every slip (even one that says "not found"), and limits how many slips one file can use, so nobody is stuck in a loop. In an AI claims triage agent, the clerk is the model, the records team is your code, and the slips are tool calls.
How does one round of the loop run?
Each round has the same parts. The model asks for a tool. Your app checks the request and runs it. Your app sends back a reply for every request. Then your code reads the stop reason, the label the API sends back that says why the model stopped (such as tool_use), to decide whether to go round again.
One round of a tool loop
Model
asks for a tool, runs nothing
Your app
Run each call
check first, then run it
Send every result back
errors too, marked as errors
Stop reason is tool_use?
if yes, go round again, within the cap
Loop ends
any other stop reason ends it
- 1The model's tool request goes to your app.
- 2Each result, or each error, goes into the reply for that call.
- 3Your app sends the replies and reads the stop reason.
- 4If the model wants more tools, the loop goes round again.
- 5Any other stop reason ends the loop, such as a final answer or a refusal.
Anthropic's docs describe the exit this way: "The loop exits on any other stop reason ("end_turn", "max_tokens", "stop_sequence", or "refusal"), which means Claude has either produced a final answer or stopped for another reason that your application should handle."
A model can ask for several tools in one turn. OpenAI's docs say: "The model may choose to call multiple functions in a single turn." OpenAI also advises to "assume there are several" calls, so the loop must handle a list, not one call. Parallel calls are faster, but two writes that run at once can clash. OpenAI notes that you can set parallel_tool_calls to false, which "ensures exactly zero or one tool is called."
What stops the loop from running forever?
A loop needs a clear exit. The normal exit is a stop reason other than tool use, such as end_turn when the model has finished. Other stop reasons, such as max_tokens (the reply ran out of room) or refusal (the model declined), also end the loop, so your code must handle them. Models do not always reach a final answer, so you also add hard limits in code. Anthropic's engineers note that it is common to include "stopping conditions (such as a maximum number of iterations) to maintain control."
- Without a cap
Runs until a bill stops it
A claims agent keeps re-reading the same policy file, because each reply asks for one more check. Nothing ends the loop, and time and money drain away.
- With a cap
Stops at the limit
After 12 steps the loop stops and hands the file to a claims handler, with the log of every call it made.
Pick the cap from real tasks. Run realistic cases, find the longest honest one, and set the cap above it, so a normal case never hits it.
How should errors and retries work?
A tool can fail. A service can be down, an ID can be wrong, or the model can send a date in the wrong format. The loop's job is to tell the model what happened, so it can fix a small mistake and stop on a big one.
- 1
Answer every call
Each call needs its own result, even a failed one. If one is missing, Anthropic's API returns an error.
- 2
Mark the failure
In Anthropic's API, set is_error to true when a call fails or is invalid, so the model reads the result as a failure.
- 3
Cap the retries
The model may try the same tool again with a new call. Count the attempts in code and stop at a set number.
- 4
Split fixable from fatal
A wrong date format can be fixed by the model. A service that is down cannot. Send the first back with a clear message, and send the second to a person.
“Claude might then call the tool again with a new tool_use block, so limit how many retries your loop allows.”
Anthropic, tool use docs
What must your code check before a tool runs?
A schema is the written rule for the arguments. OpenAI says: "Setting strict to true will ensure function calls reliably adhere to the function schema, instead of being best effort." It adds: "We recommend always enabling strict mode." Strict mode, the setting that turns this rule on, fixes the shape of the call. It cannot decide whether the action is allowed.
A call can match the schema and still be wrong. Take a bank's support assistant that asks its refund tool for 9,500 on an account that belongs to someone else. The shape is fine, but the action must not run.
“Setting strict to true will ensure function calls reliably adhere to the function schema, instead of being best effort.”
OpenAI, function calling docs
“Route privileged calls through a deterministic policy engine that re-validates intent and arguments at execution time.”
OWASP, LLM01:2026
“Require explicit human confirmation before any privileged, irreversible, or externally visible action”
OWASP, LLM01:2026
The rules live in code, outside the model. OWASP puts it this way: "Hold credentials and state-change capability in application code, not the model, and grant least privilege per operation." So the refund tool reads one customer's account, refunds have a ceiling, and anything above it waits for a person.
Checks before a tool runs
Model asks
a request, not an action
Checks in your code
Schema matches
right types, required fields present
Allowed for this case
this customer, this amount, this scope
Tool runs
only when every check passes
Error sent back
or the case goes to a person
- 1The model's request arrives. It is only a request.
- 2Both checks pass, so the tool runs.
- 3A failed check sends an error back, or a person decides.
Tool results can carry hidden text from a web page or an email, so treat them as untrusted, as Anthropic's docs advise. Test the whole loop, not only the prompt. Anthropic's engineers say: "We recommend extensive testing in sandboxed environments, along with the appropriate guardrails."
# A simplified claims-triage loop. The model is a scripted stand-in, so the output is fixed.
MAX_STEPS = 4
ALLOWED = {"lookup_claim", "request_payment"}
def fake_model(step):
script = [
{"tool": "lookup_claim", "args": {"claim_id": "CL-1042"}},
{"tool": "request_payment", "args": {"claim_id": "CL-1042", "amount": 9500}},
{"tool": "delete_claim", "args": {"claim_id": "CL-1042"}},
]
return script[step] if step < len(script) else None # None means: final answer
def run_tool(name, args):
if name not in ALLOWED: # the allow-list, checked in code
return {"is_error": True, "text": name + " is not an allowed tool"}
if name == "request_payment" and args["amount"] > 5000: # the limit, checked in code
return {"is_error": True, "text": "over the 5000 limit, needs a person"}
return {"is_error": False, "text": name + " ok"}
for step in range(MAX_STEPS): # the step cap stops a loop that never ends (not reached in this run)
call = fake_model(step)
if call is None:
print("final answer")
break
result = run_tool(call["tool"], call["args"])
status = "ERROR" if result["is_error"] else "OK"
print("step " + str(step + 1) + ": " + call["tool"] + " -> " + status + ": " + result["text"])
else:
print("stopped: step limit reached, hand to a person")Output
step 1: lookup_claim -> OK: lookup_claim ok step 2: request_payment -> ERROR: over the 5000 limit, needs a person step 3: delete_claim -> ERROR: delete_claim is not an allowed tool final answer
How would you debug a loop that keeps calling the same tool?
Log every call with its ID, arguments, result and stop reason. A loop that repeats the same call with the same arguments is making no progress. Add a repeat check next to the step cap, so the loop stops and escalates when it sees the same call come back the same way.
A realistic case: a coding agent in a CI pipeline (the automatic build and test runner that checks each change) re-runs a failing test again and again, because a tool returns an empty log and the model reads the empty log as a reason to try again. The fix is to make the empty case an explicit error, cap the retries, and post what the agent saw so a person can read it.
What does the interviewer want to hear?
A strong answer covers
- A plain picture: the model asks, your code runs, the result goes back.
- Stop rules: a step cap and a clear stop reason, so the loop always ends.
- Every call gets an answer, including the failed ones.
- Checks in code before any tool runs: schema, a list of allowed tools (an allow-list), limits.
- Human sign-off for risky or irreversible actions.
- Tests on realistic multi-step tasks in a sandbox (a safe test copy of the real systems), before and after each change.
Common traps
Trap"If the schema is strict, the call is safe."
BetterStrict mode fixes the shape of the arguments. Your code still checks whether the action is allowed.
Trap"A step cap means we are done."
BetterA cap stops a runaway loop. A wrong refund on step two still needs a check on that call.
Trap"Retry until it works."
BetterRetries need a limit. Past the cap, send the case to a person with the log.
Can you spot the loop bug?
Spot the bug
The model asks for a refund. The refund call fails, and the loop moves on. Which line is the reliability bug?
Quick check
A refund call times out. The bank may or may not have paid it. What is the safest next step?
Can you answer these from memory?
Flash cards · tap a card to flip it
What will they ask next?
Last updated on 26 November 2026
Building an agent that calls tools on real systems?
I design and build AI agents, the interface and the system behind them, including the tool loop, its checks and its tests. Book a short call and tell me what your agent needs to reach.