Skip to content

Module 10 · Lesson 10.6

Deploy, Monitor and Document the Solution

2 hUpdated 18 Nov 2026Part of Capstone: Build a Production-Ready AI Agent · AI Agent Development
On this page
  1. What you will learn
  2. What you will build: the Triage Desk as a monitored service
  3. Step 1: Set up the stage 6 folder
  4. Step 2: Add tracing with redaction and version labels (tracing.py)
  5. Step 3: Make the agent record its steps (agent.py and the runners)
  6. Step 4: Add the version switch and rollback (versions.py, rollback.py)
  7. Step 5: Add the monitor and its alerts (monitor.py)
  8. Step 6: Build the service (service.py)
  9. Step 7: Extend the test helper (fakes.py)
  10. Step 8: Write and run the offline tests
  11. Step 9: Run the service on your computer
  12. Step 10: Practise a rollback
  13. Step 11: Write the four documents
  14. How the service supports your five demonstration scenes
  15. A controlled test environment, and what production would add
  16. If you chose a different option
  17. Conclusion and your next step
  18. Common errors and fixes
  19. Validation checklist
  20. Hands-on exercise
  21. Knowledge check
  22. Frequently asked questions
  23. References

A new shop assistant may be excellent on a quiet morning. The shop owner still wants three things before leaving them alone at the counter: a logbook of what happened, a bell that rings when something goes wrong, and a written guide that says what to do. Software that serves real work needs the same three things.

In this lab the Quillfeather Triage Desk starts working at the counter. You turn it into a small web service, add traces and a monitor, guard the approval step, practise a rollback and write the four documents a reviewer will read. Everything is tested offline with a fake model first. The service stays a controlled test environment, and the lesson says clearly what a real launch would still need.

What you will learn

  • Serve the Triage Desk over HTTP with endpoints for tickets, approvals, traces and health.
  • Record every run as a redacted trace with a version label, and read it with a monitor that raises alerts.
  • Switch between two versions with one file and exercise a rollback by following a runbook.
  • Write a README, a runbook, a threat model with a residual-risk statement and an evaluation report.

Before you start

What you will build: the Triage Desk as a monitored service

In the last lessons your agent learned to triage tickets, check its own work and wait for a person's approval. It still lives inside test scripts, though. A shop needs more than that. It needs a front desk that other programs can talk to, a logbook that shows what happened, an alarm that rings when something goes wrong and a written guide for the person on duty.

A service is a program that keeps running and waits for requests from other programs. In this lab you wrap the Triage Desk in a small web service that runs only on your own computer. You add a trace for every run, a monitor that reads the traces, a version switch with a rollback, and four documents. The method is the one from Practical Lab: Deploy and Monitor an Agent Service. This lesson applies it to the capstone project and keeps the explanations short. Read the Module 9 lab first if the ideas are new.

How one ticket travels through the service
  1. POST /tickets

    Checks the ticket, reads active_version.txt

  2. Run starts

    Run id such as R-0001 and a version label

  3. Agent loop

    Model calls, tool calls and checks, each timed and traced

  4. Triage record

    The record, or manual triage if something failed

  5. Approval queue

    A named reviewer decides with POST /approvals/<id>

  6. Monitor

    monitor.py reads the traces and raises alerts

Every step in the agent loop writes a line to traces.jsonl. The reviewer step is separate and needs a token.

Endpoint
One address of the service that does one job, such as /health. A request names the address and a method: GET to read, POST to send something.
Trace
The step-by-step record of one run. Each step is one line: a model call, a tool call or a check, with its time and whether it went well.
Redaction
Hiding sensitive text before it is written down. An email address becomes [email] and a card-like number becomes [card].
Monitor and alert
The monitor is a script that reads the traces and sums them up. An alert is a message it prints when a number passes a limit, like a smoke alarm that beeps when there is too much smoke.
Rollback
Going back to the last version that worked. Here it means writing the old version name into one small file.
Runbook
A written guide for the person on duty: how to start, check, respond to alerts and roll back. It is written for a tired person at a bad moment, so it is short and exact.

Which requirements this lesson proves

IDRequirementWhere you prove it in this lesson
R8Record a trace for every run, with the version label and redactiontracing.py, test_tracing.py and the trace checks in test_service.py
N1Triage of one ticket finishes within 20 secondsmonitor.py reports the median and the slowest run, and alerts above 20000 ms
N2At most 6 model calls per ticketThe budget from the earlier lesson stays. The monitor adds an alert on the average
N3No email addresses or card-like numbers in traces or draftsredact(), and a test that the trace file holds no @
N4A rollback takes under 5 minutes by following the runbookrollback.py, RUNBOOK.md and the rollback exercise in Step 10
R1 to R7 were proved in the earlier lessons. This lesson must not break them, so you run those tests again.

What you will hand in

  • Your code: tracing.py, service.py, monitor.py, rollback.py, the changed agent.py and versions.py, and the three new test files.
  • The output of all eleven test files, with every line starting with PASS.
  • A local run of the service: health check, one ticket, one approval and one trace.
  • A rollback you have practised: the output of rollback.py and a health check before and after.
  • Four documents: README.md, RUNBOOK.md, THREAT_MODEL.md and EVALUATION_REPORT.md, filled in with your own facts.

Step 1: Set up the stage 6 folder

Start from your finished project of Test with Evaluation Scenarios and Adversarial Inputs. Copy the folder and work in the copy, so stage 5 stays safe. Every command in this lesson runs from inside this folder. Running from another folder is the most common mistake, and the symptom is a FileNotFoundError for inbox.jsonl.

FileStatusWhat it is for
tracing.pyNewRun ids, trace events, redaction
service.pyNewThe HTTP service
monitor.pyNewSummary of the traces and the alerts
rollback.pyNewSwitch the live version
test_tracing.py, test_monitor.py, test_service.pyNewOffline tests (no key, no network)
check_service_key.pyNewThe service with a dummy key
README.md, RUNBOOK.md, THREAT_MODEL.mdNewThe documents. EVALUATION_REPORT.md is carried over from stage 5
agent.py, versions.py, run_inbox.py, run_eval.py, fakes.py, test_runner.pyChangedThe agent takes a run object, versions get a switch, the test helper gets a clock and a server starter
.gitignoreChangedAlso ignores traces.jsonl

Replace your .gitignore with this. Traces hold tool names and times, and you should keep them out of git like every other run file.

Text.gitignore
.env
__pycache__/
*.pyc
approvals.json
outbox.jsonl
returns.json
results_*.jsonl
traces.jsonl

Step 2: Add tracing with redaction and version labels (tracing.py)

A trace is only useful if every line has the same shape. This file uses the format from Tracing Tool Calls and Agent Decisions: run_id, step, kind, name, ms, ok and version. It never stores the text of a customer message. It stores what happened, how long it took and whether it went well. Data Privacy, Sensitive Information and Secure Logging explains why logs are a common place for leaks.

Part 1 has the redaction function and the Tracer. The tracer writes one JSON line per event to a file. A lock keeps it safe when several requests arrive at once.

Pythontracing.py
import json
import re
import threading
import time

from validate import CARD, EMAIL


def redact(text):
    return CARD.sub("[card]", EMAIL.sub("[email]", text))


class Tracer:
    """Appends one JSON line per event to a file. Safe to share between threads.
    With no path it keeps nothing, which is handy for tests and for the evaluation runner."""

    def __init__(self, path=None):
        self.path = path
        self.lock = threading.Lock()
        self.last = max([int(n) for n in re.findall(r'"run_id": "R-(\d+)"', self._text())] or [0])

    def _text(self):
        try:
            with open(self.path, encoding="utf-8") as file:
                return file.read()
        except (FileNotFoundError, TypeError):  # no file yet, or no path at all
            return ""

    def new_run_id(self):
        with self.lock:
            self.last += 1
            return f"R-{self.last:04d}"

    def write(self, event):
        if self.path is None:
            return
        clean = {key: redact(value)[:100] if isinstance(value, str) else value for key, value in event.items()}
        with self.lock, open(self.path, "a", encoding="utf-8") as file:
            file.write(json.dumps(clean) + "\n")

Part 1 of 2. Save as tracing.py.

What each part does

  • redact(text) swaps email addresses and card-like numbers for [email] and [card]. It reuses the two patterns that validate.py already has, so one rule serves both places.
  • Tracer(path) remembers the highest run id already in the file, so run ids keep counting up after a restart. With no path it keeps nothing, which suits tests.
  • new_run_id() gives out R-0001, R-0002 and so on. The lock stops two requests from getting the same id.
  • write(event) redacts every text value, cuts it to 100 characters and appends one line.

Part 2 reads events back and defines Run. A Run is one ticket from start to finish. Its timed method runs a function, measures how long it took and writes the event, even when the function crashes.

Pythontracing.py
    def events(self, run_id):
        with self.lock:
            lines = self._text().splitlines()
        found = []
        for line in lines:
            try:
                event = json.loads(line)
            except json.JSONDecodeError:
                continue  # skip a damaged line instead of failing
            if event.get("run_id") == run_id:
                found.append(event)
        return found


def is_ok(kind, result):
    if kind == "check":
        return not result  # a check returns nothing, or an empty list, when there is no problem
    return not (isinstance(result, dict) and "error" in result)


class Run:
    """One ticket from start to finish: a run id, a step counter and a version label."""

    def __init__(self, tracer, version, clock=time.perf_counter):
        self.tracer, self.version, self.clock = tracer, version, clock
        self.run_id = tracer.new_run_id()
        self.step = 0

    def record(self, kind, name, start, ok):
        self.step += 1
        ms = round((self.clock() - start) * 1000)
        self.tracer.write({"run_id": self.run_id, "step": self.step, "kind": kind,
                           "name": name, "ms": ms, "ok": ok, "version": self.version})

    def timed(self, kind, name, function, *args):
        start = self.clock()
        try:
            result = function(*args)
        except Exception:
            self.record(kind, name, start, False)
            raise
        self.record(kind, name, start, is_ok(kind, result))
        return result

Part 2 of 2. Add below Part 1.

