
Confidently Wrong: A Field Guide to RAG Bot Failures
A chatbot that answers from your own documents can still be wrong. It is just wrong with more confidence, and often with the right document sitting in front of it.
This article is a field guide to those failures. It covers the common ways a document-backed bot goes wrong, how to tell which part of the bot broke, and a small test you can run to catch most of them before your customers do.
These bots use a technique called RAG, short for retrieval-augmented generation. Before the bot answers, it looks up the most relevant passages in your documents and writes its reply from them. That gives it two steps that can fail: the lookup and the writing. The main idea of this guide is simple. When a RAG bot gives a wrong answer, find out which step failed before you change anything.
Every example comes from a real bot. Crumb is the chat assistant for Bready or Not, a made-up bakery in a made-up harbor town. It was built step by step in the series "Building your own AI chatbot", which starts with Part 1. You do not need to read the series to follow this article. If you want to run Crumb yourself, the code is in the bready-or-bot repo on GitHub.
Crumb also shows why RAG exists in the first place. An early version, with no documents at all, was asked what time the shop opens on Saturday:
We're open from 8am to 6pm on Saturdays. You can swing by then for a fresh loaf or some sweet treats!
The shop opens at 7. It closes at 3. Both numbers were made up. Once Crumb could read the bakery's own documents, it answered 7:00 am. It also picked up a whole new set of ways to be wrong, and they are harder to spot, because now the bot sounds confident and has paperwork.
Here is a rough map for your time. If you lead a team and do not write code, read through the field guide, then skip to "What to ask your team". That is about 14 minutes. If you build these bots, add the builder section and expect about 17 minutes of reading, plus however long you spend running the script. The failure most teams never test for is fourth in the field guide, so stay for it.
How these bots work, in plain words
Think of the two steps as two people working together. A researcher takes the customer's question, goes to the filing cabinet, and brings back the three pages that seem most related. A writer reads only those pages and composes a reply. The writer never sees the rest of the cabinet. In a RAG bot, the writer is the language model, the part most people mean when they say "the AI".
The researcher's step is called retrieval. To make it work, the documents are cut into short passages, usually called chunks. For the bakery, that is one chunk per section, such as "Opening hours" or "Custom cake orders". Each chunk is turned into a long list of numbers called an embedding, which captures roughly what the text means.
The question gets the same treatment, and the search returns the chunks whose numbers sit closest to the question's. How close they are is a similarity score: higher means more alike in meaning. Crumb keeps the three best chunks, the "top 3", and the single best one is the "top 1".
Either person can fail. The researcher can bring back the wrong pages. The writer can misread the right pages, or make something up when the pages do not help. From the outside, both failures look exactly the same: a confident, wrong answer.
Do not blame the model (yet)
When a bot gets something wrong, the first instinct is to blame the language model. Swap in a bigger one, add another line to its instructions, move on. Sometimes that is the right call. Often it is not, and the only way to know is to ask two questions in order.
Did the right passage come back? And did the answer use it?
Here is what the possible outcomes look like with real Crumb output, and who usually owns the fix.
| Right passage came back? | What the bot did | Real example | Who usually owns the fix |
|---|---|---|---|
| Yes | Answered correctly | "What time do you open on Saturday?" The opening hours came back first. Crumb: "According to our opening hours, we open at 7:00 am on Saturdays. Hope to see you here then!" | Nobody. Enjoy it while it lasts. |
| No | Admitted it did not know | "Will you bring a loaf to my house?" Search missed the delivery policy entirely. Crumb: "I do not know that yet. You might want to call the shop to ask about delivery options." | The engineers who built the search |
| No | Answered anyway | "How much is it?" right after asking about a pastry. Search brought back the parking passage, and Crumb replied: "The ferry lot charges $2.00 an hour. There are also four free 30 minute spots directly in front of the shop." | The engineers who built the search |
| Yes | Answered wrong | "How much notice do you need for a custom cake?" The current policy ranked first. Crumb answered from an outdated copy that was ranked second. | Whoever maintains the documents, and whoever writes the bot's instructions |
| Nothing to find | Invented something | "Do you sell bagels?" No document mentions bagels. Crumb suggested brioche or ciabatta instead. The bakery sells neither. | Whoever writes the bot's instructions, and whoever maintains the documents |
If you remember one thing from this article, make it this table. Two of its rows are search failures, and no amount of model upgrading fixes a search that brings back parking prices.
The parking reply comes from Part 4 of the series. In a later session with the same search miss, Crumb asked "Could you please provide more context about what you're asking the price for?" instead. The search failed the same way both times, but the bot covered for it differently. That is exactly why you check the search on its own.
The thirty-question test
So how do you answer the first question, "did the right passage come back?", without reading thousands of conversations? You write a small test.
Take thirty realistic questions, phrased the way customers actually ask them. For each one, note a short phrase that the correct passage must contain. Then run each question through the search step only, and check whether that phrase shows up in what comes back. If it does, the question is a hit. If it does not, it is a miss.
This beats reading final answers, because a final answer mixes both steps together. A wrong answer tells you that something broke. A miss tells you where. And if the passage came back and the answer is still wrong, you know the problem is in the writing step, and you can stop rearranging the filing cabinet.
You do not need code for this. Any bot that shows its sources will do: put the questions in a spreadsheet, ask each one, and tick a box when the right passage is among the sources. The builder section below has a script that does the same thing automatically.
Here are six of the thirty questions written for Crumb:
| Question | The right passage must contain | Kind of question |
|---|---|---|
| Where can I leave my car? | four free 30 minute spots | different words |
| What time does the shop close on Friday? | Friday: 6:30 am to 7:00 pm | direct |
| How much is it? (asked after "Do you teach classes?") | $65.00 | follow-up |
| How much is a quarter sheet cake and how much notice does it need? | Quarter sheet, serves 24: $95.00 and 5 business days | two documents |
| Do you sell bagels? | (nothing, there is no answer) | no answer |
| How much notice do you need for a custom cake? | at least 72 hours of notice | stale (the rule has changed) |
Here is what happened when I ran all thirty through Crumb's search, using the script from the builder section. The three questions with no answer have nothing to find, so they are not scored. That leaves 27.
| Kind of question | Questions | Right passage in the top 3 |
|---|---|---|
| Different words | 9 | 8 |
| Direct | 7 | 7 |
| Follow-up | 4 | 2 |
| Two documents | 4 | 4 |
| Stale | 3 | 3 |
| Total | 27 | 24 |
There is also a stricter measure: was the right passage the very first result? That happened for 17 questions. The four two-document questions can never pass this one, because no single passage holds both answers. So the fair score is 17 of 23. You will see that number again when we compare ways of cutting documents.
Only three questions missed: one in different words and two follow-ups. That is where the field guide starts.
The field guide
Different words
Customers do not talk like policy documents. Meaning-based search, the embeddings from earlier, handles that most of the time. "Where can I leave my car?" shares no key words with the bakery's parking passage, and the parking passage still came back first. Eight of the nine "different words" questions were hits.
The ninth was "Will you bring a loaf to my house?" The answer sits in a section called "Delivery and shipping", which starts with "We do not deliver and we do not ship." Nothing in the question says deliver. Search came back with the wifi question from the FAQ, the bread menu, and the refund policy. Crumb, to its credit, said it did not know.
Fix: rewrite the question before searching, or add the words customers actually use to your documents (an FAQ entry for "Can you bring bread to my house?" costs one line). Searching by keywords as well as meaning helps with other cases, such as product names and codes. Owner: the engineers, and whoever maintains the documents.
Follow-up questions
"How much is it?" and "And on Sunday?" are perfectly clear to a person in the middle of a conversation. To a search that only sees the latest message, they are nearly empty. "How much is it?", asked after "Do you teach classes?", brought back parking, drinks, and discounts, every single time. "And on Sunday?" sat right on the line: the opening hours were a near tie for third place, so it was a miss in some runs and a hit in others.
A blunt fix works well here: search with the previous question joined on, so the search sees "Do you teach classes? How much is it?" With that one change, both follow-ups came back in every run I tried, and the whole set reached 26 of 27 in the top 3.
Fix: include the conversation in the search. Owner: the engineers.
Split answers
Before search can work, the documents have to be cut into chunks. Cutting at each section heading keeps a topic together. Cutting every few hundred characters is simpler and very common, and it has no idea what it is cutting through. Here is the bakery's opening hours section cut every 300 characters:
--- chunk policies.md @0 (characters 0 to 300) ---
# Bready or Not Policies
> Fictional sample content for a tutorial.
## Opening hours
- Monday: closed
- Tuesday: closed
- Wednesday and Thursday: 6:30 am to 2:00 pm
- Friday: 6:30 am to 7:00 pm. We bake a second batch at 4:00 pm for the evening ferry crowd.
- Saturday: 7:00 am to 3:00 pm
- Sunday:
--- end of chunk ---
--- chunk policies.md @300 (characters 300 to 600) ---
7:00 am to 1:00 pm
## Preorders and pickup
...One chunk ends at "Sunday:". The next begins with hours that belong to no day at all.
To be fair to size-based cutting, the damage on this small set of documents was modest. In the top 3, it scored about the same as cutting by heading:
- Headings: 24 of 27
- 300-character chunks: 24 of 27
- 300-character chunks with 60 characters of overlap: 25 of 27
Overlap means each chunk repeats the end of the one before it, so a line cut in one chunk appears whole in the next.
The cost showed up in first place. Headings put the right passage first for 17 of 23 questions. Plain 300-character chunks managed 13, and overlap managed 16. With documents this small, that is all I would claim.
Fix: split on the document's structure, such as headings, or add overlap. Owner: the engineers.
Stale versions
This is the one that should worry you most.
Somebody keeps an old copy of the bakery policies, policies-2024.md, in the same folder as the current one. It happens in every company that has ever had a shared drive. The old copy says custom cakes need 48 hours of notice and no deposit. The current policy says at least 72 hours of notice and a 50 percent deposit. Both files start with the same title, "Bready or Not Policies". The old one does have a "Last updated: March 2024" line, but it sits above the first heading, so it never ends up in any chunk. Search cannot see the date at all.
Then a customer asks: "How much notice do you need for a custom cake?"
Search did its job. The current cake policy ranked first, and the old one came second. Crumb answered "According to our policies, we need at least 48 hours of notice for a custom cake." It gave the old 48 hours in all three fresh sessions. One of those replies even noticed something was off, adding "However, I do not know which specific policy to reference for the most up-to-date information", and still led with the wrong number.
The model was not completely in the dark, either. Crumb labels each passage with its file name, so the model could see that one passage came from policies-2024.md, and it still chose 48 hours.
For Saturday hours, the ranking went the other way. The old passage ranked first, the current one second, and Crumb gave the current 7:00 am in all three sessions. So the ranking did not predict the answer. Three sessions per question is a small sample, but it is enough to show that the old file can win, even when search puts the right passage on top.
The old file also caused a quieter problem. For "Who handles cake orders and how do I place one?", the old cake passage took up a slot in the top 3 and pushed out the passage that names the person who handles cake orders.
Fix: remove old versions from what the bot can search, or store a version or date with each passage and filter on it. Owner: whoever maintains the documents.
No answer exists
Search always returns something. It has no way to say "nothing here is relevant". It just ranks everything and hands over the top 3.
For "Do you sell bagels?", the best match was the FAQ entry about wholesale, with a score of 0.489. That is higher than the score of several correct hits, such as 0.342 for the parking passage on "Where can I leave my car?". So you cannot fix this with a score cut-off: a cut-off strict enough to drop the bagel results would also drop real answers.
Given three passages that say nothing about bagels, Crumb replied:
We don't have bagels on our menu at the moment. Our focus is on traditional breads and pastries. If you're looking for something similar, our brioche or ciabatta might be a good option.
It suggested brioche or ciabatta in three out of three sessions. The menu has neither. The oat milk question from the test set has the same shape: no document mentions oat milk, and search still came back with the drinks menu.
Fix: write the missing content (if people keep asking about bagels, one line saying you do not make them turns a gap into an answer), and tell the bot what to say when nothing it found fits the question. Owner: whoever writes the bot's instructions, and whoever maintains the documents.
Right passage, wrong answer
The cake notice above is one case. Another comes from Part 4. After a question about Saturday, a customer asked "And what about the other days?" The opening hours passage came back first, with every day of the week in it. Crumb replied, "I do not know that yet. It seems we only have information about weekend croissant sales." It had read the passage about when things sell out instead.
This is the case where blaming the model is fair.
Fix: clearer instructions, a stronger model, or removing conflicting content. Owner: whoever writes the bot's instructions.
Where the test itself went blind
Here is the uncomfortable part. With the old policy file in the folder, the thirty-question test still scored 24 of 27 in the top 3. It counted all three stale questions as hits. Meanwhile, Crumb was telling customers that cakes need 48 hours of notice.
The test was not lying. It checks whether the right passage came back, and it did. It just never asked whether a wrong passage came back with it. A hit means the right passage was present. It does not mean it was the only one.
The way to catch this is a second column, must_not_contain: phrases that must not appear in the top passages, such as 48 hours of notice. If one shows up, the question fails even though the right passage is there too. Choose these phrases as carefully as the others. Plain 48 hours would also match the current refund policy, which mentions 48 hours before pickup. The script below does not include this column yet, and adding it is a small change.
For the builders
This is the technical section. If you do not write code, skip ahead to "What to ask your team".
The checker is one Python file. It reads every .md file in a folder, cuts them into chunks, embeds the chunks and the questions, and checks the top 3 for each question. It works with any OpenAI-compatible service that offers embeddings. I used OpenRouter.
Set up
You need Python 3.12 or later. Some systems still ship an older python3, and the pinned packages will not install on it, so the commands below ask for python3.12 by name. If python3 --version already says 3.12 or later, plain python3 works too.
Make an empty folder, create a virtual environment, and install the three packages:
mkdir rag-check
cd rag-check
python3.12 -m venv .venv
source .venv/bin/activate
pip install openai==3.52.0 python-dotenv==1.2.4 numpy==2.5.5Create a file called .env in the same folder with your settings:
LLM_BASE_URL=https://openrouter.ai/api/v1
LLM_API_KEY=your-key-here
EMBED_MODEL=openai/text-embedding-3-smallDownload the bakery's sample documents from the part-4/content folder on GitHub into a folder called content. From the command line:
mkdir content
for name in about faq menu policies; do
curl -sSfo content/$name.md https://raw.githubusercontent.com/blobaugh/bready-or-bot/main/part-4/content/$name.md
doneThe script
Save this as rag_check.py:
"""Check whether retrieval brings back the passage that holds the answer.
python rag_check.py CONTENT_DIR questions.csv [--k 3] [--chunk-size N] [--overlap N]
[--with-previous]
A question is a hit when every phrase in its must_contain column (separated by |) appears in
the text of the top K chunks. Questions with an empty must_contain have no answer in the
documents. They are listed separately with their best score.
"""
import argparse
import csv
import os
import sys
from collections import Counter
from pathlib import Path
import numpy as np
from dotenv import load_dotenv
from openai import OpenAI, OpenAIError
def split_by_heading(text: str, source: str) -> list[tuple[str, str]]:
"""One chunk per '## ' section, with the document title and heading at the top."""
chunks, title, heading, body = [], "", "", []
def flush() -> None:
if heading and "\n".join(body).strip():
chunks.append((f"{source} / {heading}", f"{title}: {heading}\n" + "\n".join(body)))
for line in text.splitlines():
if line.startswith("# "):
title = line[2:].strip()
elif line.startswith("## "):
flush()
heading, body = line[3:].strip(), []
else:
body.append(line)
flush()
return chunks
def split_by_size(text: str, source: str, size: int, overlap: int) -> list[tuple[str, str]]:
"""Cut the text every `size` characters, sharing `overlap` characters between neighbors."""
starts = range(0, len(text), size - overlap)
return [(f"{source} @{start}", text[start : start + size]) for start in starts]
def embed(client: OpenAI, model: str, texts: list[str]) -> np.ndarray:
"""Embed all the texts in one call. Rows are scaled to length 1, so a dot product is cosine."""
vectors = np.array(
[item.embedding for item in client.embeddings.create(model=model, input=texts).data]
)
return vectors / np.linalg.norm(vectors, axis=1, keepdims=True)
def has_all(phrases: list[str], text: str) -> bool:
return all(phrase.lower() in text.lower() for phrase in phrases)
def main() -> None:
parser = argparse.ArgumentParser(description="Check retrieval against a set of questions.")
parser.add_argument("content_dir")
parser.add_argument("questions")
parser.add_argument("--k", type=int, default=3)
parser.add_argument("--chunk-size", type=int, help="split by size instead of by heading")
parser.add_argument("--overlap", type=int, default=0)
parser.add_argument("--with-previous", action="store_true", help="add the previous question")
args = parser.parse_args()
load_dotenv()
missing = [n for n in ("LLM_BASE_URL", "LLM_API_KEY", "EMBED_MODEL") if not os.environ.get(n)]
if missing:
sys.exit(f"Missing settings in .env: {', '.join(missing)}")
if args.chunk_size and not 0 <= args.overlap < args.chunk_size:
sys.exit("--overlap must be at least 0 and smaller than --chunk-size.")
try:
files = sorted(Path(args.content_dir).glob("*.md"))
rows = list(csv.DictReader(Path(args.questions).read_text(encoding="utf-8").splitlines()))
except OSError as error:
sys.exit(f"Could not read the input files: {error.strerror}.")
if not files:
sys.exit(f"No .md files found in {args.content_dir}.")
chunks = []
for path in files:
text = path.read_text(encoding="utf-8")
if args.chunk_size:
chunks += split_by_size(text, path.name, args.chunk_size, args.overlap)
else:
chunks += split_by_heading(text, path.name)
queries = [
f"{row['previous_question']} {row['question']}"
if args.with_previous and row["previous_question"]
else row["question"]
for row in rows
]
client = OpenAI(base_url=os.environ["LLM_BASE_URL"], api_key=os.environ["LLM_API_KEY"])
try:
chunk_vectors = embed(client, os.environ["EMBED_MODEL"], [text for _, text in chunks])
query_vectors = embed(client, os.environ["EMBED_MODEL"], queries)
except OpenAIError as error:
sys.exit(f"The embedding call failed ({type(error).__name__}). Check your .env settings.")
print(f"{len(chunks)} chunks from {len(files)} files, top {args.k}\n")
hits_at_1, hits_at_k, scored, no_answer = 0, 0, 0, []
by_category: Counter = Counter()
for row, scores in zip(rows, query_vectors @ chunk_vectors.T, strict=True):
best = np.argsort(-scores)[: args.k]
phrases = [p for p in row["must_contain"].split("|") if p]
if not phrases:
status = "n/a"
no_answer.append(
f" {row['id']:>2} {row['question']} (best score {scores[best[0]]:.3f})"
)
else:
scored += 1
at_1 = has_all(phrases, chunks[best[0]][1])
at_k = has_all(phrases, "\n".join(chunks[i][1] for i in best))
status = "hit@1" if at_1 else "hit" if at_k else "MISS"
hits_at_1, hits_at_k = hits_at_1 + at_1, hits_at_k + at_k
by_category[row["category"]] += at_k
numbers = " ".join(f"{scores[i]:.3f}" for i in best)
labels = " | ".join(chunks[i][0] for i in best)
print(f"{row['id']:>2} {status:<5} {row['question'][:44]:<44} {numbers} {labels}")
print(f"\nScored questions: {scored}")
print(f"Right chunk at top 1: {hits_at_1} of {scored}")
print(f"Right chunk in top {args.k}: {hits_at_k} of {scored}")
totals = Counter(r["category"] for r in rows if r["must_contain"])
for category, total in totals.items():
print(f" {category}: {by_category[category]} of {total}")
print("\nNo answer exists (retrieval still returned something):")
print("\n".join(no_answer))
if __name__ == "__main__":
main()The scoring rule is deliberately simple. For each question, the script takes the top 3 chunks by similarity, joins their text, and checks that every phrase in must_contain appears in it, ignoring case. Phrases are separated by |, which is how a two-document question asks for a fact from each file. A question is a "hit@1" when the first chunk alone holds every phrase, a "hit" when the top 3 together do, and a "MISS" otherwise. Because the rule looks at text and not at chunk names, it works the same whether you cut by heading or by size.
The similarity score is cosine similarity. The embed function scales every vector to length 1, so a plain matrix multiplication (query_vectors @ chunk_vectors.T) gives the score of every question against every chunk at once.
The script sends every chunk to the embedding service in a single call. That is fine for a bakery. A large document set needs to be embedded in batches.
The questions
Save this as questions.csv:
id,question,previous_question,must_contain,category
1,Where can I leave my car?,,four free 30 minute spots,different-words
2,Are pets allowed?,,Dogs are welcome on the patio,different-words
3,Can I buy a gift certificate for a friend?,,$10 to $100,different-words
4,Which of your pastries are free of animal products?,,None of our pastries are,different-words
5,What time does the shop close on Friday?,,Friday: 6:30 am to 7:00 pm,direct
6,How much is a croissant?,,butter croissant. $4.75,direct
7,Do you make lattes?,,We do not make espresso drinks,different-words
8,Will you bring a loaf to my house?,,We do not deliver,different-words
9,Who owns the bakery?,,owner and head baker,different-words
10,How do I sign up for a baking lesson?,,sourdough class runs on the first Sunday,different-words
11,What is your sourdough starter called?,,"Gerald, our sourdough starter",direct
12,Is there a discount near closing time?,,Last Call: in the final 30 minutes,direct
13,Is there anything with almonds in it?,,tree nuts (almonds),different-words
14,What is the shop phone number?,,555-0142,direct
15,Where does your flour come from?,,Halvorsen Mill,direct
16,What happens to a preorder that I never collect?,,not collected by then is donated,direct
17,How much is it?,Do you teach classes?,$65.00,follow-up
18,And on Sunday?,What time do you open on Saturday?,Sunday: 7:00 am to 1:00 pm,follow-up
19,Is it vegan?,How much is the Rye Me a River?,dark rye with caraway,follow-up
20,How far ahead do I need to order?,Can I order a custom cake?,at least 72 hours of notice,follow-up
21,How much is a quarter sheet cake and how much notice does it need?,,"Quarter sheet, serves 24: $95.00|5 business days",two-documents
22,Can I preorder a croissant for pickup and what does it cost?,,$4.75|Bread and pastry preorders,two-documents
23,Who handles cake orders and how do I place one?,,Priya Raman manages the front counter and custom cake orders|in person or by phone only,two-documents
24,How much is the deposit on a 6 inch cake?,,"6 inch round, serves 8: $48.00|50 percent deposit",two-documents
25,Do you sell bagels?,,,no-answer
26,What is the wifi password?,,,no-answer
27,Do you have oat milk for my coffee?,,,no-answer
28,What time do you open on Saturday?,,Saturday: 7:00 am,stale
29,How much notice do you need for a custom cake?,,at least 72 hours of notice,stale
30,Do I need to pay a deposit for a custom cake?,,50 percent deposit,staleA phrase with a comma in it needs double quotes around the whole field, as in rows 11, 21, and 24.
Run it
Start with the baseline, one chunk per heading:
python rag_check.py content questions.csvYou get one line per question with its status, the top 3 scores, and the chunks that came back. At the end you get a summary like this:
Scored questions: 27
Right chunk at top 1: 17 of 27
Right chunk in top 3: 24 of 27
different-words: 8 of 9
direct: 7 of 7
follow-up: 2 of 4
two-documents: 4 of 4
stale: 3 of 3The top 1 line counts all 27 scored questions, including the four two-document questions that can never come first. That is why the field guide calls it 17 of 23.
Here are the three misses from my run:
8 MISS Will you bring a loaf to my house? 0.412 0.398 0.388 faq.md / Do you have wifi? | menu.md / Breads | policies.md / Refunds and replacements
17 MISS How much is it? 0.286 0.265 0.255 faq.md / Is there parking? | menu.md / Drinks | policies.md / Discounts
18 MISS And on Sunday? 0.251 0.245 0.241 faq.md / Do you teach classes? | faq.md / When do things sell out? | policies.md / Preorders and pickupYour scores may differ in the third decimal place, and that matters for question 18. The opening hours passage and the preorder passage are within a few thousandths of each other for third place, so run the script a few times and you will most likely see question 18 flip between a miss and a hit. Expect 24 or 25 of 27 in the top 3. Every other count should match.
Now try the follow-up fix, which joins the previous question onto each follow-up before searching:
python rag_check.py content questions.csv --with-previousThen cut by size instead of by heading, with and without overlap:
python rag_check.py content questions.csv --chunk-size 300
python rag_check.py content questions.csv --chunk-size 300 --overlap 60Finally, the stale test. Make a second folder with the same four documents plus an outdated copy of the policies:
mkdir content-stale
cp content/*.md content-stale/Save this as content-stale/policies-2024.md:
# Bready or Not Policies
> Fictional sample content for a tutorial. This is an outdated copy kept on purpose to show the stale-version problem.
> Last updated: March 2024
## Opening hours
- Monday and Tuesday: closed
- Wednesday to Friday: 7:00 am to 2:00 pm
- Saturday and Sunday: 8:00 am to 12:00 pm
## Custom cake orders
Custom cakes need 48 hours of notice. No deposit is required. Orders are taken in person only.
## Discounts
Day-old bread is half price all day. Ask at the counter.And run it:
python rag_check.py content-stale questions.csvLook at questions 28 to 30. They all still count as hits, and the old policies-2024.md chunks sit right next to the current ones in the top 3. That is the blind spot from the field guide, in your own terminal.
Use your own documents
Point the script at a folder of your own .md files. If they use ## ` headings, the default splitting keeps each section together and skips any text above the first heading. If they do not, use `--chunk-size. Then write your own questions.csv with the same columns. Copy each must_contain phrase straight from the passage that answers it, and keep it short and specific enough that no other passage contains it. Use --k if your bot keeps more or fewer than 3 passages.
Any OpenAI-compatible service with an embeddings endpoint works. Change LLM_BASE_URL, LLM_API_KEY, and EMBED_MODEL in .env. If your bot uses a different embedding model, test with that one, because scores and rankings change with the model.
What to ask your team
You do not need to read the code to hold a team to this. These questions are enough:
- Can you show me what the bot retrieved for this answer?
- Do we have a fixed set of test questions with known answers, and what is our hit rate?
- Does the test check for outdated passages as well as missing ones?
- Who owns the documents, and how do old versions get removed?
- What does the bot do when nothing relevant exists?
- Do we re-run the test after every change?
If the answer to the first one is "no", start there. Everything else depends on it.
Where this breaks
The bakery has about two dozen passages, so landing the right one in the top 3 is easy. On a real document set with thousands of passages, expect lower numbers, and expect the gap between top 1 and top 3 to matter more.
The scores are noisy. Embedding the same text twice can change the third decimal place, and that was enough to flip "And on Sunday?" between a miss and a hit. Do not read meaning into differences that small. The bot results above come from three sessions per question, which is enough to show a failure exists and not enough to say how often it happens.
Phrase matching is crude. A correct passage worded differently from your phrase will count as a miss, so read every miss before you trust it.
Real systems often add steps this article does not cover: searching by keywords and meaning together, reranking the results with a second model, or having a model rewrite a follow-up into a complete question before searching. They help. They also make it even more important to test the search on its own, because there are more places for it to go wrong. Whatever you build, test it on your own documents.
Build your own Crumb
If you want to see where these failures come from in code, Part 4 of the series is where Crumb learns to answer from documents. All the code is at github.com/blobaugh/bready-or-bot.