Lab: Trace Real Traffic, Then Analyse Errors
Record every model call as an OpenTelemetry span with prompt and model versions, tokens and latency, redact personal data before it is stored, join user feedback, score a 10% sample with an online judge, then read the failures, name and count their types and turn them into test cases.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: The assistant and its FAKE model
- Step 2: Redact, then trace every call
- Step 3: Replay a day of traffic
- Step 4: Compare the versions from their traces
- Step 5: Score a 10% sample online
- Step 6: Read the failures and name them
- Step 7: Turn failure types into test cases
- Step 8: Swap in the real model
- Troubleshooting
- Check your understanding
- Apply it: stretch tasks
- Review prompt
Lessons of AI Evaluation
- What to Measure, Offline and Online Concept · 15 min
- Lab: Trace Real Traffic, Then Analyse Errors Lab · 30 min
- Building a Versioned Evaluation Set Worked example · 20 min
- Lab: An LLM Judge Checked Against Human Labels Lab · 25 min
- Evaluations as a CI Regression Gate Lab · 25 min
- Check: Read an Evaluation Report Knowledge check · 10 questions
What you will learn
- Trace production LLM calls with prompt and model versions, token usage, latency and user feedback, with personal data redacted, and score a sample of traces with online evaluations.
- Perform error analysis on failures and turn recurring failure types into new test cases.
Prerequisites: RAG Retrieval Evaluation, Grounding & Citations
01. Goal and setup
In this lab you instrument the Lumen help-centre assistant and replay one day of its traffic: 200 questions, a fifth of them answered by a new prompt version running as a canary. Every call becomes a trace with versions, tokens, latency, retrieved passages and a redacted copy of the text; user feedback is joined by request ID. You then compare the versions, score a 10% sample online, read and label the failures, count the labels and turn them into test cases for lesson 3.
You need: Python 3.12 or later and the OpenTelemetry SDK (tested with opentelemetry-sdk 1.45.2). No API key: the model is a FAKE stand-in, a few rules with deliberate flaws, and it runs on a simulated clock so that every number below repeats exactly. Step 8 shows the real model behind the same interface; it needs the anthropic package (tested with 2.9.0) and an API key.
lumen-traces/
├── assistant.py step 1: passages, retriever and the FAKE model
├── redact.py step 2: replaces personal data with placeholders
├── tracing.py step 2: one span per model call, written to traces.jsonl
├── traffic.py step 3: the questions of one simulated day
├── simulate.py step 3: replays the day, writes traces and feedback
├── show_trace.py step 3: prints one stored trace
├── report.py step 4: latency, tokens and feedback per prompt version
├── fake_judge.py step 5: FAKE judge (an answer key, not an LLM)
├── online_eval.py step 5: scores a 10% sample of the traces
├── review.py step 6: lists the traces worth reading
├── notes.csv step 6: your notes, one row per trace read
├── count_failures.py step 6: counts the failure types
├── to_cases.py step 7: drafts test cases from the failures
└── claude_model.py step 8: the real model behind the same interfacemkdir lumen-traces && cd lumen-traces
python3 -m venv .venv && source .venv/bin/activate
pip install opentelemetry-sdk==1.45.202. Step 1: The assistant and its FAKE model
The assistant has seven help-centre passages, one of them an outdated community forum post, a word-overlap retriever that returns the two best passages with a score between 0 and 1, and a model. The FAKE model answers with the first sentence of the top passage and cites it, unless the top score is below the threshold of the prompt version, in which case it says it could not find the answer. Prompt v7 is in production; the canary v8 lowers the threshold so that the assistant abstains less often, and it adds a friendly opening and closing line.
"""The Lumen help-centre assistant: a tiny retriever and a FAKE model.
The FAKE model is a few rules, not an LLM. It runs offline, gives the same
answer every time, and has realistic flaws for the traces to reveal.
"""
import re
import zlib
from dataclasses import dataclass
PASSAGES = {
"refunds#1": "Refunds. Monthly plans can be refunded within 14 days of a charge;"
" annual plans within 30 days of purchase.",
"uploads#1": "Upload limits. A single upload can be up to 250 MB on the Business"
" plan and 100 MB on the Pro plan.",
"forum-4821": "Forum: what is the max attachment size? Uploads are capped at"
" 100 MB per file, whatever plan you are on.",
"guests#1": "Guests. Guests can view and comment on projects they are invited"
" to, but they cannot create projects.",
"export#1": "Export. Admins can export all projects as CSV or JSON from"
" Settings > Data > Export.",
"sso#1": "Single sign-on. SAML single sign-on is available on the Business plan;"
" set it up under Settings > Security.",
"billing#1": "Billing email. Change the billing email under Settings > Billing;"
" invoices are sent to that address.",
}
STOP = set("a an the is are am i my me we our you your can do does how what which to"
" of on in for and or it be with from at there this that".split())
PROMPT_VERSIONS = {"v7": 0.25, "v8": 0.10} # each version's evidence threshold
def words(text: str) -> set[str]:
return {w for w in re.findall(r"[a-z0-9]+", text.lower()) if w not in STOP}
def retrieve(question: str, k: int = 2) -> list[tuple[str, float]]:
q = words(question)
scored = [(pid, len(q & words(text)) / max(len(q), 1))
for pid, text in PASSAGES.items()]
return sorted(scored, key=lambda pair: -pair[1])[:k]
@dataclass
class Reply:
text: str
model: str
input_tokens: int
output_tokens: int
finish_reason: str
def tokens(text: str) -> int:
return max(1, round(len(text) / 4)) # rough: about four characters per token
class FakeModel:
"""FAKE model with a simulated clock, so latencies repeat exactly."""
name, provider = "fake-lumen-1", "fake"
def __init__(self) -> None:
self.seconds = 0.0
def clock(self) -> float:
return self.seconds
def complete(self, version: str, question: str,
hits: list[tuple[str, float]]) -> Reply:
system = f"Lumen help-centre assistant, prompt {version}. Cite passage IDs."
context = " ".join(PASSAGES[pid] for pid, _ in hits)
top_id, top_score = hits[0]
if top_score < PROMPT_VERSIONS[version]:
text = "I could not find this in the Lumen help centre."
else:
sentence = re.split(r"(?<=[.?]) ", PASSAGES[top_id], maxsplit=1)[1]
text = f"{sentence} [{top_id}]"
if version == "v8":
text = f"Thanks for asking! {text} Anything else I can help with?"
reply = Reply(text, self.name, tokens(system + question + context),
tokens(text), "end_turn")
jitter = zlib.crc32(question.encode()) % 400 / 1000 # 0 to 0.4 s, repeatable
self.seconds += 0.35 + 0.018 * reply.output_tokens + jitter # simulated
return replyReply carries what a real API response gives you besides the text: the model that answered, token counts (estimated here at four characters per token) and why generation stopped. The simulated clock charges a fixed time per call plus a little per output token, so longer answers are slower, as with a real model. Check the retriever on one question:
python -c "from assistant import retrieve
print(retrieve('Can guests create new projects?'))"[('guests#1', 0.75), ('export#1', 0.25)]03. Step 2: Redact, then trace every call
Questions arrive with email addresses, phone numbers and card numbers in them. redact.py replaces each with a typed placeholder such as <EMAIL>. Card numbers are matched before phone numbers, because a 16-digit card would otherwise also match the looser phone pattern.
"""Replace personal data with typed placeholders before anything is stored."""
import re
PATTERNS = [ # order matters: card numbers before phone numbers
("EMAIL", re.compile(r"[\w.+-]+@[\w-]+(\.[\w-]+)+")),
("CARD", re.compile(r"\b(?:\d[ -]?){13,19}\b")),
("PHONE", re.compile(r"\+?\d[\d ()-]{7,}\d")),
]
def redact(text: str) -> str:
for label, pattern in PATTERNS:
text = pattern.sub(f"<{label}>", text)
return texttracing.py wraps each call in an OpenTelemetry span: a named, timed record with attributes. JsonlExporter stands in for a real exporter by appending finished spans to traces.jsonl; in production you would send them over OTLP to a backend such as Jaeger, Grafana, Langfuse or LangSmith, through a batching span processor rather than the simple one used here.
"""One OpenTelemetry span per model call, written as JSON lines."""
import json
import time
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import (
SimpleSpanProcessor, SpanExporter, SpanExportResult)
from assistant import retrieve
from redact import redact
class JsonlExporter(SpanExporter):
"""Stand-in for an OTLP exporter: appends each finished span to a file."""
def __init__(self, path: str) -> None:
self.path = path
def export(self, spans) -> SpanExportResult:
with open(self.path, "a", encoding="utf-8") as f:
for span in spans:
record = {
"trace_id": format(span.context.trace_id, "032x"),
"name": span.name,
"duration_ms": round((span.end_time - span.start_time) / 1e6),
**dict(span.attributes),
}
f.write(json.dumps(record) + "\n")
return SpanExportResult.SUCCESS
def setup(path: str) -> trace.Tracer:
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(JsonlExporter(path)))
return provider.get_tracer("lumen.assistant")
def answer(tracer, model, request_id: str, question: str, version: str,
now=time.perf_counter) -> str:
hits = retrieve(question)
start = now()
span = tracer.start_span(f"chat {model.name}", start_time=int(start * 1e9))
reply = model.complete(version, question, hits)
span.set_attributes({
# GenAI semantic conventions (status: Development, names can change)
"gen_ai.operation.name": "chat",
"gen_ai.provider.name": model.provider,
"gen_ai.request.model": model.name,
"gen_ai.response.model": reply.model,
"gen_ai.usage.input_tokens": reply.input_tokens,
"gen_ai.usage.output_tokens": reply.output_tokens,
"gen_ai.response.finish_reasons": [reply.finish_reason],
# this application's own attributes
"app.request.id": request_id,
"app.prompt.version": version,
"app.retrieval.ids": [pid for pid, _ in hits],
"app.retrieval.top_score": round(hits[0][1], 2),
"app.question": redact(question), # redacted before it is stored
"app.answer": redact(reply.text),
})
span.end(end_time=int(now() * 1e9))
return reply.textThree decisions in answer() matter more than the code around them:
- Standard names where they exist. The
gen_ai.*attributes and the span name (chatplus the model) follow OpenTelemetry's GenAI semantic conventions, so backends that know them chart tokens and latency per model without mapping. The conventions are still marked Development, so keep them in this one function. - Your own names for the rest. The conventions have no attribute for the prompt version, so
app.prompt.versionuses its own namespace, as do the request ID and retrieval results. Without it, no trace can tell you which prompt was worse. - Redaction before storage.
redact()runs before the text becomes an attribute, so the raw question never reaches the exporter. Redacting later, in the backend, is too late: the text has already been copied on the way.
04. Step 3: Replay a day of traffic
traffic.py holds the questions of the simulated day with how often each is asked, and the passages that a correct answer cites. The personal data in it are fictional test values.
"""The questions in one simulated day of traffic, with an answer key."""
QUESTIONS = [ # (weight, question, passages a correct answer cites)
(14, "Can I get a refund on a monthly plan?", ["refunds#1"]),
(12, "Can guests create new projects?", ["guests#1"]),
(10, "How do I export all my projects as CSV?", ["export#1"]),
(10, "What is the upload limit on the Business plan?", ["uploads#1"]),
(8, "How do I change the billing email? It is {email} now.", ["billing#1"]),
(6, "What is the max attachment size on the Business plan?", ["uploads#1"]),
(5, "How do I set up SSO and can guests create projects?",
["sso#1", "guests#1"]),
(4, "I was charged twice on card {card}, can I get a refund?", ["refunds#1"]),
(4, "Can I pay my invoices by bank transfer from Germany?", []), # not in docs
(4, "¿Cómo pido un reembolso?", ["refunds#1"]),
(3, "Call me on {phone} about a refund for my annual plan.", ["refunds#1"]),
(3, "Hi, I'm Ana Souza. Can guests comment on projects?", ["guests#1"]),
]
FILL = {"email": "[email protected]", "card": "4111 1111 1111 1111",
"phone": "+44 20 7946 0958"} # fictional test valuessimulate.py sends 200 requests through the traced assistant. A hash of the request ID sends a fixed fifth of the requests to prompt v8, as a canary release would. About a third of users click a thumb, and users who got a wrong answer are much more likely to click down. Feedback goes to its own file, because it arrives after the span has ended; the request ID joins the two.
"""Replay one day of Lumen traffic through the traced assistant."""
import json
import random
import re
import zlib
from pathlib import Path
from assistant import FakeModel
from tracing import answer, setup
from traffic import FILL, QUESTIONS
rng = random.Random(99)
for name in ("traces.jsonl", "feedback.jsonl"):
Path(name).unlink(missing_ok=True)
tracer, model = setup("traces.jsonl"), FakeModel()
weights = [w for w, _, _ in QUESTIONS]
with open("feedback.jsonl", "w", encoding="utf-8") as feedback:
for n in range(1, 201):
request_id = f"r{n:03d}"
_, template, needed = rng.choices(QUESTIONS, weights=weights)[0]
# canary: prompt v8 serves a fixed fifth of request ids, v7 the rest
version = "v8" if zlib.crc32(request_id.encode()) % 5 == 0 else "v7"
text = answer(tracer, model, request_id, template.format(**FILL), version,
now=model.clock)
cited = re.findall(r"\[([^\]]+)\]", text)
good = set(needed) <= set(cited) if needed else not cited
if rng.random() < 0.35: # about a third of users click a thumb
score = -1 if rng.random() < (0.04 if good else 0.5) else 1
feedback.write(json.dumps({"request_id": request_id, "score": score}))
feedback.write("\n")
print(sum(1 for _ in open("traces.jsonl")), "traces,",
sum(1 for _ in open("feedback.jsonl")), "feedback events")"""Print one stored trace, to check what was (and was not) recorded."""
import json
import sys
for line in open("traces.jsonl", encoding="utf-8"):
record = json.loads(line)
if record["app.request.id"] == sys.argv[1]:
for key, value in record.items():
if key == "trace_id":
value = value[:8] + "..." # random, so yours will differ
elif isinstance(value, str) and len(value) > 60:
value = value[:57] + "..."
print(f"{key}: {value}")python simulate.py
python show_trace.py r016200 traces, 76 feedback events
trace_id: d7bad631...
name: chat fake-lumen-1
duration_ms: 1051
gen_ai.operation.name: chat
gen_ai.provider.name: fake
gen_ai.request.model: fake-lumen-1
gen_ai.response.model: fake-lumen-1
gen_ai.usage.input_tokens: 83
gen_ai.usage.output_tokens: 24
gen_ai.response.finish_reasons: ['end_turn']
app.request.id: r016
app.prompt.version: v7
app.retrieval.ids: ['billing#1', 'refunds#1']
app.retrieval.top_score: 0.38
app.question: How do I change the billing email? It is <EMAIL> now.
app.answer: Change the billing email under Settings > Billing; invoic...The email address in request r016 was replaced before the span was written; the trace still shows which prompt and model answered, how long it took, what it cost in tokens and which passages were retrieved. That is enough to debug most failures without keeping the raw text.
05. Step 4: Compare the versions from their traces
report.py groups the traces by prompt version and reports what a dashboard would show: median and 95th-percentile latency, mean tokens, and the share of thumbs down among the calls that received any feedback.
"""Per prompt version: traffic, latency, tokens and user feedback."""
import json
import statistics
from collections import defaultdict
traces = [json.loads(line) for line in open("traces.jsonl", encoding="utf-8")]
votes = {}
for line in open("feedback.jsonl", encoding="utf-8"):
event = json.loads(line)
votes[event["request_id"]] = event["score"]
by_version = defaultdict(list)
for t in traces:
by_version[t["app.prompt.version"]].append(t)
print("version calls p50 ms p95 ms in tok out tok rated thumbs down")
for version, rows in sorted(by_version.items()):
ms = sorted(t["duration_ms"] for t in rows)
p50, p95 = statistics.quantiles(ms, n=100)[49], statistics.quantiles(ms, n=100)[94]
tok_in = statistics.mean(t["gen_ai.usage.input_tokens"] for t in rows)
tok_out = statistics.mean(t["gen_ai.usage.output_tokens"] for t in rows)
rated = [votes[t["app.request.id"]] for t in rows if t["app.request.id"] in votes]
down = rated.count(-1) / len(rated)
print(f"{version:<7} {len(rows):>5} {p50:>6.0f} {p95:>6.0f} {tok_in:>6.1f}"
f" {tok_out:>7.1f} {len(rated):>5} {down:>11.0%}")python report.pyversion calls p50 ms p95 ms in tok out tok rated thumbs down
v7 153 987 1143 75.4 22.5 55 15%
v8 47 1233 1364 74.9 35.6 21 19%The canary is clearly slower and costs more output tokens, because of its extra opening and closing lines: a cost you can now put a number on. Its thumbs-down share looks worse, 19% against 15%, but that rests on 21 ratings, and only 76 of the 200 calls received any feedback at all. A difference of one or two clicks is not evidence. Feedback tells you where to look; the next two steps look.
06. Step 5: Score a 10% sample online
An online evaluation applies a judge to a random sample of production traces. Lesson 4 builds and validates a real LLM judge; here a FAKE judge stands in for it. It is an answer key for the simulated questions, which no real system has, so read it as "the verdict a good judge would give".
"""FAKE judge: an answer key for the simulated traffic, not an LLM.
A real judge reads the question, the retrieved passages and the answer, and
needs validating against human labels first (lesson 4 builds one).
"""
import re
from redact import redact
from traffic import FILL, QUESTIONS
KEY = {redact(q.format(**FILL)): needed for _, q, needed in QUESTIONS}
def judge(question: str, answer: str) -> str:
cited = set(re.findall(r"\[([^\]]+)\]", answer))
needed = KEY[question]
ok = set(needed) <= cited if needed else not cited
return "pass" if ok else "fail"The sample is chosen by hashing the request ID with a salt, which is repeatable and does not depend on the content. The salt matters: simulate.py already used a hash of the same ID to assign versions, and sampling with that hash would select one version only. Each verdict is stored as its own record linked to the trace, with the attribute names that the GenAI conventions define for evaluation results.
"""Score a 10% sample of the day's traces with the same checks as offline."""
import hashlib
import json
from collections import defaultdict
from fake_judge import judge # to use a real judge: from claude_judge import judge
def sampled(request_id: str, rate: float = 0.10) -> bool:
# an independent hash: never reuse the one that assigns prompt versions
digest = hashlib.sha256(b"online:" + request_id.encode()).digest()
return int.from_bytes(digest[:8]) / 2**64 < rate
traces = [json.loads(line) for line in open("traces.jsonl", encoding="utf-8")]
sample = [t for t in traces if sampled(t["app.request.id"])]
results = defaultdict(list)
with open("evaluations.jsonl", "w", encoding="utf-8") as out:
for t in sample:
label = judge(t["app.question"], t["app.answer"])
results[t["app.prompt.version"]].append(label)
out.write(json.dumps({ # one evaluation record, linked to its trace
"trace_id": t["trace_id"], "request_id": t["app.request.id"],
"gen_ai.evaluation.name": "answers_from_sources",
"gen_ai.evaluation.score.label": label}) + "\n")
print(f"sampled {len(sample)} of {len(traces)} traces")
for version, labels in sorted(results.items()):
print(f"{version}: {labels.count('pass')}/{len(labels)} pass")python online_eval.pysampled 20 of 200 traces
v7: 13/17 pass
v8: 2/3 passFour of the 17 sampled v7 answers fail, a far more informative signal than the thumbs. The three v8 traces are too few to say anything about the canary: to compare versions online, sample enough calls of each version, for example by raising the rate for the canary.
07. Step 6: Read the failures and name them
Error analysis starts with reading. review.py lists every trace with a thumbs down and every sampled trace the judge failed, with the question and the start of the answer.
"""List the traces to read: every thumbs-down and every failed sampled trace."""
import json
traces = {}
for line in open("traces.jsonl", encoding="utf-8"):
t = json.loads(line)
traces[t["app.request.id"]] = t
down = {json.loads(line)["request_id"] for line in open("feedback.jsonl")
if json.loads(line)["score"] == -1}
failed = {json.loads(line)["request_id"] for line in open("evaluations.jsonl")
if json.loads(line)["gen_ai.evaluation.score.label"] == "fail"}
for request_id in sorted(down | failed):
t = traces[request_id]
flags = ("thumb-down " if request_id in down else "") + (
"judge-fail" if request_id in failed else "")
print(f"{request_id} {t['app.prompt.version']} {flags:<21} {t['app.question']}")
answer = t["app.answer"]
print(" ->", answer if len(answer) <= 78 else answer[:75] + "...")python review.pyr022 v7 thumb-down I was charged twice on card <CARD>, can I get a refund?
-> I could not find this in the Lumen help centre.
r023 v8 thumb-down Can I get a refund on a monthly plan?
-> Thanks for asking! Monthly plans can be refunded within 14 days of a charge...
r029 v7 judge-fail ¿Cómo pido un reembolso?
-> I could not find this in the Lumen help centre.
r047 v7 thumb-down What is the max attachment size on the Business plan?
-> Uploads are capped at 100 MB per file, whatever plan you are on. [forum-4821]
r048 v7 thumb-down How do I set up SSO and can guests create projects?
-> Guests can view and comment on projects they are invited to, but they canno...
r072 v7 thumb-down How do I set up SSO and can guests create projects?
-> Guests can view and comment on projects they are invited to, but they canno...
r099 v7 thumb-down I was charged twice on card <CARD>, can I get a refund?
-> I could not find this in the Lumen help centre.
r116 v7 judge-fail I was charged twice on card <CARD>, can I get a refund?
-> I could not find this in the Lumen help centre.
r155 v7 thumb-down How do I set up SSO and can guests create projects?
-> Guests can view and comment on projects they are invited to, but they canno...
r156 v8 thumb-down judge-fail I was charged twice on card <CARD>, can I get a refund?
-> I could not find this in the Lumen help centre.
r163 v7 thumb-down Call me on <PHONE> about a refund for my annual plan.
-> I could not find this in the Lumen help centre.
r176 v8 thumb-down I was charged twice on card <CARD>, can I get a refund?
-> I could not find this in the Lumen help centre.
r177 v7 thumb-down Call me on <PHONE> about a refund for my annual plan.
-> I could not find this in the Lumen help centre.
r190 v8 thumb-down Hi, I'm Ana Souza. Can guests comment on projects?
-> Thanks for asking! Guests can view and comment on projects they are invited...
r193 v7 judge-fail What is the max attachment size on the Business plan?
-> Uploads are capped at 100 MB per file, whatever plan you are on. [forum-4821]
r198 v7 judge-fail I was charged twice on card <CARD>, can I get a refund?
-> I could not find this in the Lumen help centre.Read each trace and write one row in notes.csv: what went wrong in your own words, and the passages a correct answer would cite. Do not start from a list of categories; after a few rows the same problems recur, and you give each a short, stable name. When the answer is fine, write no problem: a thumbs down can be about the policy. Look at r190 too: the customer's name went through redact() untouched, because regular expressions catch structured data, not names. That is a finding about your tracing, worth its own fix.
request_id,failure_type,expected,note
r022,refund wording missed,refunds#1,asks for a refund; the passage says refunded
r023,no problem,,answer is right; maybe unhappy with the policy itself
r029,non-English question,refunds#1,Spanish; the retriever matched nothing
r047,stale forum post,uploads#1,2024 forum post outranks the help article
r048,second question ignored,sso#1 guests#1,the SSO half is never answered
r072,second question ignored,sso#1 guests#1,same as r048
r099,refund wording missed,refunds#1,same as r022
r116,refund wording missed,refunds#1,same as r022
r155,second question ignored,sso#1 guests#1,same as r048
r156,refund wording missed,refunds#1,card digits dilute the match as well
r163,refund wording missed,refunds#1,phone digits dilute the match as well
r176,refund wording missed,refunds#1,same as r156
r177,refund wording missed,refunds#1,same as r163
r190,no problem,,answer is right; but the name was not redacted
r193,stale forum post,uploads#1,same as r047
r198,refund wording missed,refunds#1,same as r022"""Count the failure types from your notes, most frequent first."""
import csv
from collections import defaultdict
by_type = defaultdict(list)
with open("notes.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
by_type[row["failure_type"]].append(row["request_id"])
read = sum(len(ids) for ids in by_type.values())
print(f"{read} traces read")
for failure, ids in sorted(by_type.items(), key=lambda item: -len(item[1])):
print(f"{len(ids):>3} {failure:<26} {' '.join(ids[:4])}"
+ (" ..." if len(ids) > 4 else ""))python count_failures.py16 traces read
8 refund wording missed r022 r099 r116 r156 ...
3 second question ignored r048 r072 r155
2 no problem r023 r190
2 stale forum post r047 r193
1 non-English question r029More than half of the failures are one type, and it is a retrieval failure: users write refund, the passage says refunded, the word-overlap retriever finds nothing and the assistant abstains (card and phone digits make it worse, because they count as words). No prompt can fix that; stemming, synonyms or hybrid search can. The two-part questions are a generation failure for the prompt, and the stale forum post calls for removing outdated pages. Without the count, the most visible failure, the wrong upload limit, might have been fixed first.
08. Step 7: Turn failure types into test cases
A failure you have fixed can come back with the next prompt or model change. to_cases.py drafts one test case per distinct failing question. Placeholders go back to fictional values, because a test input should look like the real one: the digits of a card number changed the retrieval score, and <CARD> would not.
"""Turn every failure type into draft test cases for the evaluation set."""
import csv
import json
FICTIONAL = {"<CARD>": "4111 1111 1111 1111", "<PHONE>": "+44 20 7946 0958",
"<EMAIL>": "[email protected]"} # realistic but not real
questions = {json.loads(line)["app.request.id"]: json.loads(line)["app.question"]
for line in open("traces.jsonl", encoding="utf-8")}
seen, drafts = set(), []
with open("notes.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
text = questions[row["request_id"]]
if row["failure_type"] == "no problem" or text in seen:
continue
seen.add(text)
for placeholder, value in FICTIONAL.items():
text = text.replace(placeholder, value)
expected = row["expected"].split()
drafts.append({
"id": f"trace-{row['request_id']}", "input": text,
"expect": "abstain" if expected == ["abstain"] else {"cite": expected},
"tags": [row["failure_type"]], "source": f"trace {row['request_id']}",
})
with open("new_cases.jsonl", "w", encoding="utf-8") as out:
for draft in drafts:
out.write(json.dumps(draft, ensure_ascii=False) + "\n")
line = f"{draft['id']:<11} {draft['tags'][0]:<25} {draft['input'][:48]}"
print(line.rstrip())python to_cases.pytrace-r022 refund wording missed I was charged twice on card 4111 1111 1111 1111,
trace-r029 non-English question ¿Cómo pido un reembolso?
trace-r047 stale forum post What is the max attachment size on the Business
trace-r048 second question ignored How do I set up SSO and can guests create projec
trace-r163 refund wording missed Call me on +44 20 7946 0958 about a refund for mThese five drafts are the first real cases of the evaluation set you build in the next lesson, each tagged with the failure type it guards against. Write a few variants of each recurring type as well (other wordings of a refund request, other two-part questions), so that a fix that only matches one sentence does not pass.
09. Step 8: Swap in the real model
ClaudeModel has the same name, provider and complete() as the FAKE model, so the tracer does not change. The model ID comes from an environment variable, and the reply carries the token counts that the API reports.
"""The real model behind the same interface as FakeModel. Needs an API key."""
import os
import anthropic
from assistant import PASSAGES, Reply
PROMPTS = { # in a real project, load these from versioned files
"v7": "You answer questions about Lumen using only the passages given. Cite"
" each passage you use as [id]. If they do not answer the question,"
" say you could not find it in the help centre.",
}
class ClaudeModel:
provider = "anthropic"
def __init__(self) -> None:
self.client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
self.name = os.environ["ANTHROPIC_MODEL"] # e.g. claude-sonnet-5-5
def complete(self, version: str, question: str,
hits: list[tuple[str, float]]) -> Reply:
passages = "\n".join(f"[{pid}] {PASSAGES[pid]}" for pid, _ in hits)
response = self.client.messages.create(
model=self.name,
max_tokens=16000, # one cap for thinking and answer text together
system=PROMPTS[version],
messages=[{"role": "user", "content":
f"<passages>\n{passages}\n</passages>\n\n{question}"}],
)
text = "".join(b.text for b in response.content if b.type == "text")
usage = response.usage # input_tokens excludes prompt-cache reads/writes
return Reply(text, response.model, usage.input_tokens, usage.output_tokens,
response.stop_reason)To use it, install anthropic, set ANTHROPIC_API_KEY and, for example, ANTHROPIC_MODEL=claude-sonnet-5-5, then in simulate.py replace FakeModel() with ClaudeModel() and drop now=model.clock, so that the tracer measures real time. Answers, tokens and latencies will then differ from the output above.
Two details for real traffic. The Messages API reports prompt-cache reads and writes outside input_tokens, so add them if you want total input. And the Anthropic SDK can emit its own OpenTelemetry spans (a beta feature that leaves prompts and responses out unless you opt in); if you use both, count tokens from one source only.
10. Troubleshooting
11. Check your understanding
12. Apply it: stretch tasks
- An implicit signal. Add to
report.pythe share of requests followed by another request with a similar question within the same session (simulate a session ID first), and compare it with the thumbs-down share per version. - Names. Replace the regular expressions with a named-entity detector such as Presidio, or stop storing the question text and keep only its length, language and retrieved IDs. Measure what each choice costs you when you repeat step 6.
- Your project. Trace every request of your RAG tool with prompt and model versions, tokens, latency, retrieved IDs and redacted text, send a 10% sample to the judge you will validate in lesson 4, and keep a
notes.csvfor one day of real failures.
13. Review prompt
Without looking back:
- Which attributes does each span carry, which of them come from the GenAI conventions, and why does the prompt version need a name of your own?
- Why must redaction happen before an attribute is set, and what does a regular-expression redactor miss?
- Why is the thumbs-down share a poor way to compare the canary with production in this lab?
- Describe the error-analysis steps from reading traces to new test cases, and say why the biggest failure type here is not fixed with a prompt.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.