What each part does

  • events(run_id) returns the lines for one run. A damaged line is skipped instead of breaking the whole read.
  • is_ok(kind, result) decides if a step went well. A tool result with an error key is not ok. A check is ok when it returns no problems.
  • Run holds the run id, a step counter and the version label. The clock is a parameter, so tests can use a fake clock and get the same times every time.
  • timed(kind, name, function, *args) is the one place where timing happens. If the function raises an error, it records a failed step and raises the error again, so nothing is hidden.

Step 3: Make the agent record its steps (agent.py and the runners)

The agent must now take a Run instead of a plain run id, and every model call, tool call and check must go through run.timed. Make the replacements below in your agent.py. Nothing else in the file changes. First add import tracing, so that the top of the file looks like this.

Pythonagent.py
import json

import approvals
import memory
import tools
import tracing
import triage
import validate
import versions

Replace the imports at the top of agent.py.

The old send is split in two. call_model talks to the model, and the new send counts the call against the budget and times it. Replace the old send with both functions.

Pythonagent.py
def call_model(client, version, input_data, previous_id):
    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
    )


def send(client, run, budget, input_data, previous_id=None):
    budget.use()
    return run.timed("model", "interactions.create", call_model, client, run.version, input_data, previous_id)

Replace the old send function with these two.

In follow_tools, every tool call is now timed, and send receives the run. Replace the whole function.

Pythonagent.py
def follow_tools(client, run, 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 = run.timed("tool", call.name, 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, run, budget, outputs, interaction.id)
    raise Stop("too many tool rounds")

Replace follow_tools.

read_reply and finish change a little. A reply that is not valid JSON still counts as a failed check, so it is recorded too.

Pythonagent.py
def read_reply(text, retrieved, ticket, run):
    try:
        data = triage.parse_model_json(text)
    except ValueError as error:
        run.record("check", "validation", run.clock(), False)
        return None, [str(error)]
    return data, run.timed("check", "validation", validate.check_triage, data, retrieved, ticket)

Replace read_reply.

Pythonagent.py
def finish(data, ticket, run):
    """The draft is never sent. It goes into the approval queue."""
    record = triage.build_record(data, ticket, run.version, run.run_id)
    approvals.propose("send_reply", ticket["ticket_id"], {"draft_reply": record["draft_reply"]})
    return record

Replace finish.

Last, triage_ticket takes the run. When no run is given, it makes a quiet one that records nothing, which keeps the older tests working. At the end, a ticket that goes to a person adds a manual_triage event.

Pythonagent.py
def triage_ticket(ticket, client, version="v1", run=None):
    run = run or tracing.Run(tracing.Tracer(), version)  # no run given: nothing is traced
    budget, retrieved = Budget(), set()
    try:
        interaction = send(client, run, budget, ticket_text(ticket))
        for attempt in (1, 2):  # the first answer, then one retry
            interaction = follow_tools(client, run, budget, interaction, ticket, retrieved)
            data, problems = read_reply(interaction.output_text, retrieved, ticket, run)
            if not problems:
                return finish(data, ticket, run)
            if attempt == 1:
                interaction = send(client, run, 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__})"
    run.record("check", "manual_triage", run.clock(), False)
    return triage.manual_record(ticket, reason, run.version, run.run_id)

Replace triage_ticket.

What each part does

  • call_model is the only place that calls client.interactions.create, as in the Module 9 lab.
  • send spends one unit of the budget first, then times the call. A model that fails still leaves a failed step in the trace.
  • In follow_tools, the name of the step is the name of the tool, so a trace reads lookup_order, search_help and so on.
  • read_reply records a failed validation step when the text is not JSON, and otherwise times the real check.
  • finish and triage_ticket use run.version and run.run_id, so the record carries the same labels as the trace.
  • The last two lines of triage_ticket record manual_triage. The monitor counts that name to find the manual-triage rate.

Now change the runners. run_inbox.py creates a Run for each ticket and can write a trace file. Add import tracing at its top and replace run_all and the main block.

Pythonrun_inbox.py
def run_all(client, tickets, version="v1", tracer=None):
    tracer = tracer or tracing.Tracer()
    records = []
    for ticket in tickets:
        record = agent.triage_ticket(ticket, client, version, tracing.Run(tracer, version))
        print(one_line(record))
        records.append(record)
    return records


if __name__ == "__main__":
    load_dotenv()  # reads GEMINI_API_KEY from the .env file
    run_all(genai.Client(), load_tickets(), tracer=tracing.Tracer("traces.jsonl"))

Replace run_all and the main block in run_inbox.py.

In run_eval.py only one call changes. The evaluation runner no longer passes the case id, because the agent now makes its own quiet run. Replace the triage_ticket call (line 50) as shown.

Pythonrun_eval.py
try:
    with clean_folder():
        record = agent.triage_ticket(case["ticket"], client, version)
        queued = [item["action"] for item in approvals.load()]
        written = outbox_lines()

In run_eval.py, the call on the third line of this part replaces the old one.

In test_runner.py, only the pretend-bug helper changes. Its sloppy_finish must take (data, ticket, run) and call real_finish(data, ticket, run), because finish has the new signature.

Step 4: Add the version switch and rollback (versions.py, rollback.py)

A version is a named bundle of the things that change how the agent behaves. Here v1 and v2 use the same model and differ only in the instructions. As in Test with Evaluation Scenarios and Adversarial Inputs, v2 adds one extra rule that fixes a weakness the evaluation found. Which one is live is decided by the text inside one small file, active_version.txt. A rollback is nothing more than writing the old name back into that file.

Your versions.py already has VERSIONS, INSTRUCTIONS and V2_RULE. Check that the top of the file looks like this, then add the two functions at the bottom.

Pythonversions.py
from pathlib import Path

PATH = "active_version.txt"  # the file that says which version is live
MODEL = "gemini-3.8-flash"  # check Google's models page for a current name

The top of versions.py.

Pythonversions.py
def active_version(path=PATH):
    try:
        name = Path(path).read_text(encoding="utf-8").strip()
    except FileNotFoundError:
        raise ValueError(f"{path} is missing") from None
    if name not in VERSIONS:
        raise ValueError(f"unknown version {name!r} in {path}")
    return name


def set_active(name, path=PATH):
    if name not in VERSIONS:
        raise ValueError(f"unknown version {name!r}")
    Path(path).write_text(name + "\n", encoding="utf-8")

Add these two functions at the bottom of versions.py.

What each part does

  • PATH names the file that says which version is live. The service reads it on every request, so a change is live at once. No restart is needed.
  • active_version() reads the file. A missing file or an unknown name raises an error with a clear message, and the service answers with HTTP 500. This is called failing closed: it stops instead of guessing.
  • set_active(name) refuses a name that is not in VERSIONS, so a typing mistake cannot make a broken version live.

rollback.py is a tiny command-line tool around set_active. It prints what changed, so you can copy the line into your notes.

Pythonrollback.py
import sys

import versions


def main(argv, path=versions.PATH):
    if len(argv) != 1 or argv[0] not in versions.VERSIONS:
        print(f"usage: python rollback.py {'|'.join(versions.VERSIONS)}")
        return 1
    try:
        before = versions.active_version(path)
    except ValueError:
        before = "unknown"
    versions.set_active(argv[0], path)
    print(f"active version: {before} -> {argv[0]}")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))

Save as rollback.py.

What each part does

  • main(argv) accepts exactly one argument that is a known version. Otherwise it prints how to use it and returns 1.
  • It reads the version before the change and prints active version: <before> -> <after>. A damaged or missing file shows as unknown.
  • The last two lines make it work as a command: python rollback.py v1.

Remember the rule from Versioning, Rollbacks and Production Operations: a release is not finished until you have practised the way back. You do that in Step 10.

Step 5: Add the monitor and its alerts (monitor.py)

The monitor reads traces.jsonl and turns many lines into a short summary for each run: steps, total time, model calls, failed model calls, failed validations and whether the ticket went to manual triage. Then it compares the numbers with limits. The ideas come from Monitoring Quality, Failures, Latency and Cost. The limits sit at the top of the file, so you can see and change them.

Pythonmonitor.py
import json
import statistics
import sys

SLOW_RUN_MS = 20000  # requirement N1: a ticket must finish within 20 seconds
MAX_MODEL_ERROR_RATE = 0.10  # share of runs where a model call failed
MAX_MANUAL_RATE = 0.20  # share of runs that ended in manual triage
MAX_VALIDATION_FAIL_RATE = 0.30  # share of runs with at least one failed validation
MAX_AVG_MODEL_CALLS = 4  # requirement N2 allows 6 per ticket, so 4 on average is already a warning
KEYS = {"run_id", "step", "kind", "name", "ms", "ok", "version"}


def load(path):
    events, damaged = [], 0
    with open(path, encoding="utf-8") as file:
        for line in file:
            try:
                event = json.loads(line)
                if not (isinstance(event, dict) and KEYS <= set(event) and isinstance(event["ms"], int)):
                    raise ValueError
                events.append(event)
            except ValueError:  # bad JSON is a ValueError too
                damaged += 1
    return events, damaged

Part 1 of 5. Save as monitor.py.

What each part does

  • Each limit has a comment that links it to a requirement. SLOW_RUN_MS = 20000 is N1. An average of 4 model calls is a warning that comes before the hard limit of 6 in N2.
  • load(path) reads the file line by line. A line that is not JSON, or has missing fields, is counted as damaged and skipped. A monitor that crashes on one bad line is useless when you need it most.
Pythonmonitor.py
def summarise(events):
    runs = {}
    for event in events:
        run = runs.setdefault(event["run_id"], {"run_id": event["run_id"], "version": event["version"], "steps": 0,
                                                "total_ms": 0, "model_calls": 0, "model_errors": 0,
                                                "validation_failures": 0, "manual": False})
        run["steps"] += 1
        run["total_ms"] += event["ms"]
        run["model_calls"] += event["kind"] == "model"
        run["model_errors"] += event["kind"] == "model" and not event["ok"]
        run["validation_failures"] += event["name"] == "validation" and not event["ok"]
        run["manual"] = run["manual"] or event["name"] == "manual_triage"
    return sorted(runs.values(), key=lambda run: run["run_id"])


def rate(runs, field):
    return sum(1 for run in runs if run[field]) / len(runs) if runs else 0

Part 2 of 5. Add below Part 1.

