
Claude Triage API
Take the course · Visit the shop · Read the scenario · Node ≥ 20
A reference implementation of a customer-support triage service built on the Claude API, plus the course that teaches it — written to be read and taught from, not just run.
Personal project. This course is an independent educational resource. The views expressed here are my own and are not affiliated with or endorsed by Cursor.
Four routes, four capabilities, one coherent domain. Each route introduces exactly one new idea and builds on the one before it.
flowchart LR
Triage["POST /v1/triage<br/>structured outputs"] --> Resolve["POST /v1/resolve<br/>tool use"]
Resolve --> Draft["POST /v1/draft<br/>streaming"]
Draft --> Estimate["POST /v1/estimate<br/>token counting"]
Three things live here
| What it is | Where | |
|---|---|---|
| The service | src/ — the Claude API reference implementation the whole course is about. Runs locally; not deployed. |
this repo |
| The course | website/ — Docusaurus site: scenario, setup, eleven labs with inline knowledge checks, solutions, instructor guide, auto-scored assessment, and seven interactive playgrounds. |
triage.mlynn.dev |
| The Python track | python/ — the same service on FastAPI, plus what is actually different. Four differences, all of them found by porting rather than recalled. |
this repo |
| The scenario, made real | storefront/ — Next.js shop for the fictional company. Browse the gear, file a support ticket, watch your own words get classified live, then try to break the classifier. Escalated tickets land in a reviewer queue you can read without a credential; Priya's ops dashboard sits on top. |
northwind.mlynn.dev |
Start with the scenario. The domain is a real company with a real problem: 4,100 support tickets a week, manual triage as the bottleneck, two failed automation attempts, and an incident where a child's injury report sat unrouted for three days because it opened with "probably nothing." Every design decision in this repo traces back to something on that page, and the labs are much harder to motivate without it.
What that looks like
The introduction, in two minutes. The queue, the ticket that sat for three days, and what you build to catch it — before you decide whether to spend an afternoon on it. Watch it
The shop. A working Next.js storefront for the fictional company, so the tickets the service triages are about products a learner has actually looked at. northwind.mlynn.dev

The queue. Every ticket here was classified requires_human: true and
written to the database by the persist stage. Tickets that did not need a
human were classified and discarded — storage is a consequence of escalation,
not of submission. northwind.mlynn.dev/queue

The playgrounds. Seven of them on the course site, rendering results from real runs rather than illustrations of results. This is the model matrix from Lab 7, where the calibration gap — not the accuracy column — is the number that decides whether you can route on confidence. triage.mlynn.dev/playground

The deck. Slideshow mode for the course introduction, with speaker notes
and a synchronised presenter window. Arrow keys move it, S opens the notes
in the page, P puts them in a second window that stays in step, F goes
full screen. triage.mlynn.dev/talk

