AI Agents in Production Bootcamp
Put an AI agent into a real business, and keep it there. One fictional repair company, two agents on the same stack — a requester intake agent and a field-technician assistant — built step by step and run for real: metrics, model access, knowledge, guardrails, downstream writes, security, evaluation, observability and operations, with the pitfalls that only show up in production.
- Lessons
- 32
- Time
- About 20 hours
- Level
- Advanced
- Homework
- 32 assignments
What you'll use
Curriculum
Lessons 1–1010 lessons
- 1
S1: Define “It Helped” First — Problem Definition and Business Metrics for an AI Agent
Before evals, dashboards or alarms, decide what "the agent helped" means: outcomes by what the user did (exact vs estimated), two deflection formulas that are never merged (work orders saved 28.0%, truck rolls saved 12.6%, 16.4% with an asset-tag repeat key), and how the same 300 sessions can be reported as anything from 28% to 54%.
- 2
S2: Model Access — Inference Profiles, Cross-Account Roles and Keyless CI
Model access for an AI agent in production: one getModel() seam for the Anthropic API and Amazon Bedrock (application inference profile ARN, AssumeRole credentials), a request profile per model family, and a startup check that refuses a wrong model/family pair. Measured: the AI SDK silently drops a rejected setting given a model id and sends it unchanged given an ARN (HTTP 400 in 190 ms); keyless CI and the model migration trap.
- 3
S3: Permissions Changed Outside Your Repo — A Post-Mortem of a Silent Outage
A post-mortem of a full outage nobody was alerted to: an organization policy denied every model call of an AI agent for 74 minutes and no alarm fired. Why the startup check stayed green, why a filter on a missing field reads zero, why a streamed turn says HTTP 200, and how Ironline pages one person in one minute with the cause and a runbook.
- 4
S4: The Outermost Hop Sets the Request Budget — the Deployment Skeleton and Long-Running Work
A model turn takes seconds, a downstream AI job takes minutes, and the outermost hop decides how long either may run. Why the CDN in front owns the request budget, how a synth-time timeout chain refuses the wrong-knob fix, how long work leaves the request with after() and a database row, and how a SIGTERM drain, start-before-stop deploys, backward-compatible migrations and a refresh answer for stale tabs keep a deploy from cutting requests — measured on Ironline step-07b and step-17.
- 5
A1: The Agent Stages, Code Commits — Keeping Irreversible Writes in Deterministic Code
Never let the model create the ticket: a stage-only tool with every field enforced in code, a confirm route where three confirms make one work order (201, 200, 200), a server guard that rewrites false "your ticket has been created" replies (and its own live miss), and duplicates decided by asset tag and policy leaf — 6 of 6 traps right, where a title rule would refuse 3 real reports.
- 6
A2: Prompts Are Code — Persona Modules, Per-Persona Tools, Snapshots and a Size Budget
Treat the system prompt as code: markdown modules compiled in with a freshness test, personas whose tool registration throws on a stray tool, five snapshots that make a contradicting rule visible, a test that the tools a prompt names are the tools it registers, and a per-persona token budget from a calibrated estimate (2.33 chars/token; 4 was 41% low). Every check broken once on purpose, with zero model requests.
- 7
A3: A Textbook Hybrid RAG, and Why It Was Retired — The Threshold, the Scale and the Shape
A textbook hybrid RAG (pgvector + Postgres full text + RRF + a 0.3 threshold) was retired because it usually returned nothing. Rebuilt on Ironline and measured with no model: fused RRF scores never exceed 2/61 = 0.0328, so the threshold emptied 50 of 50 questions; vector search alone found the right category 96% of the time; full text matched nothing for 45 of 50 sentences; and a generic splitter cut 7 of 9 decision-tree branches from their question.
- 8
A4: Don't Chunk: Whole SOPs, Steps by Key — A Knowledge Store the Business Edits
After the hybrid RAG was retired, the requester agent gets its knowledge by exact key: the whole SOP for the category it chose (staff-only text stripped in code, 3,217 → 2,714 characters, failing closed), troubleshooting steps by exact policy key instead of +142% on every turn, and a knowledge store with immutable revisions and a published pointer. Measured on Ironline: an edit reached the agent 20.0 s after the publish with a 20 s TTL, a rollback is revision 3, and a revoked database grant was hidden by the file fallback until a grant check and an alert on source = file caught it.
- 9
A5: Latency and Cost — Prompt Caching, Layered by How Often Things Change
Prompt caching that works across sessions, not just inside one chat: order the prompt by how often each part changes, measure the second session's first turn (79% cheaper, read share 47.7% to 71.7%), and the traps — time to first token barely moved, a prompt under the 512-token minimum caches nothing silently, and 4 chars per token was 41% low until calibrated to 2.33.
- 10
A6: Deterministic Guards After the Model — Parse, Complete, Enforce
Rules that live only in the prompt break: move them into one ordered chain of pure functions after every model turn (parse, complete, enforce) with one event per change, a tool-level two-call protocol instead of a schema rule that trapped requesters, guard state from events, a sentence gate (+58 ms vs +703 ms for waiting on validation), an offline replay (1 override in 31 turns), and demo turns kept out of the real Guardrails tile.
Lessons 11–2010 lessons
- 11
A7: Emergencies and the Silent Model — Prompt Rules, a Regex Net and a Server Fallback
Emergencies are rare and must never be missed: a prompt rule, a versioned trigger list on the requester's own words that only raises (11/11 emergencies, 0/49 false alarms on 60 conversations, with honest held-out numbers), a banner before the model (76 ms vs 4,457 ms live), a server reply when the model is empty, errors or refuses, a real "on my end" false alarm fixed, and a zero-tolerance eval that fails a 98.3 % run.
- 12
A8: Photo Uploads — The Label Is Not the File
A requester attaches "photo.jpg" and it is really a video, a HEIC or zero bytes: the provider refuses the whole turn. Judge every upload by its bytes (8 fixtures, every PUT 200, 3 labels wrong, 4 rejected), enforce the provider's image limits with their source, convert HEIC, skip an unreadable file with a system note to the model, and gate Confirm on an accepted photo, never holding back an emergency.
- 13
A9: Writing Downstream I — Failure Classes, and "HTTP 200 Does Not Mean It Executed"
A confirmed ticket goes into another team's platform, which refuses, times out and sometimes answers 200 without executing: sort every response into three classes (business refusal, user-facing error, fault), give every fault a handling (retry or page) and an executed value (no, unknown, yes), and see it live with no model on a mock with 15 fault switches — including a timeout where the requester saw 503 while the order landed six seconds later.
- 14
A10: Idempotency Without an Outbox — Write-Ahead Records, Read-Back and an Operator Redrive Tool
A create can time out and still land: write the exact payload and an idempotency key before the call, let one conditional UPDATE decide who sends, read back before every retry, adopt a 409 only when the payload matches, and give operators a redrive page with a dry run, a duplicate check and an append-only audit log. Measured: the timeout that ended A9 in a page now lands via read-back with one create and no page.
- 15
A11: Slow AI Jobs Downstream — Trigger, Poll, and Reconcile After a Timeout
A slow AI triage job runs downstream after a work order lands: schedule it after the response with after() (Confirm in 46 ms under a 60 s edge budget, checked at startup), track it in a triage_jobs row, poll it to a deadline, treat a timeout as a state and reconcile late results, re-trigger only what is lost and ignore superseded jobs on purpose, reject results about another order, and page only what cannot heal itself.
- 16
A12: Security for a Requester-Facing Agent — Identity, Tokens and Rate Limits
A find-the-holes lab for an AI agent embedded in someone else's page: another gym's siteId, someone else's session id, a leaked shared admin token and a role in the request body all work against Ironline step-11; then step-12 refuses them with a 60-second single-use token exchange, roles decided by the issuer, 404 ownership checks, token fingerprints in the logs and rate limits per identity.
- 17
A13: Conversation State and Failure Recovery — Don't Let One Bad Reply Ruin the Whole Session
A chat agent replays its stored history on every turn, so one bad row bricks the session: an orphaned tool call or a whitespace reply gets HTTP 400 on every later turn. Reproduced on Ironline step-12, fixed at step-13 with sanitizeHistory() (2,000 random histories; live 400, 400 -> 200, 200), save rules per turn status, one recorded retry and problem boundaries; then step-14b's empty first reply, caught and retried live.
- 18
A14: Evaluation I — A Two-Mode Harness, Zero-Tolerance Classes and "Known Failure" Debt
Did one line of prompt break emergency detection? Run 60 labelled scenarios through the real handlers in two modes — a free mock mode whose recorded-answer model goes through the real tools (60 of 60 in 3.3 s, on every push) and a paid real mode with a request ledger, an LLM judge for soft criteria and a simulated requester — make emergencies a zero-tolerance class (98.3 % with one missed emergency fails the push), and treat known failures as debt with an owner and an expiry, so stale and expired markers fail the run.
- 19
A15: Evaluation II — Changing Models Is an API Migration: Production Replay and Startup Checks
Your production model has a retirement date: trace every turn (self-hosted Langfuse or a JSONL file behind one interface, session ids as HMACs), replay each turn's exact request once on the candidate with recorded tool results, and score agreement field by field next to production replayed on itself — 90% vs 55% on every field over 20 turns, with the gap in when the candidate acts, not what it thinks — then the migration trap: a startup check that refuses a stale model family, a silent effort default, and a forced tool choice answered with HTTP 400.
- 20
A16: One Trace per Turn — and “Was the Model Even Called?”
A requester says "it got stuck". One trace per turn, log lines that find their trace by request id and a keyed session hash, and a terminal tool that answers "was the model even called?" and "which step failed?" — shown on an empty reply, a 403, a 5xx and a downstream fault. Then the error the SDK hides behind "no output generated", metrics on a path production never takes, a runbook broken by a vendor deprecation and a shell variable, and a trace store that fails silently.
Lessons 21–3010 lessons
- 21
A17: Why the Alarm Didn't Fire — and Why It Fired Wrong
Four alarms that failed, each in its own way: a SEARCH alarm that passed synth and tests and then rolled back the deploy, failures logged at WARN while the one alarm blamed another system, one stuck session that paged again and again, and alarms on numbers no code path writes. Each one reproduced and fixed on Ironline: a synth-time check, a catch-all line count, alarms generated from named causes, dedupe before the count, and deadmen.
- 22
A18: Running It in Production — Switches, Rollout, Dependency Upgrades and Migrations
Launching an AI agent is one event; running it is every week. Production changes sorted by how fast they act (a release, an environment variable, content, a runtime flag), a trace-export kill switch flipped on a running container with no restart, the audit gap it leaves, why a feature flag never isolates an SDK upgrade, upgrades shipped pinned and locked, a model canary and rollback pair, and a migration that never arrived while the ledger said up to date — measured on Ironline step-17.
- 23
B1: Same Stack, Different User — Problem Definition for the Technician Assistant
Track B reuses Track A's stack for a field technician on a phone, and the problem changes: an expert user, an injury-level cost for a wrong answer, and no deflection to count. We define "helped" from the expert's words, measure job-aid coverage before building retrieval (68/8/25% of policy leaves, 74/3/23% of open orders), show why a retriever's score can never say "no aid applies", import 30 job aids with the one broken table flagged, and run a technician chat API that cites its sources and saves every turn on the work order.
- 24
B2: Keep Retrieval, Fix Lexical Search First — Then Talk About Vectors
The technician assistant keeps retrieval, but fixes the boring layer first: BM25 in code instead of Postgres full-text search (whose parser splits X-450 and T-700), fault codes and model names as tokens, a generic stop list measured and rejected, plurals and title weighting — each fix measured on 34 labelled questions (section hit@1 56% → 74%, hit@3 76% → 100%, MRR 0.672 → 0.853). Vectors added nothing on top; Step 19's code-scope fix moved the T-900 E3 case from rank 10 to rank 1.
- 25
B3: Retrieved Means Candidate, Not Authority — and the Semantic Search That Was Silently Off
A technician asks about a dress code and the assistant answers from a cable machine's job aid: retrieval always returns something, and the prompt called it policy. We measure why no score threshold can say "nothing fits", label retrieval as candidates, check citations and model fit in code, and make a semantic-search fallback that was silently off loud. Then an honest null result: removing the label changed nothing measurable, and why.
- 26
B4: Field Safety — A Safety-First Block and Escalation Rules Quoted Verbatim
A technician assistant told someone to disconnect a lead on a live board, and every quality check would have scored it well. Two layers fix it: a versioned safety block first in the prompt and a code gate that releases the answer one sentence at a time, plus escalation quoted word for word from the job aid. Then the pitfalls: safe sentences blocked, invented routes, an injected job aid, permissive phrasing, and a model marker the server stopped trusting.
- 27
B5: One Seam, Two Providers — Choosing Between Latency and Cost by Measurement
Choose between a hosted agent platform and a direct model call by measurement: one seam with the same gate, scorer and 25 scenarios; a first comparison that was wrong because of our own harness (11 of 36 turns empty, +16 points); a clean rerun level within the noise (15/25 vs 16/25, p = 1.00, A − B −4 [−27, +19]); latency and cost at the same answer length (3.6 s vs 4.3 s, +9%); a decision rule written first; and a 404 AgentNotFound that pages.
- 28
B6: Evaluation Without an LLM Judge — Behavioural Checks, Offline Re-Scoring and Small-Sample Honesty
Evaluate an AI agent without an LLM judge: seven behavioural checks written as code, each verdict quoting the text that decided it; saved transcripts re-scored offline after the scorer turned out to have bugs in both directions; and Wilson intervals, run-to-run noise and exact McNemar tests that show what 25 scenarios can and cannot detect.
- 29
B7: Client-Side and API Security — Forged Markers, Input Caps and Never Retrying a Billed Call
An internal technician app is still an API on the internet. Three code-review findings: a message that forges the prompt's markers, identity from a header with no caps on what reaches the model, and a phone that retried a billed model call. On Ironline we check what the code really does: a technician token with its own issuer, audience and key set, caps tested one character past the limit, a random per-request data boundary, a model-written ESCALATE marker the server no longer trusts, and a route that never retries a 5xx — plus the two caps that are honestly missing.
- 30
B8: Offline Writes and Replay — Transient vs Semantic, Read Back Before Replay, and the Request Budget
A technician's phone queues work offline and sends one batch when the signal returns: classify every answer as transient, semantic or attention by reading the message before the error name, read back by idempotency key before any replay, hold unknown outcomes one lease so late commits land first, and stop each batch inside its own request budget. Measured: a timed-out note adopted by read-back with no second write, a full resend answered duplicate x4 with nothing sent, and a reset platform that made "did it land?" say no.
Lessons 31–322 lessons
- 31
B9: Tokens and Clocks — Renewal Margin, Single-Flight Renewal and Device Clock Skew
401s that come in bursts about an hour after start, and technicians whose every action is refused. Reproduced on Ironline step-22 and fixed in step-23 with the same script: a clock offset alone caused 0 × 401 (the cause was a live token re-issued as new), 20 instances went from 20 logins to 1, an hour against a 30/h login quota from 350 token requests and 320 failed calls to 20 and 0, a phone 10 minutes ahead stopped reordering work, a 401 retry came back inside its budget, and a sweeper that never exited learned to.
- 32
B10: Observability for the Technician Assistant — Alarms That Can Fire, the Catalogue as the Alarm List, a Read-Only Ops CLI
The final episode. With the platform login refused for a whole run, 30 technician actions parked and none of 21 alarms fired. The technician failure catalogue becomes the alarm list: one severity per cause, one TechFailures metric, 12 generated alarms with FIRST/THEN runbooks, tests that drive each alarm to ALARM from its real code path — the same run then fires 2 of 34, both pages. Plus the sweeper dead-man, fail-open traces with TraceWriteFailures, pnpm ops:tech (read-only, exit 0 / 1 / 2), and a recap of the whole course.