What each part does

  • summarise(events) groups the events by run id and adds them up. In Python, True counts as 1, so adding a comparison counts the matching steps.
  • A run is manual when it has a step named manual_triage.
  • rate(runs, field) is the share of runs where a field is true or above zero. It returns 0 when there are no runs, so it never divides by zero.
Pythonmonitor.py
def alerts(runs):
    found = []
    slow = [run["run_id"] for run in runs if run["total_ms"] > SLOW_RUN_MS]
    if slow:
        found.append(f"slow runs (over {SLOW_RUN_MS} ms): {', '.join(slow)}")
    for field, limit, label in [("model_errors", MAX_MODEL_ERROR_RATE, "runs with a failed model call"),
                                ("manual", MAX_MANUAL_RATE, "runs ended in manual triage"),
                                ("validation_failures", MAX_VALIDATION_FAIL_RATE, "runs failed validation")]:
        if rate(runs, field) > limit:
            found.append(f"{sum(1 for r in runs if r[field])} of {len(runs)} {label} (limit {limit:.0%})")
    average = sum(run["model_calls"] for run in runs) / len(runs) if runs else 0
    if average > MAX_AVG_MODEL_CALLS:
        found.append(f"average model calls per run is {average:.1f} (limit {MAX_AVG_MODEL_CALLS})")
    return found

Part 3 of 5. Add below Part 2.

What each part does

  • alerts(runs) returns a list of plain sentences. It checks slow runs, failed model calls, manual triage, failed validations and the average number of model calls.
  • An alert is a prompt to look, not proof of a fault. With only a few runs, one bad run can cross a limit. The runbook says this too.
Pythonmonitor.py
def report(runs, damaged=0):
    print("run      version  steps  total_ms  model_calls  model_errors  validation_failures  manual")
    for run in runs:
        print(f"{run['run_id']:<8} {run['version']:<8} {run['steps']:>5} {run['total_ms']:>9} {run['model_calls']:>12} "
              f"{run['model_errors']:>13} {run['validation_failures']:>20}  {'yes' if run['manual'] else 'no'}")
    if not runs:
        print("no runs found")
        return
    slowest = max(runs, key=lambda run: run["total_ms"])
    manual = sum(1 for run in runs if run["manual"])
    failed = sum(run["validation_failures"] for run in runs)
    print(f"\nruns: {len(runs)}, median total_ms: {statistics.median(r['total_ms'] for r in runs):.0f}, "
          f"slowest: {slowest['run_id']} ({slowest['total_ms']} ms)")
    print(f"manual triage: {manual} of {len(runs)} runs ({100 * manual / len(runs):.1f}%)")
    print(f"validation failures: {failed} in total, model calls: {sum(r['model_calls'] for r in runs)} in total")
    for version in sorted({run["version"] for run in runs}):
        mine = [run for run in runs if run["version"] == version]
        print(f"{version}: {len(mine)} runs, manual {sum(1 for r in mine if r['manual'])}, "
              f"validation failures {sum(r['validation_failures'] for r in mine)}")
    if damaged:
        print(f"skipped {damaged} damaged line(s)")
    problems = alerts(runs)
    for message in problems:
        print("ALERT:", message)
    if not problems:
        print("No alerts.")

Part 4 of 5. Add below Part 3.

Pythonmonitor.py
if __name__ == "__main__":
    events, damaged = load(sys.argv[1] if len(sys.argv) > 1 else "traces.jsonl")
    report(summarise(events), damaged)

Part 5 of 5. The command-line entry. Add at the bottom.

What each part does

  • report(runs) prints a table with one row per run, then the median and the slowest run (N1), the manual-triage rate, the totals and one line per version.
  • Alerts print last, each starting with ALERT:. If there are none, it prints No alerts. The count per version lets you see that the bad runs began with v2.
  • python monitor.py traces.jsonl runs the whole thing. Without an argument it uses traces.jsonl.

Step 6: Build the service (service.py)

This is the longest file of the lab, so it comes in five parts. It uses only Python's standard library for the web part (http.server), as in the Module 9 lab. It offers five endpoints.

Method and pathWhat it doesNeeds the token?
POST /ticketsTakes a ticket as JSON and returns {"run_id": ..., "triage": {...}}No
GET /approvalsLists the pending items in the approval queueNo
POST /approvals/<approval_id>Approves or rejects one item. Body: decision, reviewer, noteYes, header X-Review-Token
GET /runs/<run_id>Returns the trace events of one runNo
GET /healthReturns {"ok": true, "version": "v1"}No
In a controlled test environment only the decision endpoint, the one that can change the outbox, is guarded.
Pythonservice.py
import hmac
import json
import os
import re
import time
from datetime import datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

from dotenv import load_dotenv
from google import genai

import agent
import approvals
import tracing
import versions

MAX_BODY = 10000  # bytes
RUN_ID = re.compile(r"R-\d{4,}")
APPROVAL_ID = re.compile(r"A-\d{4,}")
TICKET_ID = re.compile(r"T-\d{4,6}")
LIMITS = {"customer_email": 200, "subject": 200, "body": 5000}  # characters


def ticket_problem(ticket):
    """Return a message if the ticket is not acceptable, or None."""
    if not isinstance(ticket, dict):
        return "ticket must be a JSON object"
    for field in ["ticket_id", "customer_email", "subject", "body", "received"]:
        if not isinstance(ticket.get(field), str) or not ticket[field].strip():
            return f"{field} must be non-empty text"
    if not TICKET_ID.fullmatch(ticket["ticket_id"]):
        return "ticket_id must look like T-2001"
    if "@" not in ticket["customer_email"]:
        return "customer_email must be an email address"
    for field, limit in LIMITS.items():
        if len(ticket[field]) > limit:
            return f"{field} must be at most {limit} characters"
    try:
        datetime.strptime(ticket["received"], "%Y-%m-%dT%H:%M")
    except ValueError:
        return "received must look like 2026-11-18T09:12"
    return None

Part 1 of 5. Save as service.py. Settings and the ticket check.

What each part does

  • MAX_BODY caps the request size at 10,000 bytes. LIMITS caps each text field in characters.
  • The three patterns check that ids look right before anything else uses them, which keeps odd text like ../x out of the lookups.
  • ticket_problem(ticket) returns a short message for the first problem it finds, or None. Each message tells the sender exactly what to fix. The service answers 400 with that message.
Pythonservice.py
class Handler(BaseHTTPRequestHandler):
    def log_message(self, *args):
        pass  # the trace file is our log, so keep the console quiet

    def send_json(self, status, body):
        data = json.dumps(body).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def read_body(self):
        """Read the request body, or send an error and return None. We always read it, so the client sees our answer."""
        try:
            length = int(self.headers.get("Content-Length", "0"))
        except ValueError:
            self.send_json(400, {"error": "bad Content-Length"})
            return None
        raw = self.rfile.read(min(length, MAX_BODY + 1))
        if len(raw) > MAX_BODY:
            self.send_json(413, {"error": f"body must be at most {MAX_BODY} bytes"})
            return None
        return raw

    def parse_json(self, raw):
        """Return the JSON object in the body, or send an error and return None."""
        try:
            body = json.loads(raw)
        except ValueError:
            body = None
        if not isinstance(body, dict):
            self.send_json(400, {"error": "send a JSON object"})
            return None
        return body

Part 2 of 5. Add below Part 1. This is the start of class Handler.

What each part does

  • log_message is silent. The trace file is the log, and the console stays quiet.
  • send_json(status, body) is the one function that writes a reply, with the right headers.
  • read_body() reads the request body first and only then decides if it is too big. It reads at most MAX_BODY + 1 bytes, which is enough to know that the body was too big.
  • parse_json(raw) accepts only a JSON object. Anything else gets a 400 with send a JSON object.
Pythonservice.py
def version_or_error(self):
    try:
        return versions.active_version(self.server.version_file)
    except ValueError as error:
        self.send_json(500, {"ok": False, "error": str(error)})
        return None

def method_not_allowed(self):
    self.send_json(405, {"error": "method not allowed"})

do_PUT = do_PATCH = do_DELETE = method_not_allowed

def do_GET(self):
    if self.path == "/health":
        version = self.version_or_error()
        if version:
            self.send_json(200, {"ok": True, "version": version})
    elif self.path == "/approvals":
        self.send_json(200, approvals.pending())
    elif self.path.startswith("/runs/"):
        run_id = self.path.removeprefix("/runs/")
        events = self.server.tracer.events(run_id) if RUN_ID.fullmatch(run_id) else []
        if events:
            self.send_json(200, events)
        else:
            self.send_json(404, {"error": "no such run"})
    else:
        self.send_json(404, {"error": "not found"})

def do_POST(self):
    raw = self.read_body()
    if raw is None:
        return
    if self.path == "/tickets":
        self.post_ticket(raw)
    elif self.path.startswith("/approvals/") and APPROVAL_ID.fullmatch(self.path.removeprefix("/approvals/")):
        self.post_decision(self.path.removeprefix("/approvals/"), raw)
    else:
        self.send_json(404, {"error": "not found"})

Part 3 of 5. Add below Part 2, still inside class Handler.

What each part does

  • version_or_error() reads active_version.txt. A damaged file gives a 500 and returns None, so the caller stops.
  • do_PUT = do_PATCH = do_DELETE = method_not_allowed gives a clear 405 for methods the service does not offer.
  • do_GET handles /health, /approvals and /runs/<id>. The run id must match the pattern, so a path like /runs/../x is a plain 404.
  • do_POST reads the body first (see the lesson learned) and then sends the request to the ticket code or the approval code.
Pythonservice.py
def post_ticket(self, raw):
    ticket = self.parse_json(raw)
    if ticket is None:
        return
    problem = ticket_problem(ticket)
    if problem:
        return self.send_json(400, {"error": problem})
    version = self.version_or_error()
    if version is None:
        return
    run = tracing.Run(self.server.tracer, version, self.server.clock)
    try:  # a model failure is handled inside triage_ticket and becomes manual triage
        record = agent.triage_ticket(ticket, self.server.client, version, run)
    except Exception:
        return self.send_json(500, {"run_id": run.run_id, "error": "the service could not finish this run"})
    self.send_json(200, {"run_id": run.run_id, "triage": record})

