Capstone: Shipping a Production GenAI Assistant
This is the project that pulls the course together: a document-grounded assistant that answers questions about a private knowledge base, refuses what it cannot support, and can be operated like any other service. You will assemble ingestion, retrieval, generation, guardrails, evaluation, and monitoring into one coherent system, then make the case that it is ready for real users. The code here is a skeleton you can run and extend; the decisions around it are the actual lesson.
Scope the Problem Until It Is Testable
Every failed assistant project I have seen was scoped as "a chatbot for our knowledge" and died in an unmeasurable middle. Start by writing ten concrete questions users will actually ask, with the answers you expect and the documents those answers come from. That list becomes your evaluation set, your acceptance criteria, and your demo script. Then write down what the system must not do â give pricing without a source, discuss competitors, offer legal advice â because refusals are part of the product, not an error state.
Three constraints shape everything that follows. Latency: users tolerate roughly two seconds before the experience feels broken, so retrieval and prompt assembly must be fast and generation must stream. Grounding: every factual claim needs a document behind it, or the feature is a liability. Scope of knowledge: define the corpus boundary explicitly, because a system that silently answers from general knowledge when your documents are silent is worse than one that says so.
The Shape of the System
Architecturally the assistant is a pipeline with a feedback loop around it. Ingestion loads documents, splits them on structure, embeds them, and stores chunks with metadata. Serving embeds the query, retrieves and reranks candidates, builds a prompt, calls the model, validates the response, and logs everything. Evaluation sits beside serving, replaying recorded traffic against candidate prompts or models before anything ships.
from dataclasses import dataclass, field
from typing import List
@dataclass
class Chunk:
id: str
text: str
source: str
section: str
@dataclass
class Answer:
text: str
citations: List[str] = field(default_factory=list)
refused: bool = False
@dataclass
class AssistantConfig:
model: str = "gpt-4o-mini"
top_k: int = 8
rerank_to: int = 4
max_context_chars: int = 4000
temperature: float = 0.0
refusal_sentinel: str = "NOT COVERED"
def assemble(config: AssistantConfig, question: str, hits: List[Chunk]) -> str:
parts, used = [], 0
for rank, hit in enumerate(hits[: config.rerank_to], start=1):
block = f"[{rank}] {hit.source} > {hit.section}\n{hit.text}"
if used + len(block) > config.max_context_chars:
break
parts.append(block)
used += len(block)
return (
"Answer using only the passages.\n"
"Cite as [n]. If the passages do not cover it, reply "
f"{config.refusal_sentinel}.\n\n"
+ "\n\n".join(parts)
+ f"\n\nQuestion: {question}\nAnswer:"
)
cfg = AssistantConfig()
demo_hits = [Chunk("c1", "Refunds within 30 days of delivery.", "policy.md", "Refunds")]
print(assemble(cfg, "How long do I have to return something?", demo_hits))
Keep configuration in one dataclass like this. Half of all "the model changed its mind" incidents turn out to be a stale prompt assembled from defaults scattered across three modules.
One Request, End to End
With the pieces in place, the request path is short enough to reason about under pressure. Retrieval casts a wide net with hybrid search, a reranker narrows it to the passages that matter, and the prompt builder spends the context budget on those passages in a stable order. Generation runs at temperature zero so that a fixed question over a fixed corpus yields a stable answer you can diff.
| Stage | Input | Output | Failure to watch |
|---|---|---|---|
| Query understanding | Raw user text | Rewritten or decomposed queries | Over-cleaning that drops key terms |
| Hybrid retrieval | Query plus filters | Hundreds of candidates | Missed rare terms and IDs |
| Reranking | Query plus candidates | Three to eight passages | Cost spikes on long passages |
| Prompt assembly | Passages plus question | One bounded prompt | Context overflow, lost citations |
| Generation | Prompt | Grounded answer | Unsupported claims, no refusal |
| Validation | Answer plus passages | Accepted or retried | Regex that rejects valid prose |
| Logging | Everything above | Replayable trace | Missing prompt or model version |
Guardrails That Users Barely Notice
Safety layers work best when they are invisible on the happy path. Input screening blocks prompt injection and disallowed categories before money is spent on generation. Output screening checks for policy violations, leaked secrets, and claims unsupported by the retrieved passages. Rate limits and per-tenant quotas protect the budget. The trick is ordering: cheap deterministic checks first, model-based checks only on what passes, and a single retry before falling back to a canned response.
Groundedness checking deserves special attention because it is the guardrail users feel. Take each factual sentence, ask a small model whether the passages entail it, and either annotate, regenerate, or refuse. Refusing well matters as much as answering well: a short, honest "the documents do not cover this, here is where to look instead" preserves trust far better than a fluent guess.
Evaluation as a Release Gate
Turn the ten questions from scoping into fifty, including unanswerable ones, and score three things: correctness of the answer, faithfulness to the passages, and format validity. Wire that suite into your release process so a prompt, model, or chunking change cannot ship without numbers. Track the diff per case, because averages hide regressions that affect one important slice.
import json
from dataclasses import dataclass
@dataclass
class Case:
question: str
expected: str
must_refuse: bool = False
def score_case(case: Case, answer: str) -> dict:
produced_refusal = "NOT COVERED" in answer
if case.must_refuse:
return {"pass": produced_refusal, "kind": "refusal"}
expected_tokens = set(case.expected.lower().split())
produced_tokens = set(answer.lower().split())
overlap = len(expected_tokens & produced_tokens) / max(len(expected_tokens), 1)
return {"pass": overlap >= 0.6 and not produced_refusal, "kind": "answer",
"overlap": round(overlap, 3)}
def run_suite(cases, ask_fn) -> dict:
results = [score_case(c, ask_fn(c.question)) for c in cases]
passed = sum(r["pass"] for r in results)
return {"cases": len(results), "pass_rate": round(passed / len(results), 3),
"failures": [c.question for c, r in zip(cases, results) if not r["pass"]]}
suite = [Case("What is the refund window?", "30 days"),
Case("Who will win the election?", "", must_refuse=True)]
print(json.dumps(run_suite(suite, lambda q: "The refund window is 30 days."), indent=2))
Store results per run rather than only the latest; being able to say "faithfulness dropped when we changed the chunk size" is what turns evaluation into engineering.
Operating the Thing
Production surfaces three numbers first: latency percentiles, cost per conversation, and groundedness over time. Latency is dominated by prefill length and decode speed, so cap context, cache the shared prefix of your system prompt, and stream tokens to hide decode time. Cost follows tokens almost linearly, which makes prompt trimming and a smaller model on easy cases the highest-yield optimizations. Groundedness drifts as the corpus changes, so sample live traffic, run it through the evaluation suite nightly, and alert on the trend rather than on individual complaints.
Observability means each request logs the prompt version, model snapshot, retrieved chunk ids, timings, and token counts, with a stable trace id the support team can quote. Add canary rollout for prompt and model changes, a fast rollback path, and a dashboard that shows refusal rate by topic â a sudden rise usually means a corpus gap, not a model problem.
What a Strong Demo Shows
Present the system on your ten real questions, including two refusals and one hard multi-document case. Show the trace for one answer end to end, then the evaluation report comparing your current build against the baseline, then the cost and latency numbers under load. Finally, show one broken case you found and fixed. Reviewers trust a project more when you have already told them where it fails. Leave them with the artifact that matters: a rerunnable script that fetches the corpus, rebuilds the index, runs the suite, and prints the same report on any machine, so the claim of quality survives the demo and can be checked a month later without you in the room.
đĄBuild in this order
Best Practices
- Write ten real questions with sourced answers before writing any code
- Fix temperature at zero for grounded QA so answers are reproducible and diffable
- Log prompt version, model snapshot, chunk ids, and timings on every request
- Make refusals machine-readable and treat them as a success case in evaluation
- Cap context length and cache shared prefixes to control both latency and cost
- Gate every prompt or model change behind the evaluation suite with per-case diffs
Key Takeaways
- Scope with real questions and expected answers; that list becomes the eval set
- The serving path is retrieve, rerank, assemble, generate, validate, log
- Guardrails belong in order: cheap checks first, model checks only on survivors
- Evaluation is a release gate, and per-case diffs beat aggregate scores
- Operate on latency, cost per conversation, and groundedness trends over time