Write the support agent's loop with every exit named
Build the loop for a fictional shop's support agent against a scripted model, then give it three named exits: an answer, a repeated call and a step limit. A run that stops should always say which exit it took, so a caller and a test can tell success from a stuck run.
20 MIN
By AIAgentInterviews · Updated
TL;DR: The loop repeats four operations: call the model, run any tool calls, append the results, repeat. The work is in the exits. Return a named exit on every path (answered, repeating, step limit) so a stuck run never looks like a finished one.
Where you are. Module one, lesson one. You build the skeleton every later lesson adds to.
The agent you are building
Fernhill Supply is an invented outdoor-gear shop. Its support agent answers three kinds of message: where is my order, can you change my address, can I have a refund. Behind it sit three ordinary APIs the shop already runs: an order service, a shipping service and a payments service. The agent's job is to choose which to call, in what order, and to stop when the customer has an answer.
Nothing here needs a real model. A scripted fake hands back a fixed sequence of replies, which is how you will test the harness for the rest of the course. The fake verifies the harness on the scripted paths. Real models can produce additional behavior, so extend the fixtures from observed failures and measure model quality separately.
In plain language. A turn is one model request and its reply. A tool call is a proposed operation; the harness is your program that decides whether and how to execute it. The model does not reach the shop service by emitting its name.
A loop you can run offline
The loop keeps a message list. Each turn it asks the model for a reply. A reply either carries tool calls or it carries text. Tool calls run, and their results go back into the list as messages, so the next turn can see them. Text ends the run.
import json
def scripted(replies):
"""A fake model: hands back the next scripted reply on every call."""
queue = list(replies)
def model(messages, tools):
return queue.pop(0) if queue else {"content": "(script exhausted)"}
return model
TOOLS = {
"orders_get": lambda order_id: {"id": order_id, "status": "shipped"},
"shipping_get": lambda order_id: {"carrier": "Parcelway", "eta": "2026-11-27"},
}
def run(model, task, max_steps=6, max_repeats=2):
messages = [{"role": "user", "content": task}]
seen = {}
for step in range(1, max_steps + 1):
reply = model(messages, list(TOOLS))
messages.append({"role": "assistant", **reply})
calls = reply.get("tool_calls")
if not calls:
return {"exit": "answered", "steps": step, "text": reply["content"]}
for call in calls:
key = (call["name"], json.dumps(call["args"], sort_keys=True))
seen[key] = seen.get(key, 0) + 1
if seen[key] > max_repeats:
return {"exit": "repeating", "steps": step, "call": call["name"]}
if call["name"] not in TOOLS:
result = {"error": f"unknown tool {call['name']}"}
else:
try:
result = TOOLS[call["name"]](**call["args"])
except Exception as exc:
result = {"error": f"{type(exc).__name__}: {exc}"}
content = json.dumps(result)
messages.append({"role": "tool", "name": call["name"], "content": content})
return {"exit": "step_limit", "steps": max_steps}
lookup = {"tool_calls": [{"name": "orders_get", "args": {"order_id": "FH-1182"}}]}
ship = {"tool_calls": [{"name": "shipping_get", "args": {"order_id": "FH-1182"}}]}
done = {"content": "FH-1182 shipped with Parcelway and arrives on 27 November."}
r = run(scripted([lookup, ship, done]), "Where is FH-1182?")
print(r["exit"], r["steps"]) # => answered 3
r = run(scripted([lookup] * 5), "Where is FH-1182?")
print(r["exit"], r["steps"], r["call"]) # => repeating 3 orders_get
r = run(scripted([lookup, ship] * 10), "Where is FH-1182?", max_repeats=9)
print(r["exit"], r["steps"]) # => step_limit 6
Three scripts, three exits. The first is the happy path: look up the order, look up the shipment, answer. The second is a model that keeps asking for the same order. The third alternates between two calls forever, which a repeat counter set high will not catch, so the step limit does.
Why every exit gets a name
A loop that returns only the model's last text has one way to say "done" and no way to say "stuck". Callers then treat a run that hit the step limit as an answer, and the customer receives whatever the model said on its sixth turn. Naming the exit costs one field and buys three things.
The caller can act on it. answered goes to the customer; repeating and step_limit go to a person, with the transcript.
Tests can assert on it. Each exit above is one line of test, and a change that breaks an exit fails a build instead of a conversation.
Traces can count it. Later in the course you will chart how often runs leave by each exit. A rising share of step_limit is often the first sign that a prompt or tool change made the agent worse.
Errors stay inside the loop
Two paths in the loop do not exit: an unknown tool name and a tool that raises. Both become results the model can read on its next turn, because the model can often recover (it misspelled a tool, it passed a bad order number). Stopping the run on the first error throws that chance away. Lesson two makes those errors far more useful by putting each tool behind a contract.
Separating the two kinds of problem is the rule to keep: errors the model can fix go back to the model, conditions only the harness can see (repetition, the step limit, later a token budget) end the run with a name.
- 01userWhere is FH-1182?
- 02toolorders_get(FH-1182)
- 03toolshipping_get(FH-1182)
- 04finalexit=answered after 3 steps
The happy path
Two lookups and a text reply. The run leaves by the answered exit after three model calls.
What the step limit is not
The step limit is a backstop, not a budget. Six steps suits a lookup; a refund with an address change may need ten. Set it from the longest legitimate path you have seen plus a margin, and treat any run that reaches it as a bug report. The context-budget lesson adds token accounting. Before that, the model-boundary module adds selection, message, completion and evidence checks.
Walk the boundary between a reply and a result
Pause at the first orders_get proposal. The model has supplied an order identifier, but the program has not yet looked up anything. After the executor returns, the transcript contains new evidence. Only the next model turn can use that observation. This is why appending the tool result is part of the loop, rather than optional logging.
Read the three scripts as a small state machine:
| Observation at the boundary | Harness action | What the caller learns |
|---|---|---|
| A permitted lookup is proposed | Execute and append its result | Work is still running |
| The identical lookup exceeds the repeat allowance | Stop before executing it again | The run is stuck |
| Text arrives without a call | Return the proposed answer | The model has stopped asking for tools |
That last row needs care. In this first skeleton, answered means the model produced text. It does not establish that the order exists, that the customer owns it, or that the sentence is supported. The completion-check lesson adds that stronger contract. A fake that exhausts its script is also a test-fixture problem, not a successful customer answer; reject that sentinel in a release harness.
Now change the first script to return text immediately. It still exits answered. You have just separated control-flow correctness from task correctness: the program followed its loop, but the customer may not have received a justified answer. Keep both claims separate when reporting a test result.
What if · interview follow-ups
Change one condition
Fernhill can stop a looping model, but the support team wants to know what the exit actually proves.
Start here
The model returns a fluent shipment answer before any lookup. Which check passes, and which evidence is missing?
Distinguish stopping from completing the customer task.
The skeleton reaches its text exit. A supported shipment answer still needs a lookup tied to the owned order, or equivalent trusted evidence already supplied to the run. Fluency supplies neither.
Weak answerCalling every text exit a successful resolution.
Constraint changes
Now a lookup contains a hundred proposed tool calls in one reply. Does a six-turn limit bound service work?
Count calls and turns separately.
No. One model turn can contain many operations. Add a call-count limit and per-tool admission before dispatch, alongside wall-time and usage budgets. Test that the excess calls never reach the fake executor.
Weak answerMultiplying the model-turn limit by an assumed one-call-per-turn rule.
Do this before moving on
Take any agent you have written, or copy the loop above, and list every way a run can end. For each, write the exit name your code returns today. If two different endings return the same thing, or an ending returns nothing at all, add a name and one test that drives a scripted model into it.
Review your result. Keep a table of script, exit, model calls and executor calls. Include an immediate unsupported answer and a multi-call reply. Your observations should expose what this skeleton proves and what the later completion and budget checks must add.
Go deeper
- The Agent Loop: the general mechanism behind this lesson's executable loop, with the four moves named.
- Stop Conditions and Budgets: every kind of exit a production loop needs, beyond the three built here.
- The Harness and the Authority Line: which decisions stay in code no matter what the model proposes.
- Reading a Trace: how the exits you just named show up when you debug a real run.
- Testing Agents with a Scripted Model: the scripted-model technique applied to a whole test suite.
Key takeaways
- The loop is short; the exits are the design. Every path out returns a name.
- Errors the model can fix go back to it as results. Conditions only the harness can see end the run.
- A scripted fake model makes every exit testable without a network or an API key.
- The step limit is a backstop set from real paths, not a cost control.
Check yourself
Answer aloud or on paper before revealing. Producing the explanation unaided is exactly what a panel listens for.
1A run reaches the step limit and the loop returns the model's last message as if it were an answer. What goes wrong?
2The model calls a tool that does not exist. Should the loop stop the run?
3Why does the third script need the step limit when a repeat counter is already in place?
Sign in to track which lessons you have finished.