| Route | Capability | The idea it teaches |
|---|---|---|
POST /v1/triage |
Structured outputs | The model's output contract is your type system |
POST /v1/resolve |
Tool use | Claude queries your systems and shows its work |
POST /v1/draft |
Streaming | Token-by-token delivery over SSE, with real cost accounting |
POST /v1/estimate |
Token counting | Know the bill before you pay it |
GET /v1/limits |
Rate-limit headers | Your remaining headroom, before a 429 tells you |
Cross-cutting, demonstrated throughout: prompt caching (a ~1,400-word policy handbook cached across every request), usage and cost accounting, typed error handling, and an eval harness with both deterministic scoring and an LLM judge.
The course
This repo doubles as a hands-on course for developers building on the Claude
API. Read curriculum/scenario.md for the domain,
follow curriculum/setup.md to get running, then
curriculum/00-concept-map.md for the
technical map.
Day 1 is the course. Labs 0-6 are the enablement asset: the four capabilities, one domain, about four hours. Someone who does only Day 1 has learned the Claude API and has a working service to show for it.
| Lab | Topic | Time |
|---|---|---|
| 0 | Establish your evaluation baseline | 20 min |
| 1 | Your first call, and reading usage |
20 min |
| 2 | Structured outputs and schema design | 35 min |
| 3 | Tool use and the agentic loop | 45 min |
| 4 | Streaming and SSE | 30 min |
| 5 | Prompt caching and cost | 35 min |
| 6 | Eval design and LLM-as-judge | 45 min |
Day 2 is optional, and it is for people who are going to ship. Three more hours on the decisions that only arrive once something is real: which model, what happens when the input is hostile, and what separates a demo from a service. Skip it without loss if you are here to learn the API.
| Lab | Topic | Time |
|---|---|---|
| 7 | Choosing a model | 45 min |
| 8 | The trust boundary | 60 min |
| 9 | Shipping it: batch, limits, MCP | 60 min |
The capstone is separate from both, and it is a reading lab. Lab 10 works
through Ask Northwind — the assistant already
running on both public sites — rather than building a route in src/. It is
the only lab where the artifact is deployed rather than local, so it needs no
key and can be run by someone who never opened a terminal.
| Lab | Topic | Time |
|---|---|---|
| 10 | Ask Northwind: scoped tools, and why the confirmation is the write | 45 min |
Optional throughout: a Python track covering the four things that genuinely differ between the SDKs. The labs are TypeScript and nothing later asks for Python.
Instructors: curriculum/01-instructor-guide.md
has timing, the failure modes learners hit, and what to do when a lab goes
sideways. Solutions are in curriculum/solutions/.
Facilitators: curriculum/02-run-of-show.md is
minute-by-minute, and docs/facilitator/keys.md
covers workspaces, keys, and measured per-learner cost.
The opening two segments — the scenario and the concept map — have a deck:
slideshow mode, nine slides with speaker
notes. P opens the notes in a second window that stays in step with the
deck, so a mirrored projector does not show the room your notes.
After the course: triage-api
The service in src/ is deliberately Northwind's — hardcoded taxonomy, one
company's handbook, fixture data, and nothing writing back to a ticketing
system. That is right for a course and wrong for production.
github.com/mrlynn/triage-api is the
same technique with those four things moved behind a config seam: policy packs,
a DataProvider, signed webhook ingest with connectors for Chatwoot,
Zammad, Zendesk, GitHub Issues and a signed generic webhook, a
reviewer queue, and a conformance suite for writing your own
adapter. The guardrails are the same code; what is new is everything that only
shows up once something has to run — including /readyz reporting which
controls can actually execute in a given deployment.
Full comparison and a reading order: curriculum/next-steps.md.
Quickstart
Full setup, prerequisites, and troubleshooting:
curriculum/setup.md. The short version:
npm install
cp .env.example .env
Put your key in .env (get one at
console.anthropic.com), then:
npm run smoke
.env and .env.local are loaded automatically by
src/lib/env.ts — no dotenv dependency, and a real shell
variable always wins over the file.
npm run smoke exercises all four routes in-process and prints the prompt-cache
hit on the second call. It costs about $0.10.
To run the service:
npm run dev
To run the whole learning environment (API, course site, and Northwind storefront) together:
npm run dev:all
It uses http://localhost:8787 for the API, http://localhost:3001 for the
course, and http://localhost:3002 for the storefront. Override a port with
API_PORT, COURSE_PORT, or STOREFRONT_PORT when needed.
curl -s localhost:8787/v1/triage -H 'content-type: application/json' -d '{
"message": "Order NW-48211 arrived Monday and the zipper separated the second time I wore it. I want a replacement."
}' | jq
What each route actually does
POST /v1/triage — structured outputs
Classifies an inbound message into a validated schema: category, urgency, sentiment, extracted entities, escalation flag, and a calibrated confidence score.
The point: there is no JSON.parse in a try/catch, no "respond only with
JSON" in the prompt, and no repair loop. One Zod schema
(src/schemas.ts) is simultaneously the model's output
constraint, the runtime validator, and the TypeScript type your consumers get.
{
"triage": {
"category": "product_defect",
"urgency": "normal",
"sentiment": "frustrated",
"summary": "Jacket zipper separated on second wear; wants a replacement.",
"entities": {
"order_ids": ["NW-48211"],
"product_names": ["Ridgeline 3L Shell Jacket"],
"requested_remedy": "replacement"
},
"requires_human": false,
"escalation_reason": null,
"confidence": 0.92
},
"meta": { "usage": { "cache_hit": true, "estimated_cost_usd": 0.0041, "...": "..." } }
}
POST /v1/resolve — tool use
Gives Claude three tools over a fake back office — lookup_order,
lookup_customer, search_policy — and lets it decide what to call, in what
order, and when it has enough to act. Returns the decision and the full tool
trace.
Production details this route does not skip:
max_iterationsis capped. An uncapped agent loop is an uncapped bill.- Usage is summed across every turn. The final message's
usagecovers only the final request; reporting it alone under-reports a 5-turn loop by ~5×. - The tool trace is returned. In support tooling, "show your work" is an audit requirement — and it is also what the guardrails read, since a control must take its inputs from a source the thing it controls cannot rewrite.
- The returned resolution is the CORRECTED one.
enforceAuthorityre-derives the $200 and $500 ceilings from the trace, and where the arithmetic disagrees with the model'swithin_agent_authorityboolean, the arithmetic wins andmeta.guardrailsrecordsmodel_claimed_authority_it_lacked. Correct and alarm.
POST /v1/draft — streaming
Streams a customer-ready reply over Server-Sent Events. Emits three event types:
text (reply body), thinking (summarized reasoning, for a collapsed UI
panel), and a terminal done carrying stop_reason and full cost.
Two things most streaming demos get wrong and this one doesn't: usage arrives
only at the end (via finalMessage()), and a client disconnect must abort the
upstream stream or you keep paying for tokens nobody will read.
POST /v1/estimate — token counting
Counts tokens server-side with the real tokenizer and projects monthly cost at a given volume, cached and uncached. No inference, so it's free.
The server also checks this at boot: src/lib/preflight.ts measures the frozen
prefix against the configured model's minimum with one free countTokens call
and prints a loud block if caching is off. Set PREFLIGHT=off to skip it. The
estimate route reports the same thing on demand — it returns
cache_minimum_tokens and prefix_meets_cache_minimum. The
minimum is a per-model property (512 on Opus 5, 1024 on Sonnet 5, 4096 on Haiku
4.5), so it is read from the catalog rather than hardcoded — below it the API
silently declines to cache, with no error.
Attachments — the photo of the zipper
/v1/triage accepts an optional base64 image alongside the message, because a
support inbox is the most obvious place in software for a photo to arrive.
Vision is not a separate API, model, or route: the user turn's content is
either a string or an array of blocks, and an image is a block. Two properties
worth knowing, both pinned by tests in
src/lib/requests.test.ts:
- A ticket with no attachment still sends a bare string, not a one-element array. Those are identical to the API and different to the cache — prompt caching is a prefix match, so returning an array unconditionally would have cost every warm caller a fresh cache write on the day it shipped.
- The image is not, and cannot be, wrapped by
wrapUntrusted— escaping is a string operation. Text rendered into an image bypasses that defence entirely, whileenforceAuthorityandverifyCitationsare completely unmoved, because they read the tool trace rather than the message. An entire defensive layer goes to zero and the money stays safe, which is the clearest demonstration in the repo of why defences get ranked by kind. Lab 2's second extension.
None of the twelve gold cases has an attachment, so npm run eval says nothing
about this path. A capability with no cases in the gold set is untested however
green the suite is.
Tests
npm test
60 tests, no credential, no network, about 100ms and $0. These cover the
guardrails as pure functions — the refund ceilings in
src/lib/authority.ts, the escaping and redaction in
src/lib/untrusted.ts, citation verification, cost
accounting, and the assistant's authority rules.
The split is the point. Lab 8 argues that a deterministic control beats a well-written instruction because it holds by construction — and a construction nobody tests is an instruction with better syntax. So the two gates answer different questions and neither substitutes for the other:
| Question | Determinism | Cost | |
|---|---|---|---|
npm test |
Does the arithmetic hold? | Exact. A failure is always a bug. | free |
npm run eval:redteam |
Can the model be talked past it? | Statistical. 100% on 14 cases. | ~$0.40 |
The suite is mutation-checked rather than merely green: breaking the refund
ceiling by one cent, dropping the Luhn check, treating a not-found customer as
zero prior refunds, or reverting verifyCitations to the version that was
wrong each turn it red. That check found one test in this file passing for the
wrong reason — an alphanumeric tracking number was being rejected by the length
gate, never reaching the Luhn check it claimed to exercise.
Evals
npm run eval:quick
The baseline evaluation: deterministic scoring only, about a minute and $0.09 warm.
It compares against the checked-in evals/baseline.json
and names the cases that moved, which is the number Lab
0 puts on the board before any prompt
work starts.
npm run eval:redteam
The trust-boundary gate: 14 cases (11 attacks, 3 benign controls) through triage and the tool loop. Gates at 100%, separately from accuracy — a rate is the wrong shape for a breach — and counts a blocked legitimate customer as loudly as a successful attack. ~$0.40. See Lab 8.
npm run eval:models
The tier matrix: the same twelve cases against the two tiers, Opus 5 and
Sonnet 5 (add --models claude-opus-5,claude-sonnet-5,claude-haiku-4-5 to
include the dropped Haiku tier), with a pinned judge and a per-case
disagreement grid. --emit-site writes the
summary the course site renders, so the
