By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
A customer writes in about a damaged pair of trail shoes. Your agent checks the order, issues 45.00 USD, and replies in a calm, confident voice. The reply is wrong. The customer asked for the full 129.00 USD, and the agent quietly decided on a smaller number.
Nothing crashed. No exception reached your logs. The agent stopped on its own, exactly as designed. That is why this failure is hard to see: every component did what it was told.
This lab is scenario 1 from the six published CCAR-F scenarios, the customer support resolution agent. Your brief: build the loop behind that conversation, with four tools, a refund limit, and an escalation path that takes over when the model is unsure or policy says no.
| Tool | What it does | What it returns on failure |
|---|---|---|
get_customer | Reads the name and tier for a customer id | customer_not_found, not retryable |
lookup_order | Reads the item, amount and status for an order id | order_not_found, not retryable |
process_refund | Moves money, up to the 5000-cent policy limit | refund_over_limit or already_refunded |
escalate_to_human | Opens a tier 2 case with a reason and a summary | Nothing: the handoff is the success path |
Escalation is a tool, not a catch block. The same function serves the model when it decides a case is too hard, and serves your harness when a gate fails. One function means one queue, one audit trail and one place to change the routing.
A tool is a function your code runs because the model asked for it. Each model reply ends with a stop reason. tool_use means 'run this and ask me again'. end_turn means 'I am finished'. The transcript records every turn, tool call and result in order.
Your loop has two jobs. It runs the tools the model names, and it decides whether the model's final answer may reach the customer. The model owns the plan. Your code owns the gate.
Every tool returns a dictionary. A success carries data. A failure carries an error object with a code, a message and a retryable flag.
Two rules carry most of the value. First, an expected failure is a value, not an exception: order_not_found must reach the model as a tool result, so the model can try something else. Second, the refund limit is enforced in the tool, not in the prompt. A prompt is a request. Code is a limit.
In production these four functions sit behind an MCP server, so the agent sees them as tools rather than imports. The loop does not care where the dispatcher gets them. That is the point of a tool contract.
The scripted client at the end of this part replaces the model. It returns canned turns, so the lab is deterministic and needs no API key. It proves your loop, not the model's judgement.
"""Lab 1: a support resolution agent with four tools and two gates."""
from __future__ import annotations
import json
POLICY = {
"refund_limit_cents": 5000,
"min_confidence": 0.70,
"max_turns": 6,
}
CUSTOMERS = {
"C-104": {"name": "Dana Ruiz", "tier": "gold"},
"C-207": {"name": "Sam Patel", "tier": "standard"},
}
ORDERS = {
"A17": {
"customer_id": "C-104",
"item": "Trail shoe",
"amount_cents": 4500,
"status": "delivered",
},
"C33": {
"customer_id": "C-207",
"item": "Standing desk",
"amount_cents": 12900,
"status": "delivered",
},
}
def ok(**payload):
return payload
def fail(code, message, retryable=False):
return {"error": {"code": code, "message": message, "retryable": retryable}}
# ── The four tools. Every failure is a value, never an exception. ──────────
def get_customer(customer_id):
customer = CUSTOMERS.get(customer_id)
if customer is None:
return fail("customer_not_found", f"no customer with id {customer_id}")
return ok(customer_id=customer_id, **customer)
def lookup_order(order_id):
order = ORDERS.get(order_id)
if order is None:
return fail("order_not_found", f"no order with id {order_id}")
return ok(order_id=order_id, **order)
def process_refund(order_id, amount_cents):
order = ORDERS.get(order_id)
if order is None:
return fail("order_not_found", f"no order with id {order_id}")
if order["status"] == "refunded":
return fail("already_refunded", f"order {order_id} was already refunded")
if amount_cents > POLICY["refund_limit_cents"]:
return fail(
"refund_over_limit",
f"{amount_cents} cents is above the {POLICY['refund_limit_cents']} cent limit",
)
order["status"] = "refunded"
return ok(order_id=order_id, amount_cents=amount_cents, status="approved")
def escalate_to_human(reason, summary):
return ok(queue="tier2-support", reason=reason, summary=summary)
TOOLS = {
"get_customer": get_customer,
"lookup_order": lookup_order,
"process_refund": process_refund,
"escalate_to_human": escalate_to_human,
}
# ── A scripted stand-in for the model. No key, no network, no surprises. ──
class FakeSupportModel:
"""Returns one scripted turn per call and ignores the message history."""
def __init__(self, turns):
self._turns = list(turns)
self._index = 0
def next_turn(self, messages):
turn = self._turns[self._index]
self._index += 1
return turn
def use_tool(tool_id, name, **tool_input):
return {
"stop_reason": "tool_use",
"content": [
{"type": "tool_use", "id": tool_id, "name": name, "input": tool_input}
],
}
def answer(text, confidence):
return {"stop_reason": "end_turn", "text": text, "confidence": confidence}The loop stops on end_turn. Before it trusts that stop, it asks two questions. Is the reported confidence below the 0.70 floor? Did any tool return a hard error that was never resolved?
A hard error is one that retrying cannot fix: unknown order, refund over the limit, already refunded. The model still sees it as a tool result, but the guard counts it as open. A retryable error, such as a timeout, goes back for another attempt and never blocks the answer. The difference is the retryable flag you set in the tool.
If either answer is yes, the loop hands the case to a person. Note who calls escalate_to_human: the harness, not the model. A model that can choose to escalate can also choose not to.
# ── The loop: one stop condition, one error channel, one guard. ───────────
def run_agent(model, question):
messages = [{"role": "user", "content": question}]
transcript = []
hard_errors = []
for turn_number in range(1, POLICY["max_turns"] + 1):
reply = model.next_turn(messages)
if reply["stop_reason"] == "end_turn":
reasons = []
if reply["confidence"] < POLICY["min_confidence"]:
reasons.append(f"low_confidence({reply['confidence']:.2f})")
if hard_errors:
reasons.append("unresolved_" + hard_errors[0])
transcript.append(
{
"turn": turn_number,
"kind": "answer",
"name": "end_turn",
"detail": {"confidence": reply["confidence"], "text": reply["text"]},
}
)
if reasons:
return hand_off(transcript, question, "+".join(reasons), turn_number)
return {"outcome": "answered", "reason": "", "transcript": transcript}
for block in reply["content"]:
if block["type"] != "tool_use":
continue
tool = TOOLS.get(block["name"])
if tool is None:
result = fail("unknown_tool", f"no tool named {block['name']}")
else:
try:
result = tool(**block["input"])
except TypeError as exc:
result = fail("invalid_tool_input", str(exc))
except Exception as exc: # a tool failure must not end the run
result = fail("tool_error", str(exc))
transcript.append(
{
"turn": turn_number,
"kind": "tool",
"name": block["name"],
"detail": {"input": block["input"], "result": result},
}
)
messages.append(
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": block["id"],
"is_error": "error" in result,
"content": result,
}
],
}
)
if "error" in result and not result["error"]["retryable"]:
hard_errors.append(result["error"]["code"])
return hand_off(transcript, question, "turn_budget_exhausted", POLICY["max_turns"])
def hand_off(transcript, question, reason, turn_number):
result = escalate_to_human(reason=reason, summary=question)
transcript.append(
{
"turn": turn_number,
"kind": "guard",
"name": "escalate_to_human",
"detail": {"input": {"reason": reason}, "result": result},
}
)
return {"outcome": "escalated", "reason": reason, "transcript": transcript}
# ── Two runs: one resolved in policy, one handed to a person. ─────────────
REFUND_OK = [
use_tool("t1", "get_customer", customer_id="C-104"),
use_tool("t2", "lookup_order", order_id="A17"),
use_tool("t3", "process_refund", order_id="A17", amount_cents=4500),
answer("I refunded 45.00 USD to your gold card for order A17.", 0.92),
]
REFUND_ESCALATE = [
use_tool("t1", "get_customer", customer_id="C-207"),
use_tool("t2", "lookup_order", order_id="C33"),
use_tool("t3", "process_refund", order_id="C33", amount_cents=12900),
answer("I can refund part of order C33 today, about 45.00 USD.", 0.62),
]
def show(label, result):
print(label)
for row in result["transcript"]:
print(f" turn {row['turn']} {row['kind']:<6} {row['name']}")
for key, value in row["detail"].items():
detail = json.dumps(value, sort_keys=True, separators=(",", ": "))
print(f" {key:<11} {detail}")
print(f" outcome: {result['outcome']} reason: {result['reason'] or '-'}")
print()
def main():
show(
"RUN 1 damaged item, refund inside policy",
run_agent(
FakeSupportModel(REFUND_OK),
"Order A17 arrived damaged. I would like a refund.",
),
)
show(
"RUN 2 full refund above policy, low confidence",
run_agent(
FakeSupportModel(REFUND_ESCALATE),
"Order C33 arrived damaged. Refund the whole 129.00 USD now.",
),
)
if __name__ == "__main__":
main()Save both parts as lab1_support.py and run it with Python 3.11 or newer. Do not install anything and do not set an API key.
python lab1_support.py| Turn | Run 1: inside policy | Run 2: above policy |
|---|---|---|
| 1 | get_customer C-104 returns a gold customer | get_customer C-207 returns a standard customer |
| 2 | lookup_order A17 returns 4500 cents | lookup_order C33 returns 12900 cents |
| 3 | process_refund 4500, approved | process_refund 12900, refund_over_limit |
| 4 | end_turn at 0.92; the guard sends it | end_turn at 0.62; the guard refuses |
| Outcome | Answered | Escalated |
Turn 4 is where the runs separate. The model does the same thing both times: it stops and states a conclusion. Only the guard knows that one conclusion is unaffordable and unsure.
Run 2's guard line names both reasons, low_confidence(0.62) and unresolved_refund_over_limit. That string is the whole diagnosis. A reviewer can read it without the rest of the transcript.
A reviewer gets three things: the original question, every tool result, and the reason string. That is not a courtesy. It is the difference between a two-minute resolution and a callback.
These four failures appear in real support agents. Each has a control you can point at in the code above.
| Failure | What you see | Control |
|---|---|---|
| A tool raises an exception | A traceback ends the turn and the customer gets nothing | invalid_tool_input or tool_error returns as data instead |
| The model names a tool you do not have | A KeyError kills the run at the dispatcher | TOOLS.get, then return unknown_tool as data |
| The model stops after a policy error | A confident answer that promises money you cannot send | The guard escalates on any unresolved hard error |
| Confidence is low but the text looks fine | Plausible prose with no human review | A confidence floor checked by the harness, not the model |
Your lab is done when every line below is true. Run the verification command again after each change.
process_refund refuses any amount above 5000 cents and returns refund_over_limit.end_turn and never runs past the max_turns budget.escalated, and the reason names both the low confidence and the unresolved policy error.The stretch task has three parts. Do them in order, because each one tests a different gate.
process_payment, a tool that does not exist. Confirm the transcript shows unknown_tool and the loop keeps going.confidence_ok and errors_resolved, then make one run fail each on its own. You should get two escalations with one reason each.Key takeaways
The model plans; the harness decides whether the plan reaches the customer.
Stop on end_turn, but check confidence and open hard errors before you trust it.
A tool failure is a structured value, so the model can recover instead of the run dying.
Enforce money limits in the tool, and keep the escalation call in the harness.
A transcript with named stop reasons is the cheapest debugging tool you own.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.