CP·211F
The AI Layer
TiffinBox's assistant built to the capstone's list: a model gateway over LLM APIs, an ingestion pipeline for kitchen documents, hybrid retrieval with reranking and citations, structured outputs that are validated, tools that act as the user with confirmation, an agent loop only where a task needs one, an evaluation suite that gates releases, and AI security for untrusted documents and tool calls; with a lab on how much validation and retries buy, and how many test questions it takes to notice a regression.
Start here: what the assistant may and may not do
TiffinBox's assistant answers questions like "Is Tuesday's sambar from Amma's Kitchen nut-free?", "When does my lunch arrive?", and "Skip tomorrow, I'm travelling". Each kind of question needs a different technique, and getting that mapping right matters more than any model choice:
| Question | Source of truth | Technique |
|---|---|---|
| allergens, ingredients, kitchen policies | the kitchen's uploaded declarations and menus | retrieval (RAG) over documents, with citations |
| my orders, my plan, delivery ETA | TiffinBox's own database | tools calling the API as the user, never retrieval |
| skip, pause, change a meal | the Subscriptions module's rules | tools with confirmation and idempotency keys |
| "plan my lunches around a trip" | several of the above | a bounded agent loop, only for multi-step tasks |
| anything else (medical advice, other users' data) | none | a polite refusal |
The non-negotiable rule: the assistant never invents an allergen claim. If the kitchen's declaration doesn't cover the question, it says it doesn't know and how to ask the kitchen. That single rule shapes retrieval, prompts, evaluation and security.
Two numbers that shape the design
The lab simulated a model whose structured outputs are valid 90% of the time, and then asked how many test questions it takes to notice a quality drop:
| Result | |
|---|---|
| accept whatever the model returns | 10% of responses broken or wrong-shaped |
| validate + 1 retry | 99.0% valid, for 1.10 calls on average |
| validate + 2 retries | 99.9% valid, 1.11 calls |
| detect a drop from 85% to 80% accuracy with 100 test questions | caught 34% of the time |
| … with 400 questions | caught 83% of the time |
| … with 800 questions | caught 98% of the time |
Validation with one retry is nearly free and removes almost all malformed output. But an evaluation set of a hundred questions misses most real regressions: small golden sets give false comfort.
How deep to go
Volume 17 defines six mastery levels. For the AI layer:
| Level | What you can do |
|---|---|
| L1 | Explain which technique answers which question, and why |
| L2 | Build ingestion, retrieval, tools and the chat endpoint |
| L3 | Explain embeddings, reranking, structured decoding, tool calling and injection from first principles |
| L4 | Debug wrong answers to retrieval, prompt, tool or model, using traces and evaluation |
| L5 | Design the assistant's scope, safety rules, evaluation and cost, and defend them |
| L6 | Run it: model upgrades, drift, incidents, cost control, red-teaming |
Volumes 14 and 14B (chapters 143–180) teach every topic in depth.
The model gateway
All model calls go through one module in the API (or a small internal service):
- Provider abstraction: one interface for chat, embeddings and reranking, with adapters per provider; prompts and models chosen by configuration, versioned.
- Timeouts and fallbacks: a first-token timeout and a total timeout; on failure or timeout, fall back to a second provider or a smaller model; a circuit breaker per provider (chapter 212B's lab: with a breaker, 100 of 100 questions were answered at a median 1.3 s during a provider outage; without a timeout, none were answered).
- Limits: per-user rate limits and daily token budgets; a global budget alarm.
- Streaming of answers to the frontend over SSE (the same mechanism as tracking).
- Logging and tracing: model, prompt version, tokens in and out, latency, cost and tool calls on every span, with personal data redacted.
Ingestion
Kitchen documents (menus, allergen declarations, policies) arrive as PDFs or images:
- Upload via a presigned URL; a
DocumentUploadedevent triggers an ingestion worker. - Validate and parse in a sandboxed worker: type by content, size and page limits, decompression limits, timeouts.
- Chunk by structure: one chunk per dish's allergen entry or per policy section, not fixed character windows; keep headings with their content.
- Embed chunks and store them with metadata (
kitchen_id,document_id,version,effective_date, page) in pgvector, plus a full-text column. - On a new version, ingest it fully, then switch
current_versionfor that document; old chunks stop being retrieved but remain for audit.
Retrieval with citations
- Filter first: only the relevant kitchen's current documents (
kitchen_id,current_version). - Hybrid search: vector similarity and full-text (BM25-like) ranks combined with reciprocal rank fusion; dish names and allergen words match well by keyword, paraphrases by vector.
- Rerank the top ~50 to the top ~5 with a cross-encoder.
- Cite: each chunk carries its document, page and version; the answer must reference them, and the UI shows the source.
- Abstain: if the top reranked score is below a threshold, or no chunk mentions the asked allergen, answer "I can't confirm that from the kitchen's declaration" with a contact option.
Structured outputs
Wherever code consumes the model's output (tool calls, classifications, the "answer + citations + confidence" envelope):
- Use the provider's schema-constrained output when available, and always validate against the JSON Schema anyway.
- On failure, retry once with the validation error included; then fall back (a safe generic answer, or hand off to a human). The lab: this takes validity from 90% to 99% for ~10% more calls.
- Never execute model output directly: no generated SQL against production, no generated HTML rendered without sanitising; render markdown with links restricted to your own domain or shown as text.
Tools
| Tool | Effect | Guard |
|---|---|---|
search_menu(query, kitchen_id?) |
read | none beyond rate limits |
get_dish_allergens(dish_id) |
read | returns declaration text and citation |
get_my_orders(date_range) |
read | runs as the user; only their orders |
get_delivery_status(order_id) |
read | ownership checked |
skip_day(subscription_id, date) |
write | user confirmation in the UI; idempotency key; cut-off rules in the use case |
pause_plan(subscription_id, from, to) |
write | same, plus a summary of credits before confirming |
Tools call the same application use cases as the REST API, with the user's identity: the assistant gets no powers the user doesn't have. Arguments are validated by schema; unknown tools or fields are rejected.
An agent loop, only where it pays
Most requests are one retrieval or one tool call plus an answer. For multi-step requests ("I'm away from the 12th to the 16th; skip those lunches and tell me my credit"), a bounded loop:
- A plan–act–observe loop with a maximum of ~6 steps, a token budget and a wall-clock limit.
- Write actions collected into one confirmation shown to the user ("Skip 12, 13, 15, 16 (14 is a holiday); credit ₹480. Confirm?"), then executed with idempotency keys.
- Every step traced; failures explained to the user, never silently retried forever.
Evaluation
Golden sets in eval/, run in CI on every prompt, model, retrieval or tool change:
| Set | Size | Metrics |
|---|---|---|
| allergen questions with labelled answers and sources | 400+ | correctness; citation accuracy; zero invented claims (any one fails the build) |
| "I don't know" cases (not in the declaration) | 100+ | abstention rate |
| order and plan questions (tool use) | 200+ | right tool, right arguments, right answer |
| multi-step tasks | 50+ | task success, steps, confirmation shown |
| injection and abuse cases | 100+ | no forbidden tool calls; no data leaks |
- Size matters (the lab): to detect a 5-point drop reliably you need hundreds of questions; compare paired results on the same questions (did this question flip?), which is more sensitive than comparing two overall scores.
- Judges: exact checks where possible (tool arguments, citations); LLM-as-judge for free text, calibrated against a few hundred human labels and re-checked when the judge model changes.
- Online: sample live conversations for human review weekly; track thumbs-down rate, abstention rate, tool error rate and cost per conversation by release.
AI security
Following the OWASP Top 10 for LLM applications:
- Prompt injection: treat retrieved documents and tool results as data, wrap them clearly, and never let them grant capabilities. The real defence is outside the model: an allow-list of tools per feature, user-scoped permissions, confirmations for writes (chapter 212B's lab: a model that obeyed a planted instruction proposed exporting customers and emailing them; the policy layer blocked both).
- Sensitive data: no other users' data reachable by any tool; personal data redacted from logs and traces; providers configured for no training on your data and appropriate retention.
- Output handling: sanitise rendered output; restrict links; no automatic execution.
- Resource abuse: per-user rate limits, token budgets, input size limits.
- Supply chain: pinned model versions, evaluated before upgrade; dependencies scanned like any other code.
Done when
- Each question type uses the right technique; out-of-scope questions are refused politely.
- Ingestion handles new document versions, rejects malformed files, and can be re-run from scratch.
- Answers cite sources; the zero-invented-allergen rule holds on the full golden set.
- Structured outputs are validated with one retry and a fallback; tools are allow-listed, user-scoped and confirmed for writes.
- Evaluation gates every change; online sampling and metrics run weekly.
- Provider outages degrade to a fallback (chapter 212B); cost per conversation is tracked and budgeted.
Common traps
- Retrieval for live data (orders, ETAs) instead of tools.
- Fixed-size chunks that split an allergen line from its dish.
- Tiny evaluation sets and single-number comparisons.
- Security in the prompt only ("never do X") instead of in code.
- Agents for everything.
Lab: validation, retries and evaluation size
Setup. NumPy simulations on the lab machine. No model is called: the point is the arithmetic of reliability and measurement, which holds whatever the model. Assumptions are stated for each experiment.
Experiment A: validate and retry structured output
Assumption: each model call independently returns valid, schema-conforming output 90% of the time (6% invalid JSON, 4% valid JSON that violates the schema). 100,000 simulated requests per policy; a request retries only when validation fails.
| Policy | Valid responses | Mean calls per request | Formula 1 − 0.1ⁿ |
|---|---|---|---|
| no validation (accept anything) | 90% (10% broken or wrong-shaped, passed on to the caller) | 1.00 | — |
| validate, no retry | 89.99% (failures caught, fallback used) | 1.000 | 0.9000 |
| validate + 1 retry | 99.02% | 1.101 | 0.9900 |
| validate + 2 retries | 99.89% | 1.110 | 0.9990 |
| validate + 3 retries | 99.99% | 1.112 | 0.9999 |
Experiment B: how many golden questions find a regression?
Setup: a system with 85% accuracy (the baseline) and a regressed version at 80%. For each evaluation-set size n, the alarm threshold is set so that the baseline triggers it about 5% of the time (a one-sided test), then 20,000 simulated runs of the regressed version measure how often the alarm fires. Questions are treated as independent draws.
| Questions | Alarm if score below | Regression caught | False alarms on the baseline |
|---|---|---|---|
| 50 | 0.760 | 19% | 3.2% |
| 100 | 0.790 | 34% | 3.8% |
| 200 | 0.805 | 53% | 3.4% |
| 400 | 0.820 | 83% | 4.2% |
| 800 | 0.829 | 98% | 4.6% |
| 1,600 | 0.836 | 100% | 5.0% |
What it shows
- Validation turns silent corruption into handled failure, and one retry is the sweet spot: 99% valid for 10% more calls. More retries buy little and add latency. This assumes failures are independent; if a particular input always produces bad output, retries won't help and the fallback must.
- Small evaluation sets mostly miss real regressions. A 100-question set noticed a 5-point drop only a third of the time. Use hundreds of questions for the metrics that matter, and keep a few zero-tolerance checks (any invented allergen claim fails the build) that don't depend on averages at all.
- Paired comparisons do better than this. The simulation compares overall scores. Running both versions on the same questions and counting which questions flipped from right to wrong (a McNemar-style test) removes much of the noise, so the same set detects smaller regressions.
Try it yourself
- Make failures correlated (10% of inputs always fail) and rerun Experiment A: how much do retries help now?
- Change the regression size to 2 points: how many questions do you need for 80% detection?
- Implement the paired comparison and measure its detection rate at 200 questions.
- Run Experiment A against a real model with a JSON Schema and measure its actual first-try validity.
Revision sheet: the AI layer
Key ideas
- Map questions to techniques: documents → RAG with citations; live data → tools as the user; multi-step → a bounded agent; out of scope → refuse.
- Never invent allergen claims; abstain when evidence is missing.
- Gateway: providers, timeouts, fallbacks, breakers, limits, streaming, tracing with cost.
- Ingestion by structure, versioned; hybrid retrieval, filters, reranking.
- Validate structured output, one retry, fallback; never execute output.
- Tools allow-listed, user-scoped, confirmed and idempotent for writes.
- Evaluation sets of hundreds of questions, paired comparisons, zero-tolerance checks, CI gates, online sampling.
- Security outside the prompt: permissions, allow-lists, confirmations, sanitising, budgets.
Numbers to remember
- Validate + 1 retry: 90% → 99% valid for ~1.10 calls.
- Detecting 85% → 80%: 100 questions 34%, 400 questions 83%, 800 questions 98%.
Pitfalls
- RAG for live data; fixed-size chunks; tiny eval sets; prompt-only security; agents everywhere.
Glossary
- Reciprocal rank fusion: combining rankings by summing 1/(k + rank).
- Cross-encoder reranker: scores a question–passage pair jointly.
- Abstention: declining to answer when evidence is insufficient.
- LLM-as-judge: a model grading outputs, calibrated against humans.
- Indirect prompt injection: instructions hidden in content the model reads.