Module 10 · Lesson 10.4
Add Memory, Validation and Human Approval
On this page
- What you will learn
- What you will build: a triage desk with a memory and a human gate
- Step 1: Set up the project folder
- Step 2: Give the agent a memory with a time limit (memory.py)
- Step 3: Check every triage record before it goes on (validate.py)
- Step 4: Build the approval queue and the outbox (approvals.py, review.py)
- Step 5: Change request_return and the instructions (tools.py, versions.py)
- Step 6: Rebuild the agent loop with a budget, a retry and the queue (agent.py)
- Step 7: Test every rule offline with a fake model
- Step 8: Run the fake inbox and play the reviewer
- Step 9: Run it with the real model and check the requests
- Step 10: Map each step to a requirement and write your notes
- If you chose a different option
- Conclusion and your next step
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
Think of a new clerk at a bike shop. The clerk keeps a card file of past customer cases, but the cards carry a code instead of a name and are shredded after three months. A colleague proofreads every letter before it goes out. The clerk has a phone-call limit for each case. And no letter is posted until the manager signs it.
In this lab you give your triage agent the same four habits. You add a memory with a time limit, a validation step that checks each answer, a budget for model calls and an approval queue where a named person decides. Nothing here needs a real model. You test every rule offline with a fake one, then you watch a reviewer approve one draft and reject another.
What you will learn
- Store past cases under a pseudonymous key, delete them after 90 days and load them in code, never by the model's choice.
- Validate every triage record, retry once with the problems listed, then fall back to manual triage.
- Count model calls in code and stop a run at the budget.
- Build an approval queue with decide(), an outbox stand-in and an idempotent return, and prove with tests that nothing leaves without a named person.
Before you start
- The previous lesson, Implement the Agent and Its Tool Integrations. You need its project folder, because this lab changes some of those files and adds new ones.
- The ideas in Memory Retention, Privacy and Data Lifecycle, Output Validation and Policy Enforcement, Human Review for High-Impact Actions and Budget Limits, Rate Limits and Runaway Execution Controls. This lab applies them, so it does not teach them again at length.
- Python 3.10 or later and the packages from the earlier labs. The tests need no API key and no internet.
What you will build: a triage desk with a memory and a human gate
In the last lesson your agent could read a ticket, call tools and produce a triage record. It had no memory of earlier cases, nobody checked its answers and a return request only sat in a list. Now you add the controls that make it safe to put in front of staff.
- Ticket in
Code reads the customer's own case history and adds short lines to the model input (R6)
- Agent loop
Tool calls, at most 6 model calls in total (N2)
- check_triage
Shape, sources, personal data, refund promises, other people's orders (R7, N3)
- Retry once
The problems go back to the model. Still bad: manual triage with no draft (R7)
- Approval queue
Every draft and every proposed return waits here (R5)
- Reviewer decides
A named person approves or rejects. Only an approved reply reaches the outbox (R5)
Code does every box except the agent loop. The model never reads a history file, never sends anything and never decides who may approve.
- Pseudonymous key
- A made-up code that stands in for a real identity. Here the code is made from the customer's email, so the history file holds no email addresses.
- Retention
- How long data is kept. Here, case records live for 90 days and are then deleted.
- Validation
- Checking an answer against fixed rules in code before anything uses it. The model's answer is a proposal until it passes.
- Approval queue
- A list of actions that wait for a person's decision. The agent can add to it. Only a named reviewer can empty it.
- Outbox
- The place where approved replies are written. In this lab it is a plain file, a stand-in for a real email system. Nothing is really sent.
- Idempotent
- Safe to do twice. If a return is recorded twice, the result is the same as recording it once.
What you will hand in
- Your code:
memory.py,seed_history.py,validate.py,approvals.py,review.py, the changedtools.py,agent.py,versions.pyandfakes.py, and the test files. - The output of your offline tests, all PASS, and of the fake-model run with the reviewer walk-through.
- A short note,
memory-and-approval-notes.md, with your retention period, what your history file may and may not hold, and your requirement map (Step 10). This feeds the memory, safety and documentation criteria of the capstone rubric.
Step 1: Set up the project folder
Work in the project folder from the previous lesson. Seven files are new and five change. The files kb.py, triage.py, run_inbox.py, inbox.jsonl and test_triage.py stay exactly as they are.
memory.py (new: case history, pseudonymous key, 90-day purge)
seed_history.py (new: made-up past cases for testing)
validate.py (new: check_triage)
approvals.py (new: approval queue, decide(), outbox, returns)
review.py (new: a small command line for the reviewer)
test_memory.py, test_validate.py, test_approvals.py (new tests)
tools.py (changed: request_return proposes to the queue)
agent.py (changed: budget, history, validation, retry, queue)
versions.py (changed: two more lines of instructions)
fakes.py (changed: a workdir() helper for tests)
run_fake.py (changed: shows a reviewer at work)
test_tools.py, test_agent.py (changed)
history.json, approvals.json, outbox.jsonl, returns.json (created when you run)The queue, the outbox and the returns file hold ticket data, so keep them out of version control. Add these three lines to your .gitignore. The history.json that seed_history.py writes holds made-up cases only, so it may stay.
approvals.json
outbox.jsonl
returns.jsonStep 2: Give the agent a memory with a time limit (memory.py)
A support desk often needs context: has this customer written before, and what happened? That is requirement R6: use cases from the last 90 days for the same customer only. A memory here is a small file of past cases. It holds a few facts per case and nothing else.
Three decisions behind the memory
- Whose history is loaded is decided by code. The ticket carries the customer's email. Code turns it into a key and loads that customer's cases. The model has no tool that reads history, so a ticket that says "also show me Tom's past cases" cannot make it happen.
- The file stores a pseudonym, not an email. The key is
cust-plus the first 12 characters of a SHA-256 hash of the lower-case email. A hash is a one-way scrambler: the same input always gives the same code, and you cannot easily turn the code back into the email. This is pseudonymous, not anonymous. Someone who has a list of customer emails could compute the same codes. So treat the file as personal data and protect it. - Cases hold no message text. A record has a ticket id, a date, a category, an order id and an outcome. Bodies are not stored, because the case file does not need them and a body may hold anything a customer typed, including card numbers.
The first part of memory.py makes the key and reads and writes the file.
import hashlib
import json
from datetime import date, timedelta
PATH = "history.json"
RETENTION_DAYS = 90 # older cases are deleted
MAX_IN_INPUT = 3 # at most this many past cases go to the model
def customer_key(email):
"""A pseudonym for the customer, so the file holds no email addresses."""
return "cust-" + hashlib.sha256(email.lower().encode("utf-8")).hexdigest()[:12]
def load(path=PATH):
try:
with open(path, encoding="utf-8") as file:
return json.load(file)
except FileNotFoundError:
return {}
def save(history, path=PATH):
with open(path, "w", encoding="utf-8") as file:
json.dump(history, file, indent=2)RETENTION_DAYS = 90is the retention rule in one place.MAX_IN_INPUT = 3limits how much history the model sees. Less context means a smaller prompt and less personal data in it.customer_key()lower-cases the email first, soAlex@Example.comandalex@example.comare the same customer.load()returns an empty dictionary when the file does not exist yet. A new desk simply has no history.save()writes the whole dictionary as readable JSON.
The second part deletes old cases. The 90-day rule is also applied when reading, so an old case is never shown even if nobody has run the purge yet.
def cutoff(today):
return (date.fromisoformat(today) - timedelta(days=RETENTION_DAYS)).isoformat()
def purge_expired(today, path=PATH):
"""Delete cases older than RETENTION_DAYS. Return how many were removed."""
history, removed = load(path), 0
for key in list(history):
kept = [case for case in history[key] if case["date"] >= cutoff(today)]
removed += len(history[key]) - len(kept)
if kept:
history[key] = kept
else:
del history[key]
save(history, path)
return removedcutoff(today)gives the oldest date that may stay. A date inYYYY-MM-DDform compares correctly as plain text, socase["date"] >= cutoff(today)keeps exactly the cases that are 90 days old or newer.purge_expired(today)goes through every customer, keeps the fresh cases, drops a customer entirely when nothing is left and returns how many cases it removed. It takestodayas an argument, so tests can use a fixed date.
def recent_cases(email, today, path=PATH):
"""The newest cases of THIS customer only, even if the purge has not run yet."""
cases = load(path).get(customer_key(email), [])
fresh = [case for case in cases if case["date"] >= cutoff(today)]
return sorted(fresh, key=lambda case: case["date"], reverse=True)[:MAX_IN_INPUT]
def history_lines(email, today, path=PATH):
"""Short text lines for the model input. They hold no message text and no email."""
return [f"{case['date']} {case['category']}, order {case['order_id'] or 'none'}, {case['outcome']}"
for case in recent_cases(email, today, path)]recent_cases()looks up the key of this email only, drops expired cases and returns the newest three.history_lines()turns each case into one short line such as2026-11-12 complaint, order none, waiting. These lines are all the model ever sees of the past.
Now the made-up data. It matches the sample history of the worked example: Alex has two complaints, and Tom has one old case that is past the 90 days on 2026-11-18.
import memory
# Made-up past cases. The email is turned into a pseudonym before anything is saved.
SAMPLE = {
"alex@example.com": [
{"ticket_id": "T-1987", "date": "2026-10-02", "category": "complaint", "order_id": None, "outcome": "resolved"},
{"ticket_id": "T-1995", "date": "2026-11-12", "category": "complaint", "order_id": None, "outcome": "waiting"},
],
"tom@example.com": [
{"ticket_id": "T-1950", "date": "2026-07-01", "category": "product_question", "order_id": None, "outcome": "resolved"},
],
}
def seed():
memory.save({memory.customer_key(email): cases for email, cases in SAMPLE.items()})
if __name__ == "__main__":
seed()
print("wrote", memory.PATH)SAMPLEis keyed by email only here, in the seed script.seed()converts each email to a pseudonym before saving, so even this made-up file contains no email address.- Run
python seed_history.pyonce. It writeshistory.json.
Step 3: Check every triage record before it goes on (validate.py)
The model's answer is a proposal. Requirement R7 says that when automatic triage fails validation twice, a person takes the ticket without a draft. First we need the checker. Think of a proofreader with a checklist: the proofreader does not rewrite the letter, only says what is wrong.
check_triage(record, retrieved_ids, ticket) returns a list of problems. An empty list means the record may go on.
import re
import kb
import tools
import triage
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")
CARD = re.compile(r"\b(?:\d[ -]?){15}\d\b") # 16 digits, with or without spaces or dashes
ORDER_ID = re.compile(r"QF-\d{4}")
# A weak, partial signal: it catches common wordings and misses reworded promises.
REFUND_PROMISES = [
re.compile(r"\bfull refund\b", re.I),
re.compile(r"\brefund (?:is|has been|will be) (?:approved|issued|processed)\b", re.I),
re.compile(r"\b(?:we|i)(?:'ll| will) refund\b", re.I),
re.compile(r"\bmoney back\b", re.I),
]
def customer_page_ids():
return {page["id"] for page in kb.KB if page["audience"] == "customer"}EMAILandCARDare the same patterns as the redaction rule of the earlier lessons. A pattern (regular expression) describes text such as "letters, an @ sign, a domain".CARDlooks for 16 digits, with or without spaces or dashes.ORDER_IDfinds order numbers likeQF-1042inside a draft.REFUND_PROMISESis a short list of wordings that sound like a promise of money. It is a weak, partial signal: it catches common phrases and misses a reworded promise such as "we will put the money back on your card". That is why the approval step still exists.customer_page_ids()returns the ids of customer help pages. Staff pages never appear in it.
def check_triage(record, retrieved_ids, ticket):
"""Return a list of problems. An empty list means the record may go on."""
problems = triage.schema_problems(record)
if problems:
return problems # the other checks need a record of the right shape
sources = set(record["sources"])
for source in sorted(sources - retrieved_ids):
problems.append(f"source {source} was not retrieved in this run")
for source in sorted(sources - customer_page_ids()):
problems.append(f"source {source} is not a customer help page")
for field in ("draft_reply", "summary"):
if EMAIL.search(record[field]):
problems.append(f"{field} contains an email address")
if CARD.search(record[field]):
problems.append(f"{field} contains a card-like number")
if any(pattern.search(record["draft_reply"]) for pattern in REFUND_PROMISES):
problems.append("draft_reply promises a refund")
mentioned = set(ORDER_ID.findall(record["draft_reply"])) | ({record["order_id"]} - {None})
if any(tools.own_order(order_id, ticket["customer_email"]) is None for order_id in mentioned):
problems.append("the reply mentions an order that is not this customer's")
return problems- The first check is the shape and the allowed values, using
triage.schema_problems()from the last lesson. If the shape is wrong, the function stops there, because the other checks need the right fields. - Sources must be ids that the agent really retrieved in this run, and they must be customer pages. So the model cannot cite a page it never read, and a staff page can never be cited, even if something leaked it.
- Both
draft_replyandsummaryare scanned for email addresses and card-like numbers (N3). - The draft is scanned for refund promises. A promise of money is something only staff may give.
- Every order id in the draft or in
order_idmust belong to the ticket's own customer.tools.own_order()is the same owner check the tools use, so one rule is applied in two places.
Step 4: Build the approval queue and the outbox (approvals.py, review.py)
Requirement R5 says: never send a reply or create a return without a named person's approval. The simplest way to keep that promise is to give the agent no way to do either. The agent can only propose. A proposal becomes an item in a queue. A person decides. Only an approved decision does the real action.
A queue item looks like this:
{"approval_id": "A-0002", "ticket_id": "T-2002", "action": "create_return",
"payload": {"order_id": "QF-1044", "reason": "wrong_size"},
"status": "pending", "reviewer": null, "note": null}import json
import threading
PATH = "approvals.json"
OUTBOX = "outbox.jsonl" # a stand-in for a real email system: nothing is really sent
RETURNS = "returns.json"
LOCK = threading.Lock() # one change at a time, even when several requests arrive together
class NotFound(ValueError):
pass
class AlreadyDecided(ValueError):
pass
def load(path=PATH):
try:
with open(path, encoding="utf-8") as file:
return json.load(file)
except FileNotFoundError:
return []
def save(items, path=PATH):
with open(path, "w", encoding="utf-8") as file:
json.dump(items, file, indent=2)OUTBOXis the stand-in for an email system. It is a text file with one JSON line per approved reply. Nothing is really sent.LOCKmakes sure only one change to the queue happens at a time. Without it, two requests that arrive together could both read the same list and one change would be lost.NotFoundandAlreadyDecidedare two named kinds of error, so callers and tests can tell the cases apart. Both are kinds ofValueError.
def propose(action, ticket_id, payload):
"""Put an action in the queue. It waits there until a person decides."""
with LOCK:
items = load()
if action == "create_return": # the same return is never queued twice
for item in items:
if item["action"] == action and item["payload"] == payload and item["status"] != "rejected":
return item["approval_id"]
approval_id = f"A-{len(items) + 1:04d}"
items.append({"approval_id": approval_id, "ticket_id": ticket_id, "action": action,
"payload": payload, "status": "pending", "reviewer": None, "note": None})
save(items)
return approval_id
def pending():
return [item for item in load() if item["status"] == "pending"]propose()adds an item with the statuspending, no reviewer and no note. The id comes from the list length, for exampleA-0001.- For
create_return, it first looks for the same return that is already waiting or approved and gives back that id. So a model that callsrequest_returntwice does not fill the queue with copies. pending()returns only the items that still wait for a decision.
def record_return(payload):
"""Create the return record. Doing it twice for the same return changes nothing."""
returns = {}
try:
with open(RETURNS, encoding="utf-8") as file:
returns = json.load(file)
except FileNotFoundError:
pass
returns[f"{payload['order_id']}:{payload['reason']}"] = payload
with open(RETURNS, "w", encoding="utf-8") as file:
json.dump(returns, file, indent=2)
def write_outbox(item, reviewer):
line = {"approval_id": item["approval_id"], "ticket_id": item["ticket_id"],
"reply": item["payload"]["draft_reply"], "approved_by": reviewer}
with open(OUTBOX, "a", encoding="utf-8") as file:
file.write(json.dumps(line) + "\n")record_return()stores the return under the keyorder:reason. Storing the same return again writes the same key with the same value, so nothing changes. That is what idempotent means here.write_outbox()adds one line with the approval id, the ticket id, the reply text and the name of the person who approved it.
def decide(approval_id, decision, reviewer, note=None):
if decision not in ("approve", "reject"):
raise ValueError("decision must be approve or reject")
if not isinstance(reviewer, str) or not reviewer.strip():
raise ValueError("a reviewer name is required")
with LOCK:
items = load()
item = next((i for i in items if i["approval_id"] == approval_id), None)
if item is None:
raise NotFound(f"no approval {approval_id}")
if item["status"] != "pending":
raise AlreadyDecided(f"{approval_id} was already {item['status']}")
if decision == "approve":
if item["action"] == "send_reply":
write_outbox(item, reviewer.strip())
else:
record_return(item["payload"])
item.update(status="approved" if decision == "approve" else "rejected",
reviewer=reviewer.strip(), note=note)
save(items)
return itemdecide()is the only door to the outbox and to the returns file. It first checks the decision word and that the reviewer name is real text, not empty or spaces.- It then finds the item. An unknown id raises
NotFound. An item that is notpendingraisesAlreadyDecided, so an item can be decided only once. - Approving a
send_replyitem writes one outbox line. Approving acreate_returnitem records the return. Rejecting does neither. - Only at the end does it save the new status, the trimmed reviewer name and the note. The whole function runs under the lock.
A reviewer needs a way to use this. review.py is a tiny command line. Run python review.py to list what waits. Run python review.py A-0001 approve Dana "Looks right" to decide.
import sys
import approvals
def show_pending():
items = approvals.pending()
for item in items:
print(f"{item['approval_id']} {item['ticket_id']} {item['action']:<13} {item['payload']}")
print(f"{len(items)} waiting")
if __name__ == "__main__":
if len(sys.argv) == 1:
show_pending()
else: # python review.py A-0001 approve Dana "optional note"
approval_id, decision, reviewer, *note = sys.argv[1:]
item = approvals.decide(approval_id, decision, reviewer, " ".join(note) or None)
print(item["approval_id"], item["status"], "by", item["reviewer"])- With no extra words, it prints every pending item and how many are waiting.
- With words, it takes the approval id, the decision, the reviewer name and an optional note, and calls
decide(). A refused decision, such as an empty name or a second decision on the same item, ends with an error message that names the reason. That is on purpose: a refusal should be loud.
Step 5: Change request_return and the instructions (tools.py, versions.py)
In the last lesson, request_return stored a pending dictionary. Now it proposes a create_return item to the queue. Three edits in tools.py do this, and the tools learn which ticket they work for. The ticket id comes from code, like the customer's email, and the model never supplies it.
Edit 1: the top of tools.py
Replace the first lines of the file with these. Then delete the line PENDING = {} in Part A, because the queue replaces it.
import re
import approvals
import kbEdit 2: the three tool functions in Part B
Replace everything from the Part B comment down to the end of search_help with this version. own_order() is unchanged.
# --- Part B: what each tool does. The customer and ticket come from code, never from the model ---
def own_order(order_id, customer_email):
"""Return the order only if it belongs to this customer, otherwise None."""
order = ORDERS.get(order_id)
if order and order["owner"] == customer_email.lower():
return order
return None
def lookup_order(order_id, customer_email, ticket_id):
order = own_order(order_id, customer_email)
if order is None:
return {"error": "order not found"} # the same answer whether the order exists or not
return {"order_id": order_id, "status": order["status"], "estimated_delivery": order["estimated_delivery"]}
def request_return(order_id, reason, customer_email, ticket_id):
order = own_order(order_id, customer_email)
if order is None:
return {"error": "order not found"}
if order["status"] != "delivered":
return {"error": "only delivered orders can be returned"}
approval_id = approvals.propose("create_return", ticket_id, {"order_id": order_id, "reason": reason})
return {"return_request": "waiting for staff approval", "approval_id": approval_id}
def search_help(query, customer_email, ticket_id):
return kb.search_help(query) # customer pages only; the email and ticket are not needed here- All three functions now take
ticket_id. Onlyrequest_returnuses it. The others accept it so that one gate can call every tool in the same way. request_return()still checks the owner and the delivered status in code. Then, instead of storing anything, it callsapprovals.propose()and gives the model a plain answer: waiting for staff approval, and the approval id.- A return for someone else's order still says
order not found, and nothing is queued. The test later proves it.
Edit 3: the gate in Part C
Replace run_tool at the end of the file. The TOOLS table above it does not change.
def run_tool(name, args, customer_email, ticket_id=None):
if name not in TOOLS:
return {"error": f"unknown tool {name}"}
function, allowed = TOOLS[name]
if set(args) != allowed:
return {"error": f"arguments must be exactly {sorted(allowed)}"}
if "order_id" in args and not re.fullmatch(r"QF-\d{4}", str(args["order_id"])):
return {"error": "order_id must look like QF-1234"}
if "query" in args and not (isinstance(args["query"], str) and 0 < len(args["query"]) <= 200):
return {"error": "query must be text of 1 to 200 characters"}
if name == "request_return" and args["reason"] not in REASONS:
return {"error": f"reason must be one of {REASONS}"}
return function(customer_email=customer_email, ticket_id=ticket_id, **args)run_toolhas one new parameter,ticket_id, with the defaultNone, so older calls still work.- The last line passes both the customer and the ticket from code. The arguments from the model are checked first, as before.
Edit 4: two lines in the instructions
In versions.py, add the two lines that start with HISTORY: and If you are told after the If a tool says line. The first tells the model that history is background only. The second prepares it for the retry message.
If a tool says "order not found", ask the customer to check the number. Do not say more.
HISTORY: Earlier cases of this customer may be listed. They are background only.
If you are told your reply had problems, answer again with one corrected JSON object.Step 6: Rebuild the agent loop with a budget, a retry and the queue (agent.py)
agent.py changes the most. Replace the whole file with the five parts below, in this order. The function tool_result is the same as before. The tool loop moves out of triage_ticket into its own function, so that the retry can reuse it.
What a budget is. A model call costs time and money, and an agent in a loop can call a model again and again. The budget is a counter kept in code. When it reaches 6, the next call is refused (N2). The model has no say.
import json
import approvals
import memory
import tools
import triage
import validate
import versions
MAX_ROUNDS = 4 # tool rounds in one answer
MAX_MODEL_CALLS_PER_RUN = 6 # all model calls for one ticket, retry included
MAX_BODY_CHARS = 1500 # a longer message is cut
class Stop(Exception):
"""The run cannot go on, so a person must take the ticket."""
class Budget:
def __init__(self):
self.calls = 0
def use(self):
if self.calls >= MAX_MODEL_CALLS_PER_RUN:
raise Stop("model call budget used up")
self.calls += 1MAX_ROUNDSlimits the tool rounds in one answer.MAX_MODEL_CALLS_PER_RUNlimits all model calls for one ticket, including the retry. Two limits guard against two different loops.Stopis a named exception that means "a person must take this ticket".Budgetcounts.use()raisesStopif the budget is used up, otherwise it adds one. It is called before every model call, so the seventh call never happens.
def ticket_text(ticket):
"""What the model sees. Code adds this customer's recent cases. The email address is left out."""
body = ticket["body"][:MAX_BODY_CHARS]
text = (f"Ticket {ticket['ticket_id']}\nReceived: {ticket['received']}\n"
f"Subject: {ticket['subject']}\nMessage: {body}")
lines = memory.history_lines(ticket["customer_email"], ticket["received"][:10])
if lines:
text += "\nEarlier cases of this customer:\n" + "\n".join("- " + line for line in lines)
return text
def send(client, version, budget, input_data, previous_id=None):
budget.use()
settings = versions.VERSIONS[version]
extra = {"previous_interaction_id": previous_id} if previous_id else {}
return client.interactions.create(
model=settings["model"], input=input_data, system_instruction=settings["instructions"],
tools=tools.CONTRACTS, **extra
)ticket_text()builds the input from the ticket fields. The customer's email is not in it. The date used for the history is the date the ticket was received, cut from thereceivedfield.- Code asks
memory.history_lines()for this customer's lines. If there are any, they are added under a heading. If not, the heading is left out. send()counts the call first, then calls the model as in the last lesson. It now needs thebudgetargument.
def tool_result(call, result):
return {"type": "function_result", "name": call.name, "call_id": call.id,
"result": [{"type": "text", "text": json.dumps(result)}]}
def follow_tools(client, version, budget, interaction, ticket, retrieved):
"""Run the model's tool calls until it gives a final answer."""
for _ in range(MAX_ROUNDS):
calls = [step for step in interaction.steps if step.type == "function_call"]
if not calls:
return interaction
outputs = []
for call in calls:
result = tools.run_tool(call.name, dict(call.arguments), ticket["customer_email"], ticket["ticket_id"])
retrieved.update(passage["id"] for passage in result.get("results", []))
outputs.append(tool_result(call, result))
interaction = send(client, version, budget, outputs, interaction.id)
raise Stop("too many tool rounds")tool_result()is unchanged. It wraps a result in the shape the model expects.follow_tools()runs the model's tool calls and sends the results back, round after round, until the model gives a final answer. AfterMAX_ROUNDSrounds it raisesStop.retrievedcollects the ids of every help page thatsearch_helpreturned in this run. Validation uses it to check the sources.- The customer email and the ticket id are passed from the ticket, not from the model's arguments.
def read_reply(text, retrieved, ticket):
try:
data = triage.parse_model_json(text)
except ValueError as error:
return None, [str(error)]
return data, validate.check_triage(data, retrieved, ticket)
def retry_message(problems):
return "Your reply had these problems: " + "; ".join(problems) + ". Reply again with one corrected JSON object."
def finish(data, ticket, version, run_id):
"""The draft is never sent. It goes into the approval queue."""
record = triage.build_record(data, ticket, version, run_id)
approvals.propose("send_reply", ticket["ticket_id"], {"draft_reply": record["draft_reply"]})
return recordread_reply()parses the model's text and validates it. A text that is not JSON counts as one problem.retry_message()turns the list of problems into one plain sentence for the model.finish()builds the stored record and puts the draft in the queue as asend_replyitem. The draft is never sent here.
def triage_ticket(ticket, client, version="v1", run_id="R-0001"):
budget, retrieved = Budget(), set()
try:
interaction = send(client, version, budget, ticket_text(ticket))
for attempt in (1, 2): # the first answer, then one retry
interaction = follow_tools(client, version, budget, interaction, ticket, retrieved)
data, problems = read_reply(interaction.output_text, retrieved, ticket)
if not problems:
return finish(data, ticket, version, run_id)
if attempt == 1:
interaction = send(client, version, budget, retry_message(problems), interaction.id)
reason = f"validation failed twice: {problems[0]}"
except Stop as stop:
reason = str(stop)
except Exception as error: # any model or network failure: a person takes over
reason = f"model error ({type(error).__name__})"
return triage.manual_record(ticket, reason, version, run_id)- The
for attempt in (1, 2)loop is the whole retry rule: the first answer, then at most one retry. A retry continues the same conversation, so the model sees its own earlier answer and the problems. - If the second answer still has problems, the loop ends and the reason names the first problem.
Stopand any other failure (a network error, for example) both end inmanual_record(): category other, urgency normal, no draft, support team. That is R7.- Safety tickets keep their rule from the last lesson: code forces urgency high and the safety team.
Step 7: Test every rule offline with a fake model
The fake model is the scripted one from the last lesson. This lab adds one helper to fakes.py: workdir(). It makes an empty temporary folder, moves into it, and optionally seeds the history. Because the files use relative names, the tests write their queue and outbox there and your real files stay untouched.
Replace the top of fakes.py, everything above def reply, with this. The scripts and the FakeModel class below it stay as they are.
import contextlib
import itertools
import json
import os
import tempfile
from types import SimpleNamespace as NS
import seed_history
def check(name, passed):
print("PASS" if passed else "FAIL", "-", name)
@contextlib.contextmanager
def workdir(seed=False):
"""Run inside an empty temporary folder, so tests never touch real files. The files use relative names."""
before = os.getcwd()
with tempfile.TemporaryDirectory() as folder:
os.chdir(folder)
try:
if seed:
seed_history.seed()
yield folder
finally:
os.chdir(before)check(name, passed)prints one PASS or FAIL line. It is the only test tool we use.workdir()is a context manager.with workdir(seed=True):runs the indented lines inside a fresh temporary folder, with the sample history already in it, and always returns to the old folder afterwards, even if a test fails.
Test the memory
import memory
from fakes import check, workdir
TODAY = "2026-11-18" # a fixed date, so the tests give the same answer every day
key = memory.customer_key("Alex@Example.com")
check("the key is cust- plus 12 hex characters", key.startswith("cust-") and len(key) == 17)
check("the key ignores upper and lower case", key == memory.customer_key("alex@example.com"))
check("different customers get different keys", key != memory.customer_key("tom@example.com"))
with workdir(seed=True):
with open(memory.PATH, encoding="utf-8") as file:
text = file.read()
check("the history file holds no email address and no message text", "@" not in text and "body" not in text)
lines = memory.history_lines("alex@example.com", TODAY)
check("alex gets 2 short lines, newest first", lines == ["2026-11-12 complaint, order none, waiting",
"2026-10-02 complaint, order none, resolved"])
check("tom's old case is too old to load, even before the purge", memory.history_lines("tom@example.com", TODAY) == [])
check("a customer without history gets no lines", memory.history_lines("kim@example.com", TODAY) == [])
check("alex's cases never appear for tom", all("T-1987" not in str(memory.recent_cases(e, TODAY)) for e in ["tom@example.com", "maya@example.com"]))
check("purge removes only the expired case", memory.purge_expired(TODAY) == 1)
check("tom's key is gone, alex's two cases are kept", memory.customer_key("tom@example.com") not in memory.load() and len(memory.load()[key]) == 2)
check("a second purge removes nothing", memory.purge_expired(TODAY) == 0)
memory.save({key: [{"ticket_id": "T-1", "date": "2026-08-20", "category": "order", "order_id": None, "outcome": "resolved"},
{"ticket_id": "T-2", "date": "2026-08-19", "category": "order", "order_id": None, "outcome": "resolved"}]})
check("exactly 90 days old is kept, 91 days is removed", memory.purge_expired(TODAY) == 1 and memory.load()[key][0]["ticket_id"] == "T-1")
many = [{"ticket_id": f"T-{n}", "date": f"2026-11-{n:02d}", "category": "order", "order_id": "QF-1042", "outcome": "resolved"} for n in range(1, 7)]
memory.save({key: many})
check("at most 3 cases go to the model, the newest ones", [c["ticket_id"] for c in memory.recent_cases("alex@example.com", TODAY)] == ["T-6", "T-5", "T-4"])
check("a missing file means no history", memory.load("nothing.json") == {})- The fixed date
2026-11-18makes the tests give the same answer every day. - Some tests look at the privacy rules: the key format, the file has no
@and no message text, Alex's cases never appear for Tom or Maya, and Tom's old case is not loaded even before the purge. - The boundary test is the important one: a case exactly 90 days old is kept, and a case 91 days old is removed.
PASS - the key is cust- plus 12 hex characters
PASS - the key ignores upper and lower case
PASS - different customers get different keys
PASS - the history file holds no email address and no message text
PASS - alex gets 2 short lines, newest first
PASS - tom's old case is too old to load, even before the purge
PASS - a customer without history gets no lines
PASS - alex's cases never appear for tom
PASS - purge removes only the expired case
PASS - tom's key is gone, alex's two cases are kept
PASS - a second purge removes nothing
PASS - exactly 90 days old is kept, 91 days is removed
PASS - at most 3 cases go to the model, the newest ones
PASS - a missing file means no historyTest the validation
import json
import validate
from fakes import check, reply
MAYA = {"ticket_id": "T-2001", "customer_email": "maya@example.com", "subject": "s", "body": "b", "received": "2026-11-18T09:12"}
GOOD = json.loads(reply("order", "normal", "QF-1042", ["KB-02"], None, "Asks about an order.",
"Your order QF-1042 was dispatched (KB-02)."))
RETRIEVED = {"KB-02", "KB-15"}
def problems(**changes):
return validate.check_triage({**GOOD, **changes}, RETRIEVED, MAYA)
check("a clean record has no problems", problems() == [])
check("a schema problem is reported first", problems(category="billing") != [] and "category" in problems(category="billing")[0])
check("a source that was never retrieved is caught", problems(sources=["KB-06"]) == ["source KB-06 was not retrieved in this run"])
check("a staff page is caught even if it was retrieved", "source KB-15 is not a customer help page" in problems(sources=["KB-15"]))
check("an email address in the draft is caught", "draft_reply contains an email address" in problems(draft_reply="Write to tom@example.com"))
check("a card-like number in the draft is caught", "draft_reply contains a card-like number" in problems(draft_reply="Card 4111 1111 1111 1111 was used"))
check("an email address in the summary is caught", "summary contains an email address" in problems(summary="Customer maya@example.com asks"))
for text in ["We will refund you today.", "A full refund is on its way.", "Your refund has been approved.", "You will get your money back."]:
check(f"refund promise caught: {text}", "draft_reply promises a refund" in problems(draft_reply=text))
check("saying no refund can be promised is allowed", problems(draft_reply="Staff decide on refunds after they review a return.") == [])
check("another customer's order in the draft is caught", "the reply mentions an order that is not this customer's" in problems(draft_reply="Order QF-1044 was delivered."))
check("another customer's order in order_id is caught", problems(order_id="QF-1044", draft_reply="Please check the number.") != [])
check("an order that does not exist is caught too", problems(draft_reply="Order QF-9999 is late.") != [])
check("no order mentioned is fine", problems(order_id=None, sources=[], draft_reply="Please send your order number.") == [])
check("a reply that is not a dict is caught", validate.check_triage("nope", set(), MAYA) == ["reply is not a JSON object"])problems(**changes)starts from a good record and changes one field, so each test shows one thing going wrong.- The loop tests four ways to promise a refund. One more test checks that a sentence that only says staff decide on refunds is allowed.
- The tests for another customer's order and for an order that does not exist both expect a problem. The owner check does not tell them apart.
PASS - a clean record has no problems
PASS - a schema problem is reported first
PASS - a source that was never retrieved is caught
PASS - a staff page is caught even if it was retrieved
PASS - an email address in the draft is caught
PASS - a card-like number in the draft is caught
PASS - an email address in the summary is caught
PASS - refund promise caught: We will refund you today.
PASS - refund promise caught: A full refund is on its way.
PASS - refund promise caught: Your refund has been approved.
PASS - refund promise caught: You will get your money back.
PASS - saying no refund can be promised is allowed
PASS - another customer's order in the draft is caught
PASS - another customer's order in order_id is caught
PASS - an order that does not exist is caught too
PASS - no order mentioned is fine
PASS - a reply that is not a dict is caughtTest the approval queue
import json
import os
import approvals
from fakes import check, workdir
def outbox_lines():
if not os.path.exists(approvals.OUTBOX):
return []
with open(approvals.OUTBOX, encoding="utf-8") as file:
return [json.loads(line) for line in file]
def refused(function, *args, **kwargs):
try:
function(*args, **kwargs)
except ValueError as error:
return type(error).__name__
return Noneoutbox_lines()reads the outbox, or gives an empty list if the file does not exist.refused()calls a function and returns the name of the error it raised, orNone.
with workdir():
reply_id = approvals.propose("send_reply", "T-2001", {"draft_reply": "It was dispatched (KB-02)."})
return_id = approvals.propose("create_return", "T-2002", {"order_id": "QF-1044", "reason": "wrong_size"})
check("items get ids A-0001, A-0002", (reply_id, return_id) == ("A-0001", "A-0002"))
item = approvals.load()[0]
check("a new item is pending, with no reviewer and no note", (item["status"], item["reviewer"], item["note"]) == ("pending", None, None))
check("nothing is in the outbox before approval", outbox_lines() == [])
check("proposing the same return again gives the same id", approvals.propose("create_return", "T-2002", {"order_id": "QF-1044", "reason": "wrong_size"}) == return_id)
check("an empty reviewer name is refused", refused(approvals.decide, "A-0001", "approve", " ") == "ValueError")
check("a missing reviewer name is refused", refused(approvals.decide, "A-0001", "approve", None) == "ValueError")
check("a decision other than approve or reject is refused", refused(approvals.decide, "A-0001", "maybe", "Dana") == "ValueError")
check("an unknown approval id is refused", refused(approvals.decide, "A-0099", "approve", "Dana") == "NotFound")
check("refused decisions changed nothing", outbox_lines() == [] and approvals.load()[0]["status"] == "pending")
done = approvals.decide("A-0001", "approve", "Dana", "Looks right.")
check("approve marks the item with reviewer and note", (done["status"], done["reviewer"], done["note"]) == ("approved", "Dana", "Looks right."))
check("approving a reply writes exactly one outbox line", outbox_lines() == [{"approval_id": "A-0001", "ticket_id": "T-2001", "reply": "It was dispatched (KB-02).", "approved_by": "Dana"}])
check("an item can be decided only once", refused(approvals.decide, "A-0001", "approve", "Sam") == "AlreadyDecided")
check("rejecting a decided item is refused too", refused(approvals.decide, "A-0001", "reject", "Sam") == "AlreadyDecided")
check("the outbox still has one line", len(outbox_lines()) == 1)check("a pending return has no return record yet", not os.path.exists(approvals.RETURNS))
approvals.decide("A-0002", "approve", "Dana")
with open(approvals.RETURNS, encoding="utf-8") as file:
check("approving a return creates one record", list(json.load(file)) == ["QF-1044:wrong_size"])
approvals.record_return({"order_id": "QF-1044", "reason": "wrong_size"})
with open(approvals.RETURNS, encoding="utf-8") as file:
check("recording the same return again changes nothing", len(json.load(file)) == 1)
check("approving a return writes nothing to the outbox", len(outbox_lines()) == 1)
third = approvals.propose("send_reply", "T-2003", {"draft_reply": "Size M (KB-06)."})
rejected = approvals.decide(third, "reject", "Dana", "Too short.")
check("reject keeps the item with its note", (rejected["status"], rejected["note"]) == ("rejected", "Too short."))
check("a rejected reply never reaches the outbox", len(outbox_lines()) == 1)
check("pending() lists only items waiting for a decision", approvals.pending() == [])- The tests that must fail come first: an empty name, a missing name, a decision word that is not allowed and an unknown id. After them, one test checks that nothing changed.
- After the first approval, the outbox has exactly one line. A second decision on the same item, approve or reject, is refused with
AlreadyDecided. - A return has no record before approval. After approval it has one, a second
record_return()changes nothing, and the outbox is still the same. - A rejected reply never reaches the outbox. That is the R5 test.
PASS - items get ids A-0001, A-0002
PASS - a new item is pending, with no reviewer and no note
PASS - nothing is in the outbox before approval
PASS - proposing the same return again gives the same id
PASS - an empty reviewer name is refused
PASS - a missing reviewer name is refused
PASS - a decision other than approve or reject is refused
PASS - an unknown approval id is refused
PASS - refused decisions changed nothing
PASS - approve marks the item with reviewer and note
PASS - approving a reply writes exactly one outbox line
PASS - an item can be decided only once
PASS - rejecting a decided item is refused too
PASS - the outbox still has one line
PASS - a pending return has no return record yet
PASS - approving a return creates one record
PASS - recording the same return again changes nothing
PASS - approving a return writes nothing to the outbox
PASS - reject keeps the item with its note
PASS - a rejected reply never reaches the outbox
PASS - pending() lists only items waiting for a decisionUpdate the tool tests
In test_tools.py, replace the import lines at the top with these:
import os
import approvals
import tools
from fakes import check, workdirThen replace the checks at the end of the file, from the undelivered order check down, with this block:
with workdir():
check("undelivered order cannot be returned", "error" in tools.run_tool("request_return", {"order_id": "QF-1042", "reason": "damaged"}, MAYA))
check("only the owner can request a return", tools.run_tool("request_return", {"order_id": "QF-1044", "reason": "damaged"}, MAYA) == {"error": "order not found"})
check("nothing was queued by the refused requests", approvals.load() == [])
first = tools.run_tool("request_return", {"order_id": "QF-1044", "reason": "damaged"}, TOM, "T-2002")
item = approvals.load()[0]
check("the owner's return becomes a pending approval item", first["approval_id"] == "A-0001" and (item["action"], item["status"], item["ticket_id"]) == ("create_return", "pending", "T-2002"))
check("no return record exists before approval", not os.path.exists(approvals.RETURNS))
again = tools.run_tool("request_return", {"order_id": "QF-1044", "reason": "damaged"}, TOM, "T-2002")
check("a repeated request is not queued twice", again["approval_id"] == "A-0001" and len(approvals.load()) == 1)PASS - owner sees the order status
PASS - email case does not matter
PASS - another customer's order looks like an unknown order
PASS - badly formed order id is rejected
PASS - unknown tool is refused
PASS - extra argument is rejected
PASS - missing argument is rejected
PASS - reason outside the list is rejected
PASS - help search returns customer pages only
PASS - empty search text is rejected
PASS - undelivered order cannot be returned
PASS - only the owner can request a return
PASS - nothing was queued by the refused requests
PASS - the owner's return becomes a pending approval item
PASS - no return record exists before approval
PASS - a repeated request is not queued twiceTest the agent
test_agent.py is the proof that the pieces work together. Replace the whole file. It has four parts, and parts B and C continue inside one with workdir(seed=True): block.
import os
import agent
import approvals
import run_inbox
from fakes import PLANS, FakeModel, check, reply, workdir
TICKETS = {t["ticket_id"]: t for t in run_inbox.load_tickets()}
SEARCH = [("search_help", {"query": "order status dispatched"})]
PROMISE = reply("order", "normal", None, [], None, "Asks.", "A full refund is on its way.")
STAFF = reply("other", "normal", None, ["KB-15"], None, "Asks.", "Refunds above 500 need a manager (KB-15).")
def triage(ticket_id, plans=PLANS):
model = FakeModel(plans)
return agent.triage_ticket(TICKETS[ticket_id], model, "v1"), modelPROMISEis a reply with a refund promise.STAFFis a reply that cites a staff page. Both are bad on purpose.triage()runs one ticket with a fake model and returns the record and the model, so a test can look at what the model was sent.
with workdir(seed=True):
print("--- memory is loaded by code, for the ticket's own customer ---")
_, model = triage("T-2006")
check("alex's two earlier cases are in the model input, newest first",
"- 2026-11-12 complaint, order none, waiting\n- 2026-10-02 complaint, order none, resolved" in model.calls[0]["input"])
_, model = triage("T-2001")
check("maya has no history, so there is no history block", "Earlier cases" not in model.calls[0]["input"])
_, model = triage("T-2002")
check("tom's case is older than 90 days, so it is not loaded", "Earlier cases" not in model.calls[0]["input"])
check("no input ever holds an email address", all("example.com" not in str(call["input"]) for call in model.calls))
print("--- every draft waits for approval ---")
record, _ = triage("T-2001")
queue = approvals.pending()
check("a good triage queues one send_reply item with the draft", queue[-1]["action"] == "send_reply" and queue[-1]["payload"]["draft_reply"] == record["draft_reply"])
check("nothing is in the outbox", not os.path.exists(approvals.OUTBOX))
triage("T-2002") # the second time for this ticket
returns = [item for item in approvals.load() if item["action"] == "create_return"]
check("the return is queued once, even though the ticket was triaged twice", len(returns) == 1)
check("the queued return comes from the model's tool call", returns[0]["payload"] == {"order_id": "QF-1044", "reason": "wrong_size"})
check("the return item belongs to ticket T-2002 and is pending", (returns[0]["ticket_id"], returns[0]["status"]) == ("T-2002", "pending"))
check("the outbox is still empty", not os.path.exists(approvals.OUTBOX))print("--- validation, retry, then manual triage ---")
before = len(approvals.load())
good = PLANS["T-2001"][-1]
record, model = triage("T-2001", {"T-2001": [SEARCH, PROMISE, good]})
check("a bad draft is retried once and then accepted", not record["manual"] and len(model.calls) == 3)
check("the retry message lists the problems", model.calls[2]["input"].startswith("Your reply had these problems:") and "promises a refund" in model.calls[2]["input"])
check("the retry continues the same conversation", model.calls[2]["previous_interaction_id"] == "i-2")
record, model = triage("T-2001", {"T-2001": [SEARCH, PROMISE]})
check("two bad answers give manual triage", record["manual"] and record["draft_reply"] == "" and record["queue"] == "support_team")
check("the manual summary says why", record["summary"] == "Automatic triage failed: validation failed twice: draft_reply promises a refund")
check("there was exactly one retry", len(model.calls) == 3)
record, _ = triage("T-2001", {"T-2001": [STAFF]})
check("a staff page id in sources gives manual triage", record["manual"])
check("only the one accepted retry queued a draft", len(approvals.load()) == before + 1)
print("--- the budget stops a run ---")
runaway = {"T-2001": [SEARCH, SEARCH, PROMISE, SEARCH, SEARCH, SEARCH, SEARCH]}
record, model = triage("T-2001", runaway)
check("the 7th model call is never made", len(model.calls) == agent.MAX_MODEL_CALLS_PER_RUN == 6)
check("the budget stop gives manual triage", record["manual"] and "budget" in record["summary"])
check("endless tool calls stop after MAX_ROUNDS", triage("T-2001", {"T-2001": [SEARCH]})[0]["summary"].endswith("too many tool rounds"))
print("--- failures and the earlier rules still hold ---")
check("model failure gives a manual record", triage("T-2001", {"T-2001": "error"})[0]["manual"])
check("text that is not JSON twice gives a manual record", triage("T-2001", {"T-2001": ["Sorry."]})[0]["manual"])
record, _ = triage("T-2004")
check("safety is still high urgency and goes to the safety team", (record["urgency"], record["queue"]) == ("high", "safety_team"))
record, _ = triage("T-2007")
check("someone else's order is still never revealed", "QF-1044" not in record["draft_reply"])with workdir(seed=True):
print("--- the whole inbox ---")
records = run_inbox.run_all(FakeModel(), list(TICKETS.values()))
items = approvals.load()
check("8 tickets give 8 drafts and 1 return proposal, all pending", len(items) == 9 and all(i["status"] == "pending" for i in items))
check("the outbox does not exist yet", not os.path.exists(approvals.OUTBOX))
approvals.decide("A-0001", "approve", "Dana")
check("after one approval the outbox has one line", len(open(approvals.OUTBOX, encoding="utf-8").read().splitlines()) == 1)- The memory tests look at the exact text sent to the model: Alex's two lines appear, newest first. Maya has no history. Tom's case is too old. No input ever contains
example.com. - A good triage queues one
send_replyitem with the draft, and the outbox file does not exist. - Triaging T-2002 twice still queues one return, but the test counts returns only, which is where the idempotent protection is.
- A bad draft followed by a good one gives an accepted record after three model calls, and the retry message lists the problems. Two bad drafts give manual triage, with exactly one retry.
- The runaway script keeps asking for tools. The test proves the seventh call is never made, and that the stop reason mentions the budget.
- The last part runs all eight sample tickets. They give 8 drafts and 1 return proposal, all pending, an empty outbox, and one outbox line after one approval.
--- memory is loaded by code, for the ticket's own customer ---
PASS - alex's two earlier cases are in the model input, newest first
PASS - maya has no history, so there is no history block
PASS - tom's case is older than 90 days, so it is not loaded
PASS - no input ever holds an email address
--- every draft waits for approval ---
PASS - a good triage queues one send_reply item with the draft
PASS - nothing is in the outbox
PASS - the return is queued once, even though the ticket was triaged twice
PASS - the queued return comes from the model's tool call
PASS - the return item belongs to ticket T-2002 and is pending
PASS - the outbox is still empty
--- validation, retry, then manual triage ---
PASS - a bad draft is retried once and then accepted
PASS - the retry message lists the problems
PASS - the retry continues the same conversation
PASS - two bad answers give manual triage
PASS - the manual summary says why
PASS - there was exactly one retry
PASS - a staff page id in sources gives manual triage
PASS - only the one accepted retry queued a draft
--- the budget stops a run ---
PASS - the 7th model call is never made
PASS - the budget stop gives manual triage
PASS - endless tool calls stop after MAX_ROUNDS
--- failures and the earlier rules still hold ---
PASS - model failure gives a manual record
PASS - text that is not JSON twice gives a manual record
PASS - safety is still high urgency and goes to the safety team
PASS - someone else's order is still never revealed
--- the whole inbox ---
T-2001 order normal orders_team manual=False
T-2002 return normal orders_team manual=False
T-2003 product_question low support_team manual=False
T-2004 safety high safety_team manual=False
T-2005 order normal orders_team manual=False
T-2006 complaint high support_team manual=False
T-2007 order normal orders_team manual=False
T-2008 other normal support_team manual=False
PASS - 8 tickets give 8 drafts and 1 return proposal, all pending
PASS - the outbox does not exist yet
PASS - after one approval the outbox has one lineFinally, run python test_triage.py. You did not change triage.py, and its 17 tests still pass. In total you now have 113 PASS lines and no FAIL. Run every test twice. The output must be identical.
Step 8: Run the fake inbox and play the reviewer
run_fake.py runs the eight sample tickets with the fake model inside a temporary folder. Then it acts as a reviewer: it approves two items and rejects one, and prints the outbox. Replace the file with this version.
import os
os.environ.setdefault("GEMINI_API_KEY", "not-used-with-a-fake") # run_inbox imports the real SDK
import approvals
import review
import run_inbox
from fakes import FakeModel, workdir
tickets = run_inbox.load_tickets()
with workdir(seed=True): # a temporary folder: your real files are not touched
run_inbox.run_all(FakeModel(), tickets)
print("--- the approval queue after triage ---")
review.show_pending()
print("--- a reviewer decides ---")
for approval_id, decision, note in [("A-0001", "approve", None), ("A-0002", "approve", None),
("A-0003", "reject", "Please offer a call instead.")]:
item = approvals.decide(approval_id, decision, "Dana", note)
print(item["approval_id"], item["action"], item["status"])
print("--- the outbox ---")
with open(approvals.OUTBOX, encoding="utf-8") as outbox:
print(outbox.read().strip())workdir(seed=True)gives a clean folder with the sample history, so you can run the script again and again.run_inbox.run_all()is the runner from the last lesson. It prints one line per ticket.review.show_pending()prints the queue before any decision.- The three decisions all use the reviewer name
Dana. A-0001 approves the order reply, A-0002 approves the return and A-0003 rejects the return reply with a note. - At the end the script prints the outbox.
Run it with python run_fake.py. It needs no key.
T-2001 order normal orders_team manual=False
T-2002 return normal orders_team manual=False
T-2003 product_question low support_team manual=False
T-2004 safety high safety_team manual=False
T-2005 order normal orders_team manual=False
T-2006 complaint high support_team manual=False
T-2007 order normal orders_team manual=False
T-2008 other normal support_team manual=False
--- the approval queue after triage ---
A-0001 T-2001 send_reply {'draft_reply': 'Your order QF-1042 was dispatched and should arrive by 2026-11-18 (KB-02).'}
A-0002 T-2002 create_return {'order_id': 'QF-1044', 'reason': 'wrong_size'}
A-0003 T-2002 send_reply {'draft_reply': 'I have asked our team to review a return for order QF-1044. Staff reply within 2 working days (KB-03, KB-04).'}
A-0004 T-2003 send_reply {'draft_reply': 'At 172 cm you fit size M, which suits riders 165 to 178 cm tall (KB-06).'}
A-0005 T-2004 send_reply {'draft_reply': 'Please stop riding and do not adjust the brakes yourself. Our safety team will contact you (KB-09).'}
A-0006 T-2005 send_reply {'draft_reply': 'The address can change only before dispatch (KB-11). Order QF-1046 is still processing, so a colleague will help you.'}
A-0007 T-2006 send_reply {'draft_reply': 'I am sorry you have waited so long. A member of our support team will reply to you personally.'}
A-0008 T-2007 send_reply {'draft_reply': 'I could not find that order number on your account. Please check the number and write back.'}
A-0009 T-2008 send_reply {'draft_reply': 'Thank you for your message. A member of our support team will read it and reply to you.'}
9 waiting
--- a reviewer decides ---
A-0001 send_reply approved
A-0002 create_return approved
A-0003 send_reply rejected
--- the outbox ---
{"approval_id": "A-0001", "ticket_id": "T-2001", "reply": "Your order QF-1042 was dispatched and should arrive by 2026-11-18 (KB-02).", "approved_by": "Dana"}What the walk-through shows
- Nine items wait, none are sent. Eight drafts and one return proposal are pending. Ticket T-2002 produced two items: the proposed return (A-0002) and the reply (A-0003).
- Approve one: A-0001 is approved by Dana. One line appears in the outbox with her name. That is the only line.
- Approve a return: A-0002 is approved. The return is recorded once in
returns.json. Nothing goes to the outbox, because a return is not a reply. - Reject one: A-0003 is rejected with a note. It never reaches the outbox.
- The outbox has one line. Three decisions, two approvals, but only one of them was a reply.
To play the reviewer yourself on real files, run python run_inbox.py (Step 9), then python review.py to see the queue, and for example python review.py A-0001 approve YourName. Use your own name, because the reviewer name is the record of who decided.
Step 9: Run it with the real model and check the requests
First the dummy-key check. A dummy key is a made-up key that Google rejects. It proves your request has the shape Google expects. The file is the same as in the last lesson, and it needs internet.
import os
os.environ["GEMINI_API_KEY"] = "dummy-key-not-real" # must be set before the client is made
from google import genai
import versions
client = genai.Client()
try:
client.interactions.create(model=versions.MODEL, input="hi")
except Exception as error:
print("Google said:", str(error)[:108])Google said: Error code: 400 - [{'error': {'code': 400, 'message': 'API key not valid. Please pass a valid API key.', 'stNow the real run. Make sure GEMINI_API_KEY is in your .env file and that you ran python seed_history.py. Delete any old approvals.json, outbox.jsonl and returns.json, because this runner writes to your real folder.
python seed_history.py
python run_inbox.py
python review.pyA real model gives answers that differ from run to run. The sample below shows the shape of the result. Yours will differ, and some tickets may fall back to manual triage. That is not a failure of the desk. It is the rule working. Look at the summary of each manual record to see which check caught the problem.
T-2001 order normal orders_team manual=False
T-2002 return normal orders_team manual=False
T-2003 product_question low support_team manual=False
T-2004 safety high safety_team manual=False
T-2005 order normal orders_team manual=False
T-2006 complaint high support_team manual=False
T-2007 order normal orders_team manual=False
T-2008 other normal support_team manual=TrueHere ticket T-2008, the one with the injection text, became a manual record in this sample. A manual record has no draft, so nothing about it goes into the queue. Whether your real run does the same depends on the model.
Step 10: Map each step to a requirement and write your notes
A requirement that no test and no code can point to is only a wish. This table connects every control of this lab to the requirement it serves and to the test that proves it. Copy it into memory-and-approval-notes.md and replace the example rows with your own.
| Requirement | Control in this lab | Where | Proved by |
|---|---|---|---|
| R5 Never send or create a return without a named person | Approval queue, decide() with a reviewer name, outbox and returns written only on approval | approvals.py, agent.py finish(), tools.py request_return | test_approvals.py, test_agent.py, test_tools.py |
| R6 Last 90 days, same customer only | Pseudonymous key, load by code from the ticket's own email, 90-day cutoff and purge | memory.py, agent.py ticket_text() | test_memory.py, test_agent.py |
| R7 Two validation failures give manual triage | check_triage, one retry with the problems, then manual_record() | validate.py, agent.py triage_ticket() | test_validate.py, test_agent.py |
| N2 At most 6 model calls | Budget counter before every model call | agent.py Budget, send() | test_agent.py (the seventh call is never made) |
| N3 No email or card-like number in drafts | Pattern checks on draft and summary, history without emails or bodies | validate.py, memory.py | test_validate.py, test_memory.py |
| R4 Only retrieved customer pages cited | Source check against pages retrieved in this run | validate.py | test_validate.py |
Your notes file
- How long you keep case history, who or what runs the purge and why that period fits your option.
- What a history record may hold and what it must never hold.
- The list of checks in
check_triageand the known weakness of each (for example, the refund patterns). - Your known gaps: no code writes closed cases yet, duplicate drafts for a repeated ticket, and the outbox is a file stand-in. Also,
decide()writes the outbox line before it saves the new status. If the program crashed between those two lines, the item would still look pending, and a second approval would write the reply twice. A real email system would refuse a second message with the sameapproval_id.
If you chose a different option
The four controls are the same for every option. Only the data and the actions change. The table gives a starting idea for each of the other options. Write your own.
| Your option | Memory (and its limit) | Validation checks | What waits for approval |
|---|---|---|---|
| 1. Documentation research agent | Past questions of one user, as topics only, with a retention period | Every cited document id was retrieved and is allowed for this user | Saving a report |
| 3. Developer issue-analysis agent | Earlier analyses of one project, as issue numbers and labels, never the issue text | Suggested labels come from an allowed list, no secrets in the comment text | Adding a label or a comment |
| 4. Claims-document review assistant | Probably none across cases. Each case stands alone. If you add memory, tie it to the assigned reviewer | Every figure in a recommendation appears in the claim document, no personal data in the summary | Every recommendation, by a named reviewer |
| 5. Cloud-cost investigation agent | Earlier investigations of one account label, with their outcome | Only resources from the read-only listing are mentioned, savings are numbers from the metrics | Any change proposal |
Conclusion and your next step
Your desk now remembers a little, forgets on schedule and loads history only for the customer on the ticket. Every model answer is checked in code. A bad answer gets one retry and then falls back to a person. A call budget stops runaway runs. Nothing is sent and no return is created until a named reviewer decides, and a return can be approved only once.
Your next step: continue with Test with Evaluation Scenarios and Adversarial Inputs. There you build a set of test cases, including tricky and hostile tickets, and measure whether these controls hold.
For the thinking behind this lab, revisit Conversation State vs. Persistent Memory, Human-in-the-Loop Approval and Escalation and Prompt Injection and Untrusted Tool Outputs. The Capstone: Build a Production-Ready AI Agent overview shows the whole path.
Common errors and how to fix them
After adding validation, almost every ticket becomes manual triage, with a summary such as "validation failed twice: source KB-02 was not retrieved in this run".
Why it happens: The model wrote a source id in sources but did not call search_help in this run, so the id is not in the set of retrieved pages. The check does what it should.
Fix: Read the summary of the manual record. Then strengthen the instructions: call search_help before citing a page. Do not weaken the check. In the fake tests, make sure the script calls the tool before it cites the page.
Running python run_inbox.py a second time doubles the number of drafts in the queue, and ids such as A-0009 keep growing.
Why it happens: The queue is a file in your folder. A repeated ticket queues a new draft each time, because only returns are protected against copies.
Fix: For practice runs, delete approvals.json, outbox.jsonl and returns.json first. In a real desk, link each draft to its ticket and run, and say so in your known gaps.
python review.py A-0001 approve ends with "a reviewer name is required", or with "A-0001 was already approved".
Why it happens: The reviewer name is missing or empty, or the item was already decided. Both refusals are deliberate.
Fix: Add your own name after the word approve. Run python review.py first to see which items are still pending. An item cannot be decided twice, so a mistake needs a new proposal, not a second decision.
The model input never contains "Earlier cases of this customer", even for Alex.
Why it happens: history.json does not exist because you did not run seed_history.py, or you started Python from another folder, or the ticket's received date is more than 90 days after the cases.
Fix: Run python seed_history.py from the project folder, then run your script from the same folder. Check the dates: a case older than 90 days on the ticket's date is ignored by design.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Close the memory loop: write closed cases into the history
Right now nothing writes to the history. Add a function remember_case(ticket, record, outcome, today) to memory.py that stores one closed case for the ticket's own customer, and call it when a reviewer decides on a reply. Keep to the rules of the history: pseudonymous key, no message text, no email address.
You will need
- Your finished
memory.py,approvals.py,test_memory.pyand the sample history. - The record format: ticket_id, date, category, order_id, outcome.
- A rule you choose: what the outcome is when a reply is approved and when it is rejected.
Acceptance criteria
Your work is done when every one of these is true.
Hints (3)
decide()does not know the ticket's email. Think about where the email is available (the ticket) and keep personal data out ofapprovals.py. One option is to callremember_case()from the code that runs the review, with the ticket in hand.- To avoid duplicates, look for an existing record with the same
ticket_idfirst and replace it. - Use the date of the decision as
today, and pass it in, so the test can use a fixed date.
Show a model answer
A strong answer adds remember_case() with four steps: build the key from the email, load the history, replace or append the record for that ticket id, and save. The record has only the five fields, so no body or email can slip in. The call comes from the place that has both the ticket and the decision, not from inside decide(), which should stay free of personal data. The test seeds a workdir, closes a case for Maya, checks that history_lines() shows it, checks that Alex's lines are unchanged, and runs the call twice to prove there is still one record. The notes explain the outcome words, for example resolved for an approved reply and waiting for a rejected one, and that the 90-day purge removes the case later. A weak answer stores the draft text so that "it is more useful later". That keeps data the desk does not need.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. The model only follows text, and text in a ticket may be hostile. Code uses the customer on the ticket, so no wording can change whose data is read. It is not about whether a model can read files, and speed is not the reason.
Show the answer and explanation
Answer: B. The checker finds the promise, and the retry rule from R7 applies. The first option is tempting, but a draft with a known problem never reaches the reviewer. Code does not edit the text, because a rewritten draft would not be what the model proposed.
Show the answer and explanation
Answer: B. An item can be decided only once, and recording the same return again changes nothing. Two return records would be a real-world mistake, and overwriting would erase who made the first decision.
Frequently asked questions
How can an AI agent have memory without storing personal data?
Store only the facts you need, such as a date, a category and an outcome. Use a pseudonymous key instead of an email and never store message text. Add a retention period and delete old records on a schedule. A pseudonym is not full anonymity, so protect the file anyway. Rules differ by country, so follow your organisation's policy.
How do I validate the output of an LLM agent?
Ask for a fixed structure, such as one JSON object, and check it in code: required fields, allowed values, sources the agent really used, and content rules such as no email addresses. If a check fails, send the problems back once. If it still fails, hand the work to a person.
How do I add human approval to an AI agent in Python?
Do not give the agent a tool that does the final action. Let it propose an action into a queue. A person calls a function such as decide() with their name. Only an approved decision does the real work, and an item can be decided only once. Log who decided and when.
How do I stop an AI agent from calling the model forever?
Count calls in code and refuse the call after a fixed number. Add a separate limit on tool rounds. When a limit is reached, stop and hand the task to a person with a clear reason. Never let the model decide its own limit.
- Written by
- PromptFable Editorial
- Last updated 18 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- LLM06:2025 Excessive Agency(opens in a new tab)
OWASP Foundation · Official documentation · Covers the risk of agents with too much power, and human approval as one control.
- LLM05:2025 Improper Output Handling(opens in a new tab)
OWASP Foundation · Official documentation · Why model output must be checked before other systems use it.
- LLM10:2025 Unbounded Consumption(opens in a new tab)
OWASP Foundation · Official documentation · Background for limits on calls and runaway runs.
- LLM02:2025 Sensitive Information Disclosure(opens in a new tab)
OWASP Foundation · Official documentation · Why personal data should not sit in memory, prompts or logs without need.
- hashlib: Secure hashes and message digests(opens in a new tab)
Python Software Foundation · Official documentation · The standard-library module that makes the pseudonymous key.
- threading: Thread-based parallelism(opens in a new tab)
Python Software Foundation · Official documentation · Describes `Lock`, which keeps the queue safe when several changes arrive together.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.