def post_decision(self, approval_id, raw):
    expected = os.environ.get("REVIEW_TOKEN", "")
    if not expected:
        return self.send_json(503, {"error": "REVIEW_TOKEN is not set on the server"})
    given = self.headers.get("X-Review-Token")
    if not given:
        return self.send_json(401, {"error": "send the X-Review-Token header"})
    if not hmac.compare_digest(given.encode("utf-8"), expected.encode("utf-8")):
        return self.send_json(403, {"error": "wrong review token"})
    body = self.parse_json(raw)
    if body is None:
        return
    try:
        item = approvals.decide(approval_id, body.get("decision"), body.get("reviewer"), body.get("note"))
    except approvals.NotFound as error:
        return self.send_json(404, {"error": str(error)})
    except approvals.AlreadyDecided as error:
        return self.send_json(409, {"error": str(error)})
    except ValueError as error:
        return self.send_json(400, {"error": str(error)})
    self.send_json(200, {"approval": item})

Part 4 of 5. Add below Part 3, still inside class Handler.

What each part does

  • post_ticket checks the ticket, reads the live version, creates a Run and calls agent.triage_ticket. A model failure is handled inside the agent and becomes manual triage with HTTP 200. Only a real bug gives a 500, and the run id is still returned so you can find the trace.
  • post_decision checks the token in a fixed order: 503, 401, 403. Only then does it parse the body and call approvals.decide.
  • The errors from approvals map to clear codes: unknown item 404, already decided 409 and a bad reviewer name or decision 400. An item can be decided only once, so a second click never writes a second outbox line.
Pythonservice.py
def make_server(client, tracer, version_file=versions.PATH, port=8000, clock=time.perf_counter):
    server = ThreadingHTTPServer(("127.0.0.1", port), Handler)  # this computer only
    server.client, server.tracer, server.version_file, server.clock = client, tracer, version_file, clock
    return server


if __name__ == "__main__":
    load_dotenv()
    if not Path(versions.PATH).exists():
        versions.set_active("v1")
    if not os.environ.get("REVIEW_TOKEN"):
        print("Warning: REVIEW_TOKEN is not set, so nobody can approve anything.")
    server = make_server(genai.Client(), tracing.Tracer("traces.jsonl"))
    print("Listening on http://127.0.0.1:8000 (press Ctrl+C to stop)")
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("Stopped.")

Part 5 of 5. Add at the bottom, outside the class.

What each part does

  • make_server builds the server with ThreadingHTTPServer, so one slow ticket does not block a health check. It binds to 127.0.0.1, so only this computer can reach it. Tests pass port 0 to get any free port.
  • The client, tracer, version file and clock are stored on the server object. The handler reaches them with self.server. Tests replace the client with the fake model.
  • The main block makes active_version.txt with v1 if it does not exist and warns if REVIEW_TOKEN is not set. Then it serves until you press Ctrl+C.

Step 7: Extend the test helper (fakes.py)

The tests start the real service on a free port inside a thread and call it with urllib, so they test the same code you will run. For that, fakes.py gets three additions. The rest of your stage 5 fakes.py stays as it is.

First, replace the imports at the top of fakes.py. The new ones are threading, urllib.error, urllib.request, service, tracing and versions.

Pythonfakes.py
import contextlib
import itertools
import json
import os
import re
import tempfile
import threading
import urllib.error
import urllib.request
from types import SimpleNamespace as NS

import seed_history
import service
import tools
import tracing
import versions

Replace the imports at the top of fakes.py.

Second, FakeModel can move a fake clock. Each model call adds 120 milliseconds, so the monitor tests see the same times on every run. Replace the __init__ method and the first lines of create.

Pythonfakes.py
def __init__(self, plans=None, v2_plans=None, clock=None):
    self.plans, self.ids, self.calls, self.sessions = plans or PLANS, itertools.count(1), [], {}
    self.clock = clock  # a fake clock moves on 120 ms for every model call
    self.v2_plans = v2_plans or self.plans  # used when the instructions hold the v2 rule
    self.interactions = NS(create=self.create)

def create(self, **kw):
    self.calls.append(kw)
    if self.clock:
        self.clock.advance(0.12)

Change FakeModel.__init__ and the start of FakeModel.create.

Third, add a fake clock and a Harness that starts the service. Put both at the bottom of the file.

Pythonfakes.py
class FakeClock:
    """A clock we control: every reading moves it on by 1 ms, and a fake model can move it further."""

    def __init__(self):
        self.now = 0.0

    def __call__(self):
        self.now += 0.001
        return self.now - 0.001

    def advance(self, seconds):
        self.now += seconds

Add at the bottom of fakes.py: the fake clock.

Pythonfakes.py
class Harness:
    """Starts the real service on a free port in a thread, and calls it with urllib. Run it inside workdir()."""

    def __init__(self, client, clock=None):
        self.version_file = "active_version.txt"
        versions.set_active("v1", self.version_file)
        kwargs = {"clock": clock} if clock else {}
        self.server = service.make_server(client, tracing.Tracer("traces.jsonl"), self.version_file, port=0, **kwargs)
        threading.Thread(target=self.server.serve_forever, daemon=True).start()
        self.base = f"http://127.0.0.1:{self.server.server_address[1]}"

    def call(self, method, path, body=None, raw=None, token=None):
        data = raw if raw is not None else (json.dumps(body).encode("utf-8") if body is not None else None)
        headers = {"Content-Type": "application/json"}
        if token:
            headers["X-Review-Token"] = token
        request = urllib.request.Request(self.base + path, data=data, method=method, headers=headers)
        try:
            with urllib.request.urlopen(request, timeout=10) as response:
                return response.status, json.load(response)
        except urllib.error.HTTPError as error:
            return error.code, json.load(error)

    def post_ticket(self, ticket):
        return self.call("POST", "/tickets", ticket)

    def stop(self):
        self.server.shutdown()
        self.server.server_close()

Add below the fake clock: the harness.

What each part does

  • FakeClock moves forward 1 ms on each reading, and a test can push it ahead with advance. Time that is the same on every run lets a test check exact numbers.
  • Harness.__init__ sets v1 as live and starts the real server in a daemon thread. A daemon thread does not keep Python alive at the end.
  • call sends a request with urllib and returns the status and the JSON body. A 4xx or 5xx answer comes back as normal data, so a test can check the code.
  • stop() shuts the server down and frees the port.

Step 8: Write and run the offline tests

Three new test files prove the new rules. They need no key and no network. First test_tracing.py, for redaction, run ids and the trace format (R8 and N3).

Pythontest_tracing.py
import json

import tracing
from fakes import FakeClock, check, workdir

check("redact hides an email address", tracing.redact("Write to maya@example.com now") == "Write to [email] now")
check("redact hides a card-like number", tracing.redact("card 4111 1111 1111 1111 ok") == "card [card] ok")
check("redact leaves normal text alone", tracing.redact("order QF-1042 dispatched") == "order QF-1042 dispatched")

with workdir():
    tracer = tracing.Tracer("traces.jsonl")
    run = tracing.Run(tracer, "v2", FakeClock())
    check("the first run id is R-0001", run.run_id == "R-0001")
    run.timed("tool", "lookup_order maya@example.com", lambda: {"status": "ok"})
    run.timed("tool", "lookup_order", lambda: {"error": "order not found"})
    run.timed("check", "validation", lambda: [])
    run.timed("check", "validation", lambda: ["draft_reply promises a refund"])
    try:
        run.timed("model", "interactions.create", lambda: 1 / 0)
    except ZeroDivisionError:
        pass
    events = tracer.events("R-0001")
    check("five events, numbered 1 to 5", [e["step"] for e in events] == [1, 2, 3, 4, 5])
    check("every event has the Module 9 fields and the version", all(set(e) == {"run_id", "step", "kind", "name", "ms", "ok", "version"} and e["version"] == "v2" for e in events))
    check("an error result, a problem list and an exception are not ok", [e["ok"] for e in events] == [True, False, True, False, False])
    check("an email address in an event name is redacted", events[0]["name"] == "lookup_order [email]")
    check("a new tracer continues after the last run id", tracing.Run(tracing.Tracer("traces.jsonl"), "v1").run_id == "R-0002")
    with open("traces.jsonl", "a", encoding="utf-8") as file:
        file.write("this line is damaged\n")
    check("a damaged line is skipped, not fatal", len(tracer.events("R-0001")) == 5)
    check("an unknown run has no events", tracer.events("R-0042") == [])

silent = tracing.Tracer()
tracing.Run(silent, "v1").record("tool", "x", 0.0, True)
check("a tracer without a file keeps nothing and does not fail", silent.events("R-0001") == [])

Save as test_tracing.py.

Run it from inside the project folder.

TextTerminal
python test_tracing.py
OutputCaptured from a real run
PASS - redact hides an email address
PASS - redact hides a card-like number
PASS - redact leaves normal text alone
PASS - the first run id is R-0001
PASS - five events, numbered 1 to 5
PASS - every event has the Module 9 fields and the version
PASS - an error result, a problem list and an exception are not ok
PASS - an email address in an event name is redacted
PASS - a new tracer continues after the last run id
PASS - a damaged line is skipped, not fatal
PASS - an unknown run has no events
PASS - a tracer without a file keeps nothing and does not fail

Next, test_monitor.py. The first part runs the real agent with the scripted fake model over the 8 sample tickets, with ticket T-2003 rigged to fail validation twice. Then the monitor reads the trace file that the run produced.

Pythontest_monitor.py
import contextlib
import io
import json

import agent
import monitor
import run_inbox
import tracing
from fakes import PLANS, FakeClock, FakeModel, check, reply, workdir


def ev(run, step, kind, name, ms, ok=True, version="v1"):
    return {"run_id": run, "step": step, "kind": kind, "name": name, "ms": ms, "ok": ok, "version": version}


def show(runs):
    out = io.StringIO()
    with contextlib.redirect_stdout(out):
        monitor.report(runs)
    return out.getvalue()


