Sub topic 2
Retrieval and context assembly as part of the pipeline
This chapter assumes you can call an LLM API from Python, read basic logging output, and understand what a prompt template is. In retrieval-augmented generation (RAG), the app searches a document store for relevant text and places that text in the prompt before the model answers.
Retrieval and context assembly
In a RAG app, the model is one step among several. The pipeline takes the user query, retrieves the top-k chunks, trims them to a token or character budget, and fills a prompt template. Each step is configuration you must version. Changing chunk size or top-k can change answers as much as changing the model.
def assemble_context(chunks, max_chars=2000):
"""Keep the highest-ranked chunks until the character budget is spent."""
selected = []
used = 0
for chunk in chunks:
if used + len(chunk) > max_chars:
break
selected.append(chunk)
used += len(chunk)
return "\n\n".join(selected)
chunks = ["Refunds take 5 days.", "Duplicate charges are reversed by support."]
print(assemble_context(chunks, max_chars=40))Evaluation: golden sets, programmatic checks, and model-graded scoring
A golden set is a fixed list of inputs, each paired with properties the output must have. Programmatic checks are plain code tests, such as "the answer mentions a refund." Model-graded scoring asks a second model to judge an output against a rubric. Start with programmatic checks because they are cheap and deterministic.
Outputs vary between runs, so run each case several times and report a pass rate.
def pass_rate(generate, text, checks, runs=3):
passes = sum(all(check(generate(text)) for check in checks) for _ in range(runs))
return passes / runsReleasing prompt and model changes behind evaluation gates
Treat a prompt, model ID, or retrieval setting as a release. Run the golden set against the candidate, and block the release if any case falls below your threshold. Prompt changes need the same gate as code changes.
Tracing LLM calls: inputs, outputs, tokens, and latency
Record each call with a trace ID, prompt version, model, latency, token counts, and status. Also log the retrieved chunk IDs. Those IDs tell you whether a bad answer came from retrieval or from generation.
Monitoring quality in production and closing the feedback loop
Sample live traces, score them with the same checks you use offline, and watch the trend. User feedback, such as thumbs-down clicks, should become new golden cases. Production failures then turn into tests before the next release.
Check your understanding
Exercise
A release raises retrieval top-k from 3 to 10. Offline checks still pass. What should your traces let you verify in production?
Show answer
Compare retrieved chunk IDs and token counts per request before and after the change, then check whether answer quality or cost moved.