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

AI and LLM interview question Q175, Agents and tool use. Advanced, very common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/reliable-tool-calling-loop

## Say it in 30 seconds

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.

## Say it in 2 minutes

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.

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

*Diagram, One round of a tool loop: The model only asks. Your app checks and runs each request, sends back a result for every one, then reads the stop reason. A tool-use stop means go round again, and any other stop ends the loop.*
1. The model's tool request goes to your app.
2. Each result, or each error, goes into the reply for that call.
3. Your app sends the replies and reads the stop reason.
4. If the model wants more tools, the loop goes round again.
5. Any 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.

*Diagram, Checks before a tool runs: The model's request is only a request. Two checks in code must pass before the tool runs. A failed check sends an error back, or a person decides.*
1. The model's request arrives. It is only a request.
2. Both checks pass, so the tool runs.
3. A 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."

```python
# 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:

```text
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." Better: Strict mode fixes the shape of the arguments. Your code still checks whether the action is allowed.
- Trap: "A step cap means we are done." Better: A cap stops a runaway loop. A wrong refund on step two still needs a check on that call.
- Trap: "Retry until it works." Better: Retries 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?

A. Each call is checked against the allow-list before it runs.
B. After the failed refund, the loop sends no result for that call and asks the model again.
C. The loop stops after 12 steps and hands the file to a person.
D. Refunds over the approved limit go to a human approver.

**Answer:** B. Every call needs its own result, even a failed one. Without it, Anthropic's API returns an error on the next request.

**Quick check:** A refund call times out. The bank may or may not have paid it. What is the safest next step?

A. Send the same refund again right away, with no limit
B. Tell the customer the refund failed and close the case
C. Look up whether the refund posted, then retry with the same request ID
D. Ask the model to guess whether the refund posted

**Answer:** C. A timeout does not tell you whether the money moved. Check the bank's own record first. Then retry with the same request ID, a label that tells the bank this is the same payment, so the bank can spot a repeat.

## Can you answer these from memory?

**Flash cards**

- **Who runs the tool?** Your code, for tools you define. The model only asks.
- **What must every tool call get?** A result, even when the call failed.
- **What does is_error do?** Tells the model the call failed or was invalid.
- **Why a step cap?** A loop with no limit can run forever.
- **Does strict mode make a call safe?** No. It fixes the shape. Your code still checks the action.
- **Where do the checks live?** In code, outside the model.

## Likely follow-up questions

- Q156 What is tool (function) calling? https://designervenkat.online/interview/ai/what-is-tool-calling
- Q173 How do you stop endless agent loops? https://designervenkat.online/interview/ai/how-do-you-stop-endless-agent-loops
- Q176 How should an agent handle tool errors and retries? https://designervenkat.online/interview/ai/how-should-an-agent-handle-tool-errors-and-retries
- Q178 What is parallel tool calling? (full answer coming)
- Q179 Excessive agency and least privilege? https://designervenkat.online/interview/ai/excessive-agency-and-least-privilege
- Q181 How do you evaluate agents? https://designervenkat.online/interview/ai/how-to-evaluate-ai-agents