print("--- a real fake-model run through the agent ---")
tickets = run_inbox.load_tickets()
promise = reply("other", "normal", None, [], None, "Asks.", "A full refund is on its way.")
plans = {**PLANS, "T-2003": [[("search_help", {"query": "frame size"})], promise]}  # T-2003 now fails validation twice
with workdir(seed=True):
    clock = FakeClock()
    tracer = tracing.Tracer("traces.jsonl")
    model = FakeModel(plans, clock=clock)
    for ticket in tickets:  # the fake clock makes every duration the same on every run
        agent.triage_ticket(ticket, model, "v1", tracing.Run(tracer, "v1", clock))
    events, damaged = monitor.load("traces.jsonl")
    runs = monitor.summarise(events)
    print(show(runs))
    check("8 runs, none damaged", len(runs) == 8 and damaged == 0)
    check("T-2001 is run R-0001: 2 model calls, no failures", (runs[0]["model_calls"], runs[0]["validation_failures"], runs[0]["manual"]) == (2, 0, False))
    check("run R-0003 failed validation twice and is manual", (runs[2]["validation_failures"], runs[2]["manual"]) == (2, True))
    check("model time comes from the fake clock", runs[0]["total_ms"] > 240)
    check("no run is slow, so there are no alerts", monitor.alerts(runs) == [])

Part 1 of 2. Save as test_monitor.py.

Pythontest_monitor.py
print("--- thresholds ---")
calm = monitor.summarise([ev("R-0001", 1, "model", "interactions.create", 900), ev("R-0001", 2, "check", "validation", 1)])
check("a calm system has no alerts", monitor.alerts(calm) == [])
slow = monitor.summarise([ev("R-0001", 1, "model", "interactions.create", 20001)])
check("a run over 20 seconds raises a slow alert", monitor.alerts(slow) == ["slow runs (over 20000 ms): R-0001"])
failing = monitor.summarise([ev("R-0001", 1, "model", "interactions.create", 5, ok=False), ev("R-0001", 2, "check", "manual_triage", 1, ok=False),
                             ev("R-0002", 1, "model", "interactions.create", 5)])
found = monitor.alerts(failing)
check("a failed model call raises an alert", any("failed model call" in a for a in found))
check("manual triage over the limit raises an alert", any("manual triage" in a for a in found))
bad_checks = monitor.summarise([ev("R-0001", 1, "check", "validation", 1, ok=False), ev("R-0002", 1, "check", "validation", 1)])
check("validation failures over the limit raise an alert", any("failed validation" in a for a in monitor.alerts(bad_checks)))
busy = monitor.summarise([ev("R-0001", n, "model", "interactions.create", 5) for n in range(1, 6)])
check("too many model calls per run raise an alert", any("average model calls" in a for a in monitor.alerts(busy)))
check("an empty trace has no alerts and no crash", monitor.alerts([]) == [] and "no runs found" in show([]))
print(show(failing))
check("the report prints the manual-triage rate", "manual triage: 1 of 2 runs (50.0%)" in show(failing))
check("the report prints ALERT lines", "ALERT:" in show(failing))
check("versions are reported separately", "v1: 2 runs" in show(failing))

print("--- damaged lines ---")
with workdir():
    with open("traces.jsonl", "w", encoding="utf-8") as file:
        file.write(json.dumps(ev("R-0001", 1, "model", "interactions.create", 5)) + "\nnot json\n{\"run_id\": \"R-2\"}\n")
    events, damaged = monitor.load("traces.jsonl")
    check("two damaged lines are skipped and counted", len(events) == 1 and damaged == 2)

Part 2 of 2. Add below Part 1. It tests the limits one by one.

TextTerminal
python test_monitor.py
Output of test_monitor.pyCaptured from a real run
--- a real fake-model run through the agent ---
run      version  steps  total_ms  model_calls  model_errors  validation_failures  manual
R-0001   v1           5       245            2             0                    0  no
R-0002   v1           7       367            3             0                    0  no
R-0003   v1           7       367            3             0                    2  yes
R-0004   v1           4       244            2             0                    0  no
R-0005   v1           5       245            2             0                    0  no
R-0006   v1           2       122            1             0                    0  no
R-0007   v1           4       244            2             0                    0  no
R-0008   v1           2       122            1             0                    0  no

runs: 8, median total_ms: 244, slowest: R-0002 (367 ms)
manual triage: 1 of 8 runs (12.5%)
validation failures: 2 in total, model calls: 16 in total
v1: 8 runs, manual 1, validation failures 2
No alerts.

PASS - 8 runs, none damaged
PASS - T-2001 is run R-0001: 2 model calls, no failures
PASS - run R-0003 failed validation twice and is manual
PASS - model time comes from the fake clock
PASS - no run is slow, so there are no alerts
--- thresholds ---
PASS - a calm system has no alerts
PASS - a run over 20 seconds raises a slow alert
PASS - a failed model call raises an alert
PASS - manual triage over the limit raises an alert
PASS - validation failures over the limit raise an alert
PASS - too many model calls per run raise an alert
PASS - an empty trace has no alerts and no crash
run      version  steps  total_ms  model_calls  model_errors  validation_failures  manual
R-0001   v1           2         6            1             1                    0  yes
R-0002   v1           1         5            1             0                    0  no

runs: 2, median total_ms: 6, slowest: R-0001 (6 ms)
manual triage: 1 of 2 runs (50.0%)
validation failures: 0 in total, model calls: 2 in total
v1: 2 runs, manual 1, validation failures 0
ALERT: 1 of 2 runs with a failed model call (limit 10%)
ALERT: 1 of 2 runs ended in manual triage (limit 20%)

PASS - the report prints the manual-triage rate
PASS - the report prints ALERT lines
PASS - versions are reported separately
--- damaged lines ---
PASS - two damaged lines are skipped and counted

Read the first table. Run R-0003 shows validation_failures 2 and manual yes. That is the rigged ticket. Its trace has seven steps: three model calls and two failed validations. The summary says one run out of eight went to manual triage (12.5%), which is under the 20% limit, so there are no alerts. In the second table the same kinds of numbers are over the limits, and two ALERT: lines appear.

Now test_service.py, the biggest test. It sends real HTTP requests to the real service. The parts follow the order of the output.

Pythontest_service.py
import json
import os
import threading

import approvals
import rollback
import run_inbox
from fakes import PLANS, FakeClock, FakeModel, Harness, check, reply, workdir

TOKEN = "test-token-123"  # a made-up token, only for these tests
TICKETS = {t["ticket_id"]: t for t in run_inbox.load_tickets()}
PROMISE = reply("order", "normal", None, [], None, "Asks.", "A full refund is on its way.")
PLANS = {**PLANS, "T-5001": [PROMISE], "T-5002": "error"}
TICKETS["T-5001"] = {**TICKETS["T-2001"], "ticket_id": "T-5001"}
TICKETS["T-5002"] = {**TICKETS["T-2001"], "ticket_id": "T-5002"}


def lines(path):
    with open(path, encoding="utf-8") as file:
        return [json.loads(line) for line in file]


os.environ["REVIEW_TOKEN"] = TOKEN
with workdir(seed=True):
    clock = FakeClock()
    app = Harness(FakeModel(PLANS, clock=clock), clock)

    print("--- health and one ticket ---")
    check("health says ok and names the active version", app.call("GET", "/health") == (200, {"ok": True, "version": "v1"}))
    status, body = app.post_ticket(TICKETS["T-2001"])
    check("a ticket gets run id R-0001 and a triage record", status == 200 and body["run_id"] == "R-0001" and body["triage"]["queue"] == "orders_team")
    check("the record carries version v1 and is not manual", (body["triage"]["version"], body["triage"]["manual"]) == ("v1", False))
    status, events = app.call("GET", "/runs/R-0001")
    check("the trace is model, tool, tool, model, check", [e["kind"] for e in events] == ["model", "tool", "tool", "model", "check"])
    check("steps are numbered and carry the version", [e["step"] for e in events] == [1, 2, 3, 4, 5] and {e["version"] for e in events} == {"v1"})
    check("the tool steps are named after the tools", [e["name"] for e in events[1:3]] == ["lookup_order", "search_help"])
    check("the trace file holds no email address", "@" not in open("traces.jsonl", encoding="utf-8").read())

Part 1 of 4. Save as test_service.py. Setup, then one ticket and its trace.

Pythontest_service.py
print("--- the approval flow over HTTP ---")
status, queue = app.call("GET", "/approvals")
check("the draft waits in the queue as a pending send_reply", status == 200 and [(i["approval_id"], i["action"], i["status"]) for i in queue] == [("A-0001", "send_reply", "pending")])
check("nothing is in the outbox yet", not os.path.exists(approvals.OUTBOX))
decision = {"decision": "approve", "reviewer": "Dana", "note": "ok"}
check("a decision without the token is refused with 401", app.call("POST", "/approvals/A-0001", decision)[0] == 401)
check("a decision with a wrong token is refused with 403", app.call("POST", "/approvals/A-0001", decision, token="wrong")[0] == 403)
check("the item is still pending and the outbox is still empty", approvals.load()[0]["status"] == "pending" and not os.path.exists(approvals.OUTBOX))
status, body = app.call("POST", "/approvals/A-0001", decision, token=TOKEN)
check("the right token approves the item", status == 200 and body["approval"]["status"] == "approved")
check("exactly one outbox line, signed by the reviewer", [l["approved_by"] for l in lines(approvals.OUTBOX)] == ["Dana"])
check("deciding again gives 409", app.call("POST", "/approvals/A-0001", decision, token=TOKEN)[0] == 409)
check("the queue is empty again", app.call("GET", "/approvals")[1] == [])
check("an unknown approval gives 404", app.call("POST", "/approvals/A-0099", decision, token=TOKEN)[0] == 404)
app.post_ticket(TICKETS["T-2003"])
check("a missing reviewer gives 400", app.call("POST", "/approvals/A-0002", {"decision": "approve", "reviewer": " "}, token=TOKEN)[0] == 400)
check("a bad decision gives 400", app.call("POST", "/approvals/A-0002", {"decision": "maybe", "reviewer": "Dana"}, token=TOKEN)[0] == 400)
status, body = app.call("POST", "/approvals/A-0002", {"decision": "reject", "reviewer": "Dana", "note": "Too short."}, token=TOKEN)
check("a rejection is stored and sends nothing", body["approval"]["status"] == "rejected" and len(lines(approvals.OUTBOX)) == 1)
del os.environ["REVIEW_TOKEN"]
check("without a server token nobody can decide (503)", app.call("POST", "/approvals/A-0002", decision, token=TOKEN)[0] == 503)
os.environ["REVIEW_TOKEN"] = TOKEN

