RnR FAQ: more questions (optional)¶
The long tail of FAQ.md: run stories (what a qwen3:8b run showed, and the lesson), design details and topics whose labs were cut to keep the capstone light (cost matrix, self-consistency, fairness, taxonomy discovery, Phoenix, batching). Their code may be gone; the lessons still hold. Start with FAQ.md.
The use cases¶
Where do evals, guardrails and cost fit?¶
| Topic | RnR use cases |
|---|---|
| Evals | Golden-set precision/recall per reason, hard cases, a business cost matrix, aspect extraction against golden labels, judge calibration (kappa) |
| Guardrails | Prompt injection inside review text, PII redaction, schema and enum checks, evidence quotes that must exist in the review, no invented claims in summaries or answers, fail closed when the model is down |
| Cost | Tokens per call from Ollama priced with a rate card, rules before the model, caching, thinking only when unsure, budgets and fallbacks, cost per 1,000 reviews |
| Observability | A trace per review (rules, model call, checks, decision) with timings and tokens; hand-rolled spans in OpenTelemetry's shape |
Data¶
Why templates for abuse and injection, and the LLM for genuine reviews?¶
- Genuine reviews need variety and natural wording; that is what the LLM is good at (
--llm). - Abusive, PII and injection texts must match their label exactly. A model asked to write abuse may soften or refuse it, and then the label is wrong.
- Rule: LLM where variety matters, templates where the label must be exact. See
data/text.py.
Can the LLM-written reviews make the golden set wrong?¶
- Yes: the model may add an aspect it was not given or flip a sentiment.
- The labels stay as the spec says, so a drifting text becomes a wrong row in the eval.
- Keep temperature moderate, spot-check a sample, and measure drift in phase 2 before trusting
--llmdata.
Design¶
Why keep the golden labels in a separate table?¶
So the AI code can never read the answer by accident. Only evals join review_labels; ai/ and api/ never touch it.
Moderation and guardrails (phase 1)¶
Why does the schema have evidence and reasons before the decision?¶
- The model writes fields in order, so it commits to "why" before "what".
- The evidence must be a real quote from the review; an invented quote is a sign the verdict is wrong, so it is held (
verdict_problems()). - Moderators see the quote in the queue, which makes their check fast.
Why are fake reviews caught by a rule and not by the model?¶
- One fake review looks like a happy buyer. The signal is the group: unverified, near-identical, same SKU, within 3 days.
- The model sees one review at a time, so it can't see the group. Code can (
find_duplicates()inworker/handlers.py). - When a burst is found, the earlier fakes that got through are taken down too.
What went wrong with mod-v1?¶
- It approved 0 of the first 50 reviews and gave confidence 1.0 to every answer, right or wrong.
- The prompt never explained the output fields. Structured output (
schema=, Ollama'sformat) forces the JSON shape, but the model never sees the field descriptions, so it filledreasonseven when approving. - Asking for evidence and reasons before the decision pushed a small model to find a problem in every review.
- Heavy injection warnings made it see injection in "Good overall. Packaging was good."
mod-v2inai/mod_prompts.pyfixes each one; lab 05 shows whether it worked.
Evals (phase 2)¶
Why are the prompt examples written fresh instead of copied from the data?¶
If the prompt contains the same sentences as the test set, the model can match them instead of understanding them, and the eval score goes up without the product getting better. Write examples that teach the idea in different words (SYSTEM_V2 in ai/moderation.py).
Why does a prompt version include its schema?¶
- The prompt, the output schema and the code that reads the answer change together; v2 swapped
decision+reasonsfor oneproblemfield. PROMPTSinai/mod_prompts.pykeeps them as one unit, converted to a commonVerdict, so the checks and the eval work for every version.llm_calls.prompt_versionthen tells you which version produced each decision and what it cost.
Should a review with a phone number or "contact me for rates" be rejected?¶
Not here. Our rule here is to mask the details and publish the review, because the opinion is genuine. A marketplace worried about buyers and sellers dealing off-platform could choose to reject it as spam; that is a business rule, so it lives in the prompt and the golden labels, not in the model's judgement.
Why is "contact details called spam" fixed in code and not in the prompt?¶
- mod-v2 already says "sharing contact details is NONE", and still called 3 of 550 such reviews SPAM. A prompt rule is a request, not a guarantee.
- The rule is clear and checkable: contact details found, model says SPAM, no link or ad in the text. Code can test that exactly (
contact_only_spam()inai/moderation.py). - It holds the review instead of approving it, because "Cheap cement, call 98xxx" really is spam. A held review costs about ₹5 of a moderator's time; a wrongly rejected buyer about ₹50 (
evals/costs.py). - Changing the prompt would mean re-scoring both datasets, and a new example risks being copied (like the 0.95 confidence).
- Rule of thumb: a clear business rule goes in code; the prompt is for judgement calls.
mod-v2 scored 100%. Is the moderation solved?¶
No. 100% on 50 reviews mostly says the test is too easy.
- The reviews come from templates: a few fixed sentences, reused. Real buyers write messier, and --llm data is closer to that.
- 50 reviews with 3 per type: one more mistake on abuse is a 33-point swing in its recall.
- The prompt's definitions use some of the same words as the abusive templates ("cheaters", "frauds"), which makes those easy.
- Next steps: run --n 0 on all 500, then regenerate with python 00_generate_data.py --llm and score again.
- Rule for the team: a perfect score is a reason to make the test harder, not to stop testing.
Why did mod-v2 report 0.95 confidence for every review?¶
Its prompt examples all say 0.95, and the model copied the number. A model's self-reported confidence follows the prompt, not how sure it is, so don't build thresholds on it. Agreement across repeated answers, and the cost of each mistake, are better signals.
How do I choose the hold threshold?¶
- Put a price on each outcome: a held review, an honest one rejected, a bad one published (
Costsinevals/costs.py). - Re-decide a saved eval run under each policy and add up the cost per 1,000 reviews; pick the cheapest (
cost()andstandard_policies()inevals/costs.py). - Check how the winner changes when a cost changes (moderators get scarcer, abuse becomes a legal risk).
- If the model writes one confidence value for everything, a threshold can only hold all or nothing; use another signal.
What do the cost-matrix prices mean, and who sets them?¶
They are business assumptions in rupees: ₹5 for a minute of moderator time, ₹50 for an honest buyer silenced, up to ₹200 for abuse on a product page. The business owner sets them, not the engineer; write them down in evals/costs.py and re-price when they change.
Why was mod-v1 more expensive than no model at all?¶
- It rejected 14 of 35 honest reviews (₹50 each) and held 21 more (₹5 each): ₹16,100 per 1,000 reviews.
- Sending every review to a human cost ₹4,100; publishing everything ₹12,600.
- A bad model isn't neutral, it adds cost. The eval is what tells you to switch it off.
What is self-consistency, and when is it worth the extra calls?¶
- Ask the same question several times at a higher temperature and count how often the answers agree.
- Agreement is measured; confidence is a number the model writes. Splits mark the grey zone worth a human.
- It costs k extra calls per review, so re-ask only where a mistake is expensive.
- Re-asking only rejects is cheap and protects honest buyers, but can't catch abuse the model approved.
- When we tried it on 14 grey-zone reviews, all 14 agreed 3 of 3 at temperature 0.8: no "unsure" signal on this data, only extra calls. That is why it is not a lab.
Is temperature 0 deterministic?¶
On the same machine, model file and Ollama build, nearly always (14 of 14 repeated exactly when we checked). It is not a promise across upgrades or hardware, which is why evals are rerun after any upgrade. Repeatable also doesn't mean right: a model can give the same wrong answer every time.
What does fairness mean for review moderation?¶
- Honest reviews get published whatever the language (English, Hinglish), tone (polite, blunt) or rating.
- Check it with slices: rejected and held rates per group of honest reviews, from a saved eval run.
- Small groups swing a lot; skip groups under 10 reviews.
- The first bias to look for here is tone: the angriest buyers often have the most useful complaint.
What is a counterfactual pair?¶
Two reviews that say the same thing with one attribute changed: English vs Hinglish, polite vs blunt, 4★ vs 1★. Both should get the same outcome; a pair that doesn't is a fairness bug even when the overall score is high. Eight such pairs found the real mod-v2 gap (blunt complaints rejected as abusive) that the golden set missed; those cases now live in evals/hard_cases.jsonl.
What is the override rate?¶
The share of automatic decisions a moderator later changed. It is a free, label-less quality signal from production: if it rises, the model, the prompt or the traffic changed. Every override is also a labelled example to add to the golden set.
Why did data generation stop with "token repeat limit reached"?¶
- At temperature 0.8 the model sometimes falls into a loop, writing the same tokens again and again. Ollama stops it and returns an error.
- It happens more with forced JSON output: if the model never closes the string, it keeps going.
- Fix in
data/text.py: cap the output (max_tokens=200), retry 3 times, then keep the template text for that review so a 30-minute run never dies on one bad call. - The same idea applies in production: one bad generation should cost one item, not the whole batch.
Why fix the abuse mistake with both a better prompt and a safety net?¶
- Abuse vs anger is a judgement call, so the real fix is the prompt:
mod-v3defines abuse by who the words are aimed at (a person, or the order) and adds rude-but-honest examples. - A new prompt needs a few runs to earn trust. Until then every ABUSIVE call from the model is held for a human (
HOLD_MODEL_ABUSEinai/moderation.py): about ₹5 per abusive review, instead of ₹50 for a silenced buyer. - Real abuse is still never published; it waits a little for a human.
- Switch the net off (
RNR_HOLD_ABUSE=0) once the model alone gets the hard cases and the golden set right.
If the safety net holds the mistakes, how do we still see them?¶
- Every saved row keeps the model's own answer (
model_decision), before any net changes it. - Lab 05 prints the model's own numbers under the product's: "honest rejected … by the model, before nets" and "right … model alone".
- It also lists the model mistakes the nets caught. Without this, a net makes a bad prompt look perfect.
- With the net on, the ABUSIVE precision/recall row shows 0 flagged: abuse is held, not rejected. Read the model-alone line instead.
mod-v3 fixed only 1 of the 4 blunt complaints. Why ship it?¶
- It was better or equal on every test: hard cases 80% → 85% (model alone), golden 50 still 100%, all 6 insults still caught, counterfactual pairs 6/8 → 7/8.
- Ship when nothing gets worse, not only when everything gets fixed. A small, safe gain is still a gain.
- 20 hard cases means one review moves the score 5 points, so treat it as "slightly better", not as proof.
- The 3 it still misses are held by the safety net, so no honest buyer is rejected meanwhile.
- Chasing those 3 with more prompt edits risks tuning to the test; the next lever is a different one (letting the model reason first, lab 10).
Observability (phase 3)¶
How does the trace id get from the API to the worker?¶
enqueue()(worker/queue.py) adds atraceparentto the job payload when it runs inside a span:00-<trace_id>-<span_id>-01, the W3C format.- The worker opens its
job.moderatespan with that traceparent, so it becomes a child ofqueue.enqueuein the same trace. - Without it you get two unrelated traces and can't connect "submitted" with "held".
- Across HTTP the same string goes in a header; OpenTelemetry propagators do that for you.
Why hand-roll tracing before using Phoenix?¶
- To see that there is no magic: a span is a row with ids and timings, and 100 lines of Python make them.
- The SQLite copy joins with your own tables (
llm_calls,moderation_decisionsontrace_id), which a hosted tool can't. - Our spans already have OpenTelemetry's shape, so Phoenix is one more sink (
tracing.add_sink()) that converts finished spans and exports them over OTLP, without touchingai/orworker/. We verified it against Phoenix 20.16: every span arrived with the same trace ids. - In production you'd usually instrument with OpenTelemetry directly and keep a small table only for joins you need.
Why does Phoenix need special attribute names?¶
- A backend only shows tokens, prompts and model names if it recognises the attribute names: the semantic conventions.
- Phoenix reads OpenInference names (
llm.token_count.prompt,llm.input_messages.0.message.content,openinference.span.kind). - A converter renames ours to those; unknown ones arrive as plain attributes.
- OpenTelemetry's own GenAI conventions (
gen_ai.*) are the vendor-neutral standard that tools are converging on.
Can tracing slow down or break the product?¶
- Yes, if it's careless. Here a failing sink is reported and ignored (
_flushinobs/tracing.py); a test checks a broken sink never fails a review. - A synchronous exporter would let a slow Phoenix slow the worker. Production uses a background batch exporter.
- Storage grows with every span; at volume, sample (keep all errors and holds, a share of the rest) and set retention.
In lab 06, why did the model share of a trace fall from 99% to 14%?¶
- One worker moderates jobs in order, so the 6th review waited 8 s in the queue for 1.3 s of model (
queue_wait_sonjob.moderate). - The trace measures what the buyer waits for: queue + model. With a backlog, the queue dominates.
- Fixes are capacity, not prompts: more workers (limited by one local model), batching (phase 5), or rules that skip the model.
- Rejects took longer than approvals (2.0-2.4 s vs 1.25 s) because they write evidence: 32-40 output tokens vs 21. Output tokens drive model time.
Why does a moderator's decision go into the same trace, hours later?¶
- A trace is the review's story, not one request: submitted, held by the net, rejected by a person. One id answers "what happened to RV00064?".
repo.human_decide()continues the trace under its root span; the gap before it on the waterfall is the time the review waited for a human.overrides=Truemarks a human who changed an automatic decision: the same signal as the Ops override rate, now with the model's input and answer one click away.- Long-running traces skew "total ms", so compare model time and queue time, not the total, for reviews a human touched.
Aspects and scores (phase 4)¶
What does the evidence check catch?¶
- A quote the review doesn't contain: the model paraphrased or invented it (
quote_found()). - A code from another category, and the same aspect twice (
check()). - The bad mention is dropped, not the whole review, and counted by the aspect eval (
dropped).
Why are aspect bars hidden under 3 mentions?¶
- One mention is an anecdote; a bar makes it look like a finding.
MIN_MENTIONSlists them as "hidden" instead. - Like
PRIOR_WEIGHT, it's a product decision: higher means fewer flukes and slower to show a real problem.
Why extract aspects after moderation and not in the same call?¶
- You'd pay to analyse reviews you then reject, and one prompt doing two jobs is harder to eval and version.
- Enrichment runs only on APPROVED reviews, on the redacted text (
enrich_review()), queued byrepo.decide(). - Cost: one more call per approved review. Phase 5 measures it and tries cheaper options (batching, caching).
How does taxonomy discovery work, and why numpy instead of a vector database?¶
- Reviews → phrases → embeddings (nomic-embed-text) → groups of similar phrases → nearest known aspect. We tried it as a lab and removed it to keep the capstone light; the lessons are below.
- Groups near no known aspect are candidates; known aspects with no group are rare or phrased differently.
- Clustering compares every vector with every other: that's a matrix in memory, not a search. A vector DB (Chroma) earns its place in phase 6, for retrieval.
- A similarity threshold instead of k-means' "k": you don't have to guess the answer you came to discover.
Why did "jung" and "rust" land in different clusters?¶
- They share no words, and nomic-embed-text is mostly English, so Hinglish phrases often form their own islands.
- Extraction (lab 07) maps both to
rustbecause the model reads the meaning. Embeddings alone may not. - Options: a multilingual embedding model, or translate before embedding (both cost something).
The aspect eval says 99% F1, but lab 07 got "koi lumps nahi" wrong. Which do I trust?¶
- Both. The eval's 50 template reviews had one lumps mention and no Hinglish negation, so the eval never saw that case.
- Six hand-written reviews found two mistakes the 50 missed. An eval only measures what it contains.
- The fix is the moderation loop again: hard cases for aspects (negation, vague praise, product names), scored before any prompt change.
Why is recall 100% but precision only 88% on the --llm data?¶
- The model never missed what a buyer said; all errors are extra aspects.
- About half were the model's: "quality accha hai" → strength, "ISA 50x50x5" → dimension_accuracy (product names read as specs).
- About half were the label's: the data writer added things it was not asked for, plus a generator bug (next question).
- Precision errors move the bars little here (2.9 points on average), so phase 4 shipped with asp-v1.
How can a golden label be wrong if the label came first?¶
- The label is right about the spec; the LLM writer can still add to the text. "Mention exactly these points" is a request, not a guarantee.
- datagen-v1 also told the writer "delivery was 2 days late" when the label had no delivery complaint (16 of 395 reviews). Fixed in datagen-v2 (
_late_but_not_a_complaint()indata/text.py). - Rule: read the disagreements (
--show) before blaming the model. Template data can't drift; LLM-written data can.
Should "good quality" be an aspect?¶
- Decided no: it's an overall opinion, like "Good overall". A "quality: 85%" bar tells a category manager nothing to act on.
- The model still maps it to strength sometimes (5 of 14 extras). The fix belongs in the prompt and hard cases, not the taxonomy.
Why did taxonomy discovery put 584 mentions in one cluster?¶
- Cosine thresholds are model-specific. With nomic-embed-text, unrelated review phrases score 0.6-0.75, so 0.7 chains them together.
- True aspect matches scored 0.82-0.95. At 0.85 to group and 0.82 to match: 76 clusters, 20 of 23 aspects found.
- Calibrate any similarity threshold on pairs you know before you trust it; a new embedding model needs new numbers.
Discovery said documentation and price_value have no cluster. Are buyers not talking about them?¶
- They are. Their clusters scored 0.80 and 0.81, just under the 0.82 match line.
- 0.78-0.82 is an overlap zone: real matches and false ones ("Bought GI wire 12 gauge" at 0.81) sit side by side. No threshold separates them; a person reviews that band.
- Rule: a threshold gives you three groups (sure yes, sure no, look at it), not two.
Why is aspect extraction 3-4x slower than moderation?¶
- Output tokens set model time. Moderation writes ~21 tokens for an approval; extraction writes a quote per aspect (~67 tokens) on a longer prompt.
- ~6 s per approved review is ~3 hours of model time a day at 2,000 reviews. Phase 5 measures and cuts it (thinking off, batching, caching).
Cost (phase 5)¶
Why price input and output tokens separately?¶
- Providers charge output 4-5x input, and the two have different levers.
- Moderation pays 89% of its price for input (a 779-token prompt, 24 tokens out): shorten or cache the prompt. Extraction writes ~94 tokens: ask for less output.
- Lab 09's "Input %" column says which lever to pull.
Why does self-hosting cost more than the API in lab 09?¶
- A GPU bills every hour, busy or not; at laptop speed one handles ~12,600 reviews a day, so the best case is ~₹0.17 per review. The small API tier is ~₹0.014.
- Self-host beats the large tier above ~3,000 reviews a day. It beats small and mid only with a faster server GPU or parallel requests (
speedup_vs_laptop,parallel_requests). - Cost is rarely the only reason: data residency, fixed budgets and no rate limits can decide it.
Is a response cache safe for moderation?¶
- Yes, when the answer depends only on the request: temperature 0, same text, prompt version, model, schema and think flag. All of those are in the key (
cache_key()). - A new prompt version never reads old answers; failed or invalid answers are never stored.
- Evals never cache: a cached answer would hide the model's speed and cost, and a run would measure yesterday.
- See it:
11_gateway.pystep 1 (cache potential in your database, then the same reviews twice).
Why didn't we build "skip extraction when there is nothing to extract"?¶
Every honest review in our data has at least one golden aspect, so a pre-filter would save nothing here. Measure before you build a lever; in B2C, where "Good product" reviews are common, it would pay.
Batching or parallel requests: what's the difference?¶
| N reviews in one prompt | N prompts at once | |
|---|---|---|
| Saves | input tokens (instructions paid once) | GPU hours (more reviews per hour) |
| Matters for | API bills | self-host bills |
| Risk | cross-talk, a missing answer, one bad output fails the batch | queueing, memory pressure on a small GPU |
| What to check | decisions vs one at a time, quotes from a neighbour | reviews per minute, p50 latency |
Which errors should be retried?¶
- Retry what can succeed next time: connection errors, timeouts, 429, 5xx (
is_transient()), with backoff and jitter. - Don't retry a bad answer (invalid JSON at temperature 0 comes back the same) or a missing model (404: go to the fallback).
- Count both layers: gateway retries × job-queue retries is how many times one review can hit the model.
Model spend is ₹7 per 1,000 reviews and mistakes are ₹300. Does cost even matter?¶
- At this volume on a small API tier, quality matters more: one honest buyer silenced costs ₹50, about 7,000 moderation calls.
- Cost matters when it multiplies: a large model (₹350), thinking on every call, or 100x the volume. Lab 09 shows when you cross that line.
- So the rule is both numbers in one table, not "cost first" or "quality first".
Why does the Ops cost panel use eval calls?¶
- Until the worker has moderated real traffic, eval calls are the only calls with the active prompt. They run the same prompt on the same model, so they price it (
FAMILYinai/cost.py). - Once the worker runs, its own
moderationandaspectscalls are priced too, and calls per review come from real decisions (review_mix()).
Thinking fixed the blunt complaints but published an off-topic review. Why?¶
- On "Your app keeps logging me out, please fix it." the quick pass said OFF_TOPIC (right). With thinking, qwen3 reasoned its way to "a service complaint, publish it".
- More reasoning is not more correct: it fixes the mistakes it was aimed at and can create new ones on easy cases. That is why lab 10
--goldenruns the golden set too, not only the hard cases. - Escalation avoided it: the quick pass was confident, so it was never re-asked.
Batching cut the token bill in half. Why did self-host cost go up?¶
- The two meters disagree. An API bills tokens: input per review fell 633 → 178. A local GPU bills time, and time per review rose 1.45 s → 2.4 s.
- Output grew (20 → 31 tokens per review: ids and JSON wrapping), and output is what a GPU spends its time on.
- One at a time, Ollama most likely reuses the identical system prompt from the previous call and only processes the new review; a batch is a new prompt every time.
- Rule: batch for an API bill, not for your own GPU. Check both meters before you call a change "cheaper".
Why did parallel requests not speed anything up?¶
- Ollama ran one request at a time: throughput stayed 36 reviews/min and p50 grew with the number of workers (1.6 → 6.6 s). The requests just queued inside Ollama.
OLLAMA_NUM_PARALLEL=4 ollama servefailed because the Ollama app already held the port. Quit the app first, orlaunchctl setenv OLLAMA_NUM_PARALLEL 4and restart it.- Even then, on a 16 GB Mac four parallel requests share one GPU and its memory: expect less than 4x.
Why did the gateway let the budget go over (1,564 of 1,500 tokens)?¶
The budget is checked before a call and the tokens are known only after it, so it can overshoot by one call. Leave that margin, or reserve max_tokens up front and settle after the call.
Summary and Q&A (phase 6)¶
Why write the summary from counts instead of giving the model all the reviews?¶
- "Facts from code, words from the model." The counts are exact and are the same bars the page shows, so the summary can't disagree with them (
build_facts()inai/summary_facts.py). - Every number and citation can then be checked in code (
check()). A summary written from 80 raw reviews has numbers nobody can check. - The prompt stays ~the same size however many reviews a SKU gets. Lab 12 compares tokens with stuff-all and map-reduce.
What do the summary checks do with a bad point?¶
- Drop it, never fix it: a citation that isn't a review of this SKU or doesn't mention the aspect, a number not in the facts, a "pos" point on a 29%-positive bar.
- Citations are cleaned one by one; a point with no valid citation left is dropped. A headline with a stray number is replaced by a plain one.
- Dropped points are saved with the reason (
sku_summaries.body.dropped), so a run of drops shows up before buyers notice.
When does the worker rewrite a summary?¶
- First at 5 enriched reviews, then after every 5 more (
maybe_enqueue_summary()), not after every review: the box barely changes and each rewrite is a model call. - If the facts are byte-for-byte the same as last time (
Facts.digest()), the job skips the model. - A new prompt version (
RNR_SUMMARY_PROMPT) writes new rows next to the old ones, so you can compare before switching.
Why judge one claim at a time instead of the whole summary?¶
- "Rate this summary 1-10" gives a number nobody can check or act on. "Is this sentence backed by these reviews?" gives a yes/no you can verify by reading.
- Per-claim results add up to the useful numbers: % of points supported per strategy (lab 13
--strategies). - The judge sees only the counts and the cited reviews (
evidence_for()). Show it all 82 reviews and it supports claims the citations never made.
Why the quote in judge-v2?¶
- Same idea as evidence-first in moderation and aspects: the judge has to find the words before it decides.
- Code checks the quote is really in the evidence (
quote_found()). A SUPPORTED verdict with a made-up quote becomes UNSUPPORTED. - Lab 13 prints how often that check overrode the judge.
Why one review per chunk?¶
- Reviews are 1-3 sentences. Splitting would cut "bars cracked" from "only the B12 batch" and cite half a thought.
- Long documents (manuals, contracts) do need chunking: see
rag/lab 02.
How does the SKU filter work, and why not put it in the prompt?¶
- It's a
where={"sku_id": ...}on the Chroma query (retrieve()inai/ask.py): another product's reviews never reach the model. - "Only answer about this product" in a prompt is a request; a filter is a guarantee. Same lesson as tier filters in
rag/lab 06. - Retrieved ids are also re-checked against the database (
allowed): a review rejected after it was indexed is never cited.
How does the index stay in sync with moderation?¶
- On read: before a SKU's question,
sync()compares its published reviews with the index by text hash, embeds only new or changed ones and removes the rest. - Cheap at this scale (one index lookup per question). At high volume you'd index on write, in a job like enrichment.
- Changing the embedding model means a new index: old and new vectors aren't comparable. Delete
data/chroma/to rebuild.
How do I pick the distance threshold?¶
- From data, not by feel: save each question's distances, and a sweep shows, per threshold, answerable questions that keep a relevant review vs unanswerable ones stopped.
- Pick the knee: past it you only let junk reach the model. It's model-specific (nomic-embed-text scored unrelated phrases 0.6-0.75 similarity in taxonomy discovery).
- The gate is the cheap layer; the citation checks are the safe one. Don't make the gate do the checks' job.
Why score RAG per failure mode instead of one accuracy number?¶
- Each has a different fix: routing (router rules), retrieval (embedder, k, hybrid search), citations (answer prompt), refusals (gate, prompt), faithfulness (prompt, checks).
- Retrieval is scored without a judge: golden aspects say which reviews are relevant. Spend judge calls only on the answer text.
The summary check dropped "Several buyers reported late delivery". Wasn't that true?¶
- Yes: 3 of 11 delivery mentions were complaints. sum-v1's check dropped any negative point on a mostly-positive bar, so it threw away a true minority view (a human labelled it supported in lab 13).
- The check now asks two narrower questions: do the cited reviews take the point's side, and does the point claim a majority ("most", "all") the counts don't show (
check_point()). - Rule: a check should test a fact, not a style. "Is it the majority view?" was a style rule dressed as a fact.
Why did judge-v1 beat judge-v2, which has a rubric and examples?¶
- On the 40 planted claims, v1 kappa 0.95, v2 0.75; v2 missed 3 of 4 wrong numbers. A longer prompt gives a small model more to misread, and quote-first can anchor it on the counts line it just copied.
- That is the point of calibrating: the "better-looking" judge lost. 3 hand labels can't settle it; 20 can start to.
- Wrong numbers are better caught in code anyway (
stray_numbers()). Keep the judge for meaning: sides, overreach, what a review really says.
Why did stuff and map-reduce fail on the biggest SKU?¶
- The JSON answer hit the output cap (600 / 500 tokens) and was cut off mid-object, so it failed validation. qwen3 writes long points when it reads 67 raw reviews.
- Caps are now 1,200 / 1,000. The real lesson: strategies that read raw text get longer and slower with the data; grounded's prompt and answer barely changed.
The checks dropped a misleading point and the defect disappeared from the summary. Now what?¶
- sum-v2 wrote "Few buyers are dissatisfied with bendability, 17 of 24". The check was right to drop it, and then nothing in the box mentioned the B12 defect.
- What must be in the output is guaranteed by code, not requested in a prompt:
ensure_top_complaint()writes a plain point from the facts when no kept point covers the top complaint. - Lab 12 reports the model's own coverage (
complaint_by_model) so prompt versions are still compared honestly.
Why limit the length of ids and sentences in the schema?¶
- The answer kept overflowing the output cap. Limit the list to 3 ids and the model wrote 13 ids inside one string; limit each id and it listed them in the sentence.
- Ollama turns
maxItemsandmaxLengthinto hard limits while it generates. A limit in the schema holds; a request in the prompt is a suggestion.
Is judge-v2 fair to points about a minority?¶
- No. It marked "Several buyers reported late delivery" (3 of 11) CONTRADICTED because most buyers were happy. Your label said supported.
- So its faithfulness scores are pessimistic for minority points. Known, accepted for now; a judge-v3 rubric ("some" needs the cited reviews, "most/all" needs the counts) is the fix if it starts to matter.
Every number was in the facts and the sentence was still wrong. How?¶
- sum-v3 wrote "10 of 20 buyers mention delivery delays": 10 is delivery mentions, 20 is all reviews; 3 complained. Each number passed; the pair didn't.
bad_pairs()checks the pair: on a complaint, "X of Y" must be negatives of mentions (3 of 10); on praise, positives of mentions.- Rule: check facts at the level the reader reads them. A reader reads "10 of 20", not "10" and "20".
If the judge is biased, why not just write a better judge prompt?¶
- That is one option (a judge-v3 rubric). We took a cheaper one first: code first, judge the rest.
- Counts are exact, so code checks them (
bad_pairs()), then removes them from what the judge sees (judge_input()). The judge only answers "do the cited reviews say this?", the part code can't. - Every rule moved from the judge to code is one the judge can no longer get wrong, and one you never need to re-calibrate.