print("--- the safety rules over HTTP ---")
body = app.post_ticket(TICKETS["T-2004"])[1]["triage"]
check("a safety ticket is high urgency for the safety team", (body["urgency"], body["queue"]) == ("high", "safety_team"))
body = app.post_ticket(TICKETS["T-2008"])[1]["triage"]
check("the injection ticket gets no refund promise", "refund" not in body["draft_reply"].lower() and body["queue"] == "support_team")
check("and still nothing new reached the outbox", len(lines(approvals.OUTBOX)) == 1)
app.post_ticket(TICKETS["T-2002"])
returns = [i for i in app.call("GET", "/approvals")[1] if i["action"] == "create_return"]
check("a return ticket queues a create_return item", len(returns) == 1)
app.call("POST", "/approvals/" + returns[0]["approval_id"], decision, token=TOKEN)
check("approving it creates one return record", list(json.load(open(approvals.RETURNS, encoding="utf-8"))) == ["QF-1044:wrong_size"])

Part 2 of 4. The approval flow, then the safety rules.

Pythontest_service.py
print("--- failures become manual triage, not crashes ---")
status, body = app.post_ticket(TICKETS["T-5001"])
check("two bad answers: 200 with manual triage", status == 200 and body["triage"]["manual"] and body["triage"]["draft_reply"] == "")
events = app.call("GET", "/runs/" + body["run_id"])[1]
check("the trace shows two failed validations, then manual_triage",
      [(e["name"], e["ok"]) for e in events if e["kind"] == "check"] == [("validation", False), ("validation", False), ("manual_triage", False)])
status, body = app.post_ticket(TICKETS["T-5002"])
events = app.call("GET", "/runs/" + body["run_id"])[1]
check("a model failure: 200 with manual triage", status == 200 and body["triage"]["manual"] and "model error" in body["triage"]["summary"])
check("the trace shows the failed model call", [(e["kind"], e["ok"]) for e in events][:1] == [("model", False)])

print("--- clear JSON errors ---")
check("bad JSON gives 400", app.call("POST", "/tickets", raw=b"{not json")[0] == 400)
check("a JSON list gives 400", app.call("POST", "/tickets", raw=b"[1, 2]")[0] == 400)
check("a missing field gives 400", app.call("POST", "/tickets", {"ticket_id": "T-2001"})[0] == 400)
check("a bad email gives 400", app.post_ticket({**TICKETS["T-2001"], "customer_email": "maya"})[0] == 400)
check("a bad date gives 400", app.post_ticket({**TICKETS["T-2001"], "received": "2026-13-45T99:99"})[0] == 400)
check("a very long body gives 400", app.post_ticket({**TICKETS["T-2001"], "body": "x" * 5001})[0] == 400)
check("an oversized request gives 413", app.call("POST", "/tickets", raw=b" " * 10001)[0] == 413)
check("an unknown path gives 404", app.call("GET", "/nothing")[0] == 404 and app.call("POST", "/nothing", {})[0] == 404)
check("an unknown run gives 404", app.call("GET", "/runs/R-9999")[0] == 404 and app.call("GET", "/runs/../x")[0] == 404)
check("a wrong method gives 405", app.call("DELETE", "/tickets")[0] == 405)

print("--- several requests at once ---")
answers = []
names = ["T-2001", "T-2003", "T-2004", "T-2006"]
threads = [threading.Thread(target=lambda n=n: answers.append(app.post_ticket(TICKETS[n]))) for n in names]
before = len(approvals.load())
for thread in threads:
    thread.start()
for thread in threads:
    thread.join()
check("four parallel tickets all succeed", sorted(s for s, _ in answers) == [200] * 4)
check("each got its own run id", len({b["run_id"] for _, b in answers}) == 4)
ids = [i["approval_id"] for i in approvals.load()]
check("each draft got its own approval id", len(ids) == before + 4 and len(set(ids)) == len(ids))

Part 3 of 4. Failures, bad requests and parallel requests.

Pythontest_service.py
print("--- release a version and roll back ---")
rollback.main(["v2"], app.version_file)
check("health shows v2 straight away", app.call("GET", "/health")[1]["version"] == "v2")
run_id = app.post_ticket(TICKETS["T-2001"])[1]["run_id"]
check("the new run is labelled v2", {e["version"] for e in app.call("GET", "/runs/" + run_id)[1]} == {"v2"})
check("rollback.py refuses an unknown version", rollback.main(["v9"], app.version_file) == 1 and open(app.version_file).read() == "v2\n")
rollback.main(["v1"], app.version_file)
check("rollback to v1 shows in health", app.call("GET", "/health")[1] == {"ok": True, "version": "v1"})
check("the next run is labelled v1 again", app.post_ticket(TICKETS["T-2001"])[1]["triage"]["version"] == "v1")
with open(app.version_file, "w") as file:
    file.write("v7\n")
check("a damaged version file fails closed with 500", app.call("GET", "/health")[0] == 500 and app.post_ticket(TICKETS["T-2001"])[0] == 500)
rollback.main(["v1"], app.version_file)
check("rollback.py repairs it", app.call("GET", "/health")[0] == 200)
app.stop()

Part 4 of 4. Version change and rollback.

What each part does

  • The made-up TOKEN is set in the environment for the test only. The real token never goes into a file.
  • The health, ticket and trace checks prove R8: the trace is model, tool, tool, model, check, every step has a number and the version, and the file holds no @.
  • The approval checks prove R5 over HTTP: no token gives 401, a wrong token gives 403, and neither changes the queue or the outbox. The right token writes exactly one line signed by the reviewer. A repeat gives 409.
  • The safety checks send the safety ticket T-2004 and the injection ticket T-2008 through the service. The safety ticket stays high urgency for the safety team, and the injection ticket gets no refund promise.
  • The failure checks rig the fake model: two bad answers, then a model that raises an error. Both give 200 with manual triage and a trace that shows why.
  • Bad JSON, a JSON list, missing fields, a bad email, a bad date, a long body and an oversized request each give a clear error code. Four tickets at once all succeed with different run ids.
  • The last part switches to v2 and back, then breaks active_version.txt on purpose. The service fails closed with 500, and rollback.py repairs it.
TextTerminal
python test_service.py
Output of test_service.pyCaptured from a real run
--- health and one ticket ---
PASS - health says ok and names the active version
PASS - a ticket gets run id R-0001 and a triage record
PASS - the record carries version v1 and is not manual
PASS - the trace is model, tool, tool, model, check
PASS - steps are numbered and carry the version
PASS - the tool steps are named after the tools
PASS - the trace file holds no email address
--- the approval flow over HTTP ---
PASS - the draft waits in the queue as a pending send_reply
PASS - nothing is in the outbox yet
PASS - a decision without the token is refused with 401
PASS - a decision with a wrong token is refused with 403
PASS - the item is still pending and the outbox is still empty
PASS - the right token approves the item
PASS - exactly one outbox line, signed by the reviewer
PASS - deciding again gives 409
PASS - the queue is empty again
PASS - an unknown approval gives 404
PASS - a missing reviewer gives 400
PASS - a bad decision gives 400
PASS - a rejection is stored and sends nothing
PASS - without a server token nobody can decide (503)
--- the safety rules over HTTP ---
PASS - a safety ticket is high urgency for the safety team
PASS - the injection ticket gets no refund promise
PASS - and still nothing new reached the outbox
PASS - a return ticket queues a create_return item
PASS - approving it creates one return record
--- failures become manual triage, not crashes ---
PASS - two bad answers: 200 with manual triage
PASS - the trace shows two failed validations, then manual_triage
PASS - a model failure: 200 with manual triage
PASS - the trace shows the failed model call
--- clear JSON errors ---
PASS - bad JSON gives 400
PASS - a JSON list gives 400
PASS - a missing field gives 400
PASS - a bad email gives 400
PASS - a bad date gives 400
PASS - a very long body gives 400
PASS - an oversized request gives 413
PASS - an unknown path gives 404
PASS - an unknown run gives 404
PASS - a wrong method gives 405
--- several requests at once ---
PASS - four parallel tickets all succeed
PASS - each got its own run id
PASS - each draft got its own approval id
--- release a version and roll back ---
active version: v1 -> v2
PASS - health shows v2 straight away
PASS - the new run is labelled v2
usage: python rollback.py v1|v2
PASS - rollback.py refuses an unknown version
active version: v2 -> v1
PASS - rollback to v1 shows in health
PASS - the next run is labelled v1 again
PASS - a damaged version file fails closed with 500
active version: unknown -> v1
PASS - rollback.py repairs it

The lines active version: v1 -> v2 and active version: v2 -> v1 are printed by rollback.py, which the test calls. The line usage: python rollback.py v1|v2 appears because the test asks for an unknown version on purpose. None of them is a failure.

Run every test, old and new

The earlier rules must still hold after your changes. Run all eleven files, for example python test_tools.py. Here are the counts from a real run of the tested code. The eight older files print the same lines as before.

Test filePASS linesWhat it protects
test_tools.py16Tools are bound to the ticket's customer
test_triage.py17Record format and routing in code (R1 to R3)
test_memory.py14Own-customer history and the 90-day purge (R6)
test_validate.py17The output checks
test_approvals.py21Approval rules and the outbox (R5)
test_agent.py28The agent loop, retry and the budget (R7, N2)
test_eval.py27The scorer and the release rule
test_runner.py22The evaluation runner
test_tracing.py12Trace format and redaction (R8, N3)
test_monitor.py16Summaries and alerts (N1)
test_service.py50Endpoints, token, errors, rollback
Total: 240 PASS and no FAIL. Each file gave identical output on two runs.

Step 9: Run the service on your computer

First, a check that needs no real key. check_service_key.py starts the service with a dummy key and sends one ticket. The Google call must fail. What matters is that the service does not crash: it answers 200, the record is manual and the trace shows the failed model step. The script also makes one direct call, so you see Google's own message. It needs internet.

Pythoncheck_service_key.py
import os

os.environ["GEMINI_API_KEY"] = "dummy-key-not-real"  # must be set before the client is made

from google import genai

import run_inbox
import versions
from fakes import Harness, workdir

client = genai.Client()
ticket = run_inbox.load_tickets()[0]
with workdir(seed=True):
    app = Harness(client)  # the real service with the real client and a dummy key
    status, body = app.post_ticket(ticket)
    print("status:", status)
    print("manual:", body["triage"]["manual"], "|", body["triage"]["summary"])
    for event in app.call("GET", "/runs/" + body["run_id"])[1]:
        print("trace:", event["kind"], event["name"], "ok =", event["ok"])
    app.stop()
try:
    client.interactions.create(model=versions.MODEL, input="hi")
except Exception as error:
    print("Google said:", str(error)[:108])

Save as check_service_key.py.

TextTerminal
python check_service_key.py
Output with the dummy keyCaptured from a real run
status: 200
manual: True | Automatic triage failed: model error (BadRequestError)
trace: model interactions.create ok = False
trace: check manual_triage ok = False
Google said: Error code: 400 - [{'error': {'code': 400, 'message': 'API key not valid. Please pass a valid API key.', 'st

The name of the error class (BadRequestError) depends on your SDK version. Without internet, the last line looks different, because the network fails first. Both are fine.

Start the service for real

Put your key in .env as in the earlier labs. Set the review token in the same terminal where you start the service. Use a long random text and never write it in a file that goes to git. In PowerShell:

TextTerminal 1 (PowerShell)
$env:REVIEW_TOKEN = "choose-a-long-random-text"
python service.py

The service prints Listening on http://127.0.0.1:8000 (press Ctrl+C to stop). Leave it running. If Windows shows a firewall question, remember that the service only listens on this computer, so you can cancel or choose a private network. Open a second terminal in the same folder and set the same token there too, because the reviewer call needs it.

TextTerminal 2 (PowerShell)
$env:REVIEW_TOKEN = "choose-a-long-random-text"
Invoke-RestMethod http://127.0.0.1:8000/health
$ticket = Get-Content inbox.jsonl | Select-Object -First 1
Invoke-RestMethod -Method Post -Uri http://127.0.0.1:8000/tickets -ContentType "application/json" -Body $ticket | ConvertTo-Json -Depth 5
Invoke-RestMethod http://127.0.0.1:8000/approvals | ConvertTo-Json -Depth 5
Illustrative output with a real model (yours will differ)Illustrative — your output will differ
{"ok": true, "version": "v1"}

{
  "run_id": "R-0001",
  "triage": {
    "category": "order",
    "urgency": "normal",
    "order_id": "QF-1042",
    "sources": ["KB-02"],
    "return_reason": null,
    "summary": "Customer asks when dispatched order QF-1042 will arrive.",
    "draft_reply": "Your order QF-1042 was dispatched and should arrive by 2026-11-18 (KB-02).",
    "ticket_id": "T-2001",
    "queue": "orders_team",
    "version": "v1",
    "manual": false
  }
}

[{"approval_id": "A-0001", "ticket_id": "T-2001", "action": "send_reply", "status": "pending", ...}]

The draft is waiting, and outbox.jsonl does not exist yet. Now a named person approves it. Use your own name as the reviewer.

TextTerminal 2 (PowerShell)
Invoke-RestMethod -Method Post -Uri http://127.0.0.1:8000/approvals/A-0001 -Headers @{"X-Review-Token" = $env:REVIEW_TOKEN} -ContentType "application/json" -Body '{"decision": "approve", "reviewer": "Your Name", "note": "ok"}'
Get-Content outbox.jsonl
Invoke-RestMethod http://127.0.0.1:8000/runs/R-0001 | ConvertTo-Json
Illustrative trace of the run (times will differ)Illustrative — your output will differ
run_id step kind  name                ms   ok   version
R-0001 1    model interactions.create 1840 True v1
R-0001 2    tool  lookup_order        1    True v1
R-0001 3    tool  search_help         2    True v1
R-0001 4    model interactions.create 1520 True v1
R-0001 5    check validation          1    True v1

Try the approval again. It must fail with 409, because an item can be decided only once. Try it without the header. It must fail with 401. Then let the monitor read what the service wrote.

TextTerminal
python monitor.py traces.jsonl

After a few tickets, the monitor prints a table like the one from test_monitor.py in Step 8, with your own times. Real model calls take seconds, not the 120 ms of the fake clock. Read the median and the slowest run against the 20-second limit of N1. Stop the service with Ctrl+C in the first terminal.

Step 10: Practise a rollback

Pretend that v2 went live and the monitor now shows alerts that began with it. You will go back to v1 and prove it worked. This is the exercise behind N4: the whole thing should take under 5 minutes when you follow the runbook, so time yourself.

  1. Step 1: Note the time and the bad version.

    Run python monitor.py traces.jsonl. The last lines show the counts per version and any ALERT: lines. Write down which version raised them.

  2. Step 2: Switch the version.

    Run python rollback.py v2 to make the pretend release, then python rollback.py v1 to roll back. The service reads the file on each request, so no restart is needed.

  3. Step 3: Check health.

    Call GET /health. It must show the old version.

  4. Step 4: Prove it with one ticket.

    Send one test ticket and read its trace with GET /runs/<run_id>. Every line must carry the old version label.

  5. Step 5: Write it down.

    Record the time, the reason and the run ids in rollback-log.txt, and the number of minutes it took.

Here is the real output of rollback.py, run in a copy of the project. The third run uses a version name that does not exist, so the file is not changed.

Output of three rollback.py runs: v2, v1 and v3Captured from a real run
active version: v1 -> v2
active version: v2 -> v1
usage: python rollback.py v1|v2

Step 11: Write the four documents

Code that only its author can run is not finished. Four short documents make the project usable by someone else, and the reviewer reads them in Final Demonstration and Technical Review. The files below are from the tested project and are about the Quillfeather Triage Desk. They are shown as selections, because the full files are longer. You write your own versions for your own option, with your own facts. Where a document has <...>, fill it in. Do not invent names of real people. Write roles, and put in a real name only if you know one.

README.md: what it is and how to run it

The README answers three questions fast: what is this, how do I start it and what are its limits. Its second paragraph says that this is a controlled test environment.

MarkdownREADME.md
# Quillfeather Triage Desk

A customer-support triage agent for the fictional shop Quillfeather Cycles. It reads a support ticket, decides the
category and urgency, picks the team with code, and prepares a draft reply. A named person must approve every draft
and every return before anything happens. Nothing is really sent: the "outbox" is a file.

This is a controlled test environment. It uses made-up data, one computer and no real customers. See "What production would need".

## What it does

1. `POST /tickets` takes a ticket. Code adds the customer's last cases (at most 3, from the last 90 days).
2. The model may call three tools: `lookup_order`, `search_help` and `request_return`. Code binds the tools to the ticket's own customer.
3. Code checks the answer (`validate.py`). It retries once, then hands the ticket to a person (manual triage).
4. Code sets the queue from a fixed table. A safety ticket is always urgency high and goes to the safety team.
5. The draft becomes a pending item in the approval queue. A reviewer approves or rejects it with `POST /approvals/<id>`.
6. Every run writes a trace (`traces.jsonl`) with the version label. `monitor.py` summarises the traces and raises alerts.

README.md, the first part.

MarkdownREADME.md
## Limits you should know

- Version v1 and v2 differ only in the instructions. v2 adds one rule found by the evaluation.
- The refund-promise check is a short pattern list. It is a weak signal and misses reworded promises.
- Case history is seeded by hand. A real system would also write a case when it closes.
- The out-of-scope list: refunds, sending without approval, changing addresses or orders, phone and chat, languages other than English, staff-only pages.

## What production would need

HTTPS, real authentication for reviewers (not one shared token), a process manager that restarts the service,
a real email system behind the outbox, a real order database, backups, log shipping, and a privacy review.

README.md, the last part: honest limits and what production would need.

RUNBOOK.md: what to do when the alarm rings

A runbook is for the moment when something is wrong, so every step must be one action that someone can follow without thinking. The table maps each alert text to its meaning and first action. The rollback steps are numbered. The full file also has a start section, a health table, an escalation table by role and a note on what to write after an incident.

MarkdownRUNBOOK.md
## 4. Alerts and what to do

| Alert text | What it means | First action |
|---|---|---|
| `slow runs (over 20000 ms)` | A ticket took longer than 20 seconds (requirement N1) | Check Google's status page and your network. If it keeps happening, tell the service owner |
| `runs with a failed model call` | The model could not be reached or refused the call | Check the key, the model name in `versions.py` and the quota. Affected tickets are already in manual triage |
| `runs ended in manual triage` | Automatic triage fails too often | Look at the latest runs: `GET /runs/<run_id>`. If it started after a release, roll back |
| `runs failed validation` | The model's answers break the checks | Same as above. Read which check failed in the manual summary |
| `average model calls per run` | Retries or tool loops are rising | Roll back if it started after a release. Tell the service owner |

An alert is a prompt to look, not a proof of a fault. A few runs are a small sample.

## 5. Roll back (target: under 5 minutes)

1. Run `python monitor.py traces.jsonl` and note which version raised the alert.
2. Run `python rollback.py v1` (or the previous version). It prints `active version: v2 -> v1`.
3. Check `GET /health`. It must show the old version. No restart is needed.
4. Send one test ticket. Its trace (`GET /runs/<run_id>`) must show the old version label.
5. Write down the time, the reason and the run ids in your notes. Run the evaluation on the bad version before you try again.

RUNBOOK.md, alerts and rollback.

THREAT_MODEL.md: what can go wrong and what is left

A threat model lists what you protect, how an attacker or a mistake could reach it, what you did about it and whether it is done. It carries on from the first rows you wrote in Design Architecture, Tools, Data and Permissions. The full table has 16 rows. The rows that matter most for the service are the token, the traces and the version file. Here are the first rows, then the end of the file with the residual-risk statement.

MarkdownTHREAT_MODEL.md
# Threat model: Quillfeather Triage Desk

Scope: the service, the agent, the tools, the data files and the review step, as run in a controlled test environment.

| asset | entry point | threat | mitigation | status |
|---|---|---|---|---|
| Customer's order data | Ticket text asking for another customer's order | The agent reveals someone else's order | `lookup_order` is bound to the ticket's email in code. The answer for a foreign order is the same as for an unknown order. `validate.py` blocks order ids that are not the customer's | Done, tested |
| Customer's order data | The model's tool arguments | The model asks for an order it should not see | `run_tool` checks the argument names, the id format and the owner before any data is read | Done, tested |

THREAT_MODEL.md, the opening and the first rows.

MarkdownTHREAT_MODEL.md
After these controls the main risks that remain are:

1. A reviewer approves a draft that is wrong. The checks lower the chance but a person still has to read it.
2. A reworded refund promise passes the pattern list. Reviewers are the last defence here.
3. The model picks a wrong category for an unusual ticket. Routing is correct for the category given, and safety words have an evaluation case, but 25 cases are a small sample.
4. One shared review token cannot show which person approved. The reviewer name is typed, not verified.
5. The evaluation used a small made-up dataset. Real tickets will differ.

This system should not be used with real customers until these risks are accepted by the people responsible, HTTPS and real
authentication are added, and a pilot with staff has measured how often drafts are approved without edits.

THREAT_MODEL.md, the residual-risk statement.

Residual risk is the risk that remains after all your controls. A statement that says there is none is not believable. The statement above names five things that can still go wrong, says who is the last defence and ends with a clear condition for real use.

EVALUATION_REPORT.md: the honest numbers

This file comes from Test with Evaluation Scenarios and Adversarial Inputs. Add the real numbers from your own run. The results table and the release rule are shown here as the template with placeholders. Do not round up, and do not hide failing cases.

MarkdownEVALUATION_REPORT.md
|---|---|---|---|
| Category accuracy | `<h/t>` | `<x.x%>` | at least 80.0% |
| Queue accuracy | `<h/t>` | `<x.x%>` | none (reported) |
| Tool-selection accuracy | `<h/t>` | `<x.x%>` | none (reported) |
| Must-include rate | `<h/t>` | `<x.x%>` | none (reported) |
| Safety recall | `<h/t>` | `<x.x%>` | 100% |
| Approval violations (outbox lines) | `<n>` | n/a | 0 |
| Adversarial cases defended | `<h/t>` | `<x.x%>` | none (reported) |

## 3. Release rule

- [ ] Safety recall is 100%
- [ ] Approval violations are 0
- [ ] No must_pass case broke compared with the previous version
- [ ] Category accuracy is at least 80.0%

Decision: `<RELEASE or BLOCK>`. Reason in one sentence: `<...>`

EVALUATION_REPORT.md, the results table and the release rule.

How the service supports your five demonstration scenes

The demonstration in Final Demonstration and Technical Review has five scenes. The service you built has what each scene needs. Practise them now. Use the fake model for the scenes where you need a repeatable result.

SceneWhat you callWhere the proof is
1. Health and versionGET /health and active_version.txt{"ok": true, "version": "v1"}
2. A normal ticket to the outboxPOST /tickets with T-2001, GET /approvals, then POST /approvals/A-0001 with the tokenOne line in outbox.jsonl with the reviewer's name. A second approval gives 409
3. A safety ticketPOST /tickets with T-2004Urgency high, queue safety_team, set by code. The draft still waits for approval
4. An injection containedPOST /tickets with T-2008, then GET /runs/<run_id>No refund promise and no outbox line. The trace shows what the agent did
5. A bad version rolled backpython monitor.py traces.jsonl, python rollback.py v1, GET /healthALERT: lines, then active version: v2 -> v1 and the old version in health

A controlled test environment, and what production would add

Your service is a good model of the real thing, and it is not the real thing. Say this plainly in your README and in your demonstration. A reviewer trusts someone who knows the limits.

In this labWhat real production would add
Plain HTTP on 127.0.0.1, one computerHTTPS, so that traffic and the token cannot be read on the way
One shared review tokenA real login for each reviewer, with roles, expiry and a record of who did what
You start it by hand and stop it with Ctrl+CA process manager that restarts it after a crash and starts it after a reboot
outbox.jsonl, a file that stands in for sendingA real email system, with its own checks, and a plan for failed deliveries
JSON files for orders, approvals and historyA real database, backups and a tested way to restore them
traces.jsonl on one diskSafe central storage for logs, with access control and a retention rule
Made-up customersA privacy review, a pilot with staff and sign-off from the people responsible
This is general guidance. The details depend on where and how you would run it.

The same warning is in Practical Lab: Deploy and Monitor an Agent Service. Both labs give you the method. Neither gives you a launch plan.

If you chose a different option

The worked example shows the method. You must apply it to your own option. Copying the Triage Desk is not a capstone. The service has the same shape for every option. Only the intake, the thing to approve and the alerts change.

Your optionYour intake endpointWhat needs a guarded approvalAn alert worth adding
1. Documentation research agentPOST /questions with a questionPublishing or sharing a summaryAnswers without a citation
3. Developer issue-analysis agentPOST /issues with an issueApplying proposed labels or commentsA secret-like text found in output
4. Claims-document review assistantPOST /claims with a claimThe recommendation going outPersonal data found in traces
5. Cloud-cost investigation agentPOST /investigations with a cost questionAny proposed change to a resourceRuns that take too long or cost too much
Option 2 is the worked example. Every option needs health, a trace with a version label, a monitor, a rollback and the four documents.

Conclusion and your next step

Your agent is now a small service. Each run has an id, a version label and a trace without sensitive text. A monitor turns traces into numbers and alerts. The approval endpoint needs a token, so a decision needs a named person. A version switch lets you roll back in seconds. And four documents let someone else run it, operate it, question it and judge it. You also learned to read the request body before answering, which makes the service behave the same way every time.

Remember what it is: a controlled test environment. It shows the method. A real launch would still need HTTPS, real logins, a process manager, a real email system and backups.

Your next step: run all eleven test files, practise the rollback with a timer, fill in your four documents and rehearse the five scenes. Then continue to Final Demonstration and Technical Review.

Common errors and how to fix them

OSError: [WinError 10048] Only one usage of each socket address is normally permitted, or Address already in use.

Why it happens: An earlier copy of service.py is still running and holds port 8000.

Fix: Stop it with Ctrl+C in its terminal, or close that terminal. The tests do not have this problem, because they ask for any free port.

Approving gives 503 with "REVIEW_TOKEN is not set on the server", or 401 although you think you sent a token.

Why it happens: The token was set in a different terminal from the one that started the service, or after it started. The service reads the variable of its own terminal. A 401 means the header was missing.

Fix: Set $env:REVIEW_TOKEN first, then start the service. Set it in the second terminal too, and send it in the header X-Review-Token.

FileNotFoundError: No such file or directory: 'inbox.jsonl' (or 'traces.jsonl').

Why it happens: You started the script from the wrong folder. The files use relative names, so they are looked up in the current folder. traces.jsonl also does not exist until the service has handled a ticket.

Fix: Open the terminal in the project folder before you run anything, and check with dir. Send one ticket before you run the monitor.

Windows asks whether to allow Python through the firewall.

Why it happens: A program started to listen on a network port. This service listens on 127.0.0.1 only, so it is not open to other computers.

Fix: You can cancel, or allow it on private networks only. Never allow public access for this test service.

Every request returns 500 with "unknown version" or "is missing".

Why it happens: active_version.txt was deleted or holds a name that is not v1 or v2.

Fix: Run python rollback.py v1. The service fails closed on purpose, and the rollback repairs the file.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Deploy, monitor and document your own capstone

Apply the steps of this lesson to your own capstone option: add the service, traces, monitor, version switch and rollback, then write your four documents.

You will need

  • Your finished stage 5 project with passing tests and an evaluation report.
  • The worked example files of this lesson as a pattern, not to copy.
  • Your own list of what the approval step must guard.

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • Copy the shape of the tests first. A failing test is the best way to find a missing rule.
  • Test the rollback on a copy of the folder before you do it in front of anyone.
  • Ask someone to follow your runbook without your help. Every place where they stop is a sentence to fix.
Show a model answer

A good answer has a service that starts with one command, a token check with the right codes, traces without sensitive text and a monitor whose alerts you can trigger with a rigged fake model. The rollback is a single command that prints the change, and health shows the old version at once. The runbook is short, with one action per step and roles instead of invented names. The threat model has a row for the token and a residual-risk statement that names real remaining problems, such as a shared token and a small test set. The documents say clearly that the environment is for testing, and list HTTPS, real login, a process manager, a real email system and backups as what production would add.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.Why does the approval endpoint check a token?
    Show the answer and explanation

    Answer: B. The token guards the one door that can change the outbox. It does not speed anything up, and the model never sees it. A shared token is still weak, because it does not show who is calling.

  2. 2.The service sent an error before it had read the request body, and clients sometimes saw a network reset. What is the fix?
    Show the answer and explanation

    Answer: A. A reply sent while the client is still sending can close the connection and hide the message. Reading first makes the order fixed. A larger limit or retries only hide the problem.

  3. 3.The monitor shows alerts that started right after v2 went live. What do you do first?
    Show the answer and explanation

    Answer: B. Rolling back is quick and safe, and the trace proves that the old version is live. Deleting the traces destroys the evidence. Waiting leaves customers with a bad version.

Frequently asked questions

How do I deploy a small AI agent as a web service?

Wrap the agent in a service that has endpoints for the request, for approvals, for traces and for health. Give each run an id, write a redacted trace with a version label, read the active version from a file and test everything offline with a fake model before you use a real key.

Is a shared review token enough to secure approvals?

It is enough for a test environment, because it keeps casual callers out. It is not real authentication. It cannot tell who is calling, it never expires and over plain HTTP it can be read. Real systems use individual logins, HTTPS and an audit trail.

What should a runbook for an AI agent contain?

How to start and stop it, how to check health, what each alert means and the first action, the exact rollback steps, who to tell by role and what to write after an incident. Keep every step to one action, so a tired person can follow it.

What does residual risk mean in a threat model?

It is the risk that remains after all your controls. For example, a reviewer might approve a wrong draft, or a reworded refund promise might pass a pattern check. Writing it down honestly shows what the system should not be trusted with yet.

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.

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.