Search Tutorials
--Ads--Common RAG Errors and How to Fix Them
Error messages and failures you will meet in RAG: dimensions, parsing, chunking, vector databases and APIs.
Every RAG project runs into the same problems. Some fail loudly with an error message; others fail quietly, with plausible but wrong answers. This lesson is a field guide to both. It lists the common error messages with their causes and fixes, grouped by pipeline stage, then gives a diagnostic script that checks an index for the silent problems that cause most bad answers.
What you will learn
- The most common errors at each stage of a RAG pipeline, and how to fix them
- How to tell retrieval failures from generation failures
- How to run a health check on your chunks and index
- A step-by-step routine for debugging a bad answer
Prerequisites
Loud failures: error messages and fixes
Ingestion and parsing
| Symptom or message | Likely cause | Fix |
|---|---|---|
| Empty or near-empty text from a PDF | Scanned (image-only) pages | Run OCR; detect pages with almost no text and route them to OCR |
| Garbled characters, missing spaces, words split by hyphens | Unusual fonts or encodings, line-break hyphenation | Try another parser; normalise Unicode; join hyphenated line breaks |
UnicodeDecodeError | Reading a non-UTF-8 text file as UTF-8 | Detect the encoding or open with errors="replace" and log the file |
| Tables come out as jumbled text | Plain text extraction loses layout | Use a layout-aware parser and convert tables to Markdown |
Process killed / MemoryError | Loading huge files at once | Stream page by page (Large Documents) |
Embeddings
| Symptom or message | Likely cause | Fix |
|---|---|---|
| "Dimension mismatch", "expected dimension 1536, got 384" | Index built with one embedding model, queried with another | Use the same model for indexing and queries; re-create the collection after a model change |
| Input too long / token limit errors from an embedding API | Chunks longer than the model's input limit | Lower the chunk size; check token counts, not characters |
| Rate-limit (429) errors during indexing | Too many requests per minute | Batch inputs, add retries with backoff, or use a batch API |
| Truncated text with no error | Local models silently truncate inputs beyond their maximum sequence length | Keep chunks below the model's limit (often 512 tokens) |
Vector databases
| Symptom or message | Likely cause | Fix |
|---|---|---|
| Connection refused | Database not running, wrong host or port | Check the container and port mapping; check the URL in your environment |
| Duplicate results | Re-running ingestion added the same chunks again | Use deterministic ids (document id + chunk number) and upsert |
| Deleted documents still answered | Old chunks never removed | Delete by document id on update and removal (CRUD and Re-indexing) |
| Filtered search returns fewer than k results | Filter applied after approximate search | Use the database's filtered-search options, raise candidate counts, or partition data |
| Similarity scores look "backwards" | Distance (lower is better) read as similarity (higher is better) | Check the metric and what your database returns |
LLM APIs
| Symptom or message | Likely cause | Fix |
|---|---|---|
| 401 / authentication error | Missing or wrong API key | Set the key in the environment; check that .env is loaded |
| Context length / prompt too long | Too many or too large retrieved chunks, long chat history | Reduce k, rerank and keep the best, summarise history |
| Answer cut off mid-sentence | Output reached max_tokens | Raise max_tokens; check the stop reason in the response |
| Parameter errors after changing models | Newer models reject parameters older ones accepted | Read the provider's model documentation and migration notes |
| 429 or overloaded errors | Rate limits or provider load | Retries with exponential backoff; queue requests; use fallbacks |
Silent failures: wrong answers without errors
When an answer is wrong, first decide where it went wrong. Look at the retrieved chunks for that question:
- The right chunk was not retrieved: a retrieval problem. Causes include bad chunking, the wrong embedding model for your language or domain, missing keyword search for codes and names, a too-small k, wrong filters, or the document never being indexed.
- The right chunk was retrieved but the answer is wrong: a generation problem. Causes include the prompt not requiring grounding, too much noise in the context, the key chunk buried in the middle, or conflicting versions of a document.
- No chunk contains the answer: a content gap. The system should say it does not know; log these questions to find missing documents.
A health check for your index
This script catches the silent data problems that cause most bad retrieval. Point it at your chunks and their embeddings:
import hashlib
from collections import Counter
import numpy as np
from rag_helpers import embed
def health_check(chunks: list[dict], vectors: np.ndarray, probes: list[tuple[str, str]]) -> None:
"""chunks: [{"id", "text", "metadata"}]; vectors: (n, d) normalised; probes: [(question, expected_id)]."""
problems = 0
def report(ok: bool, message: str) -> None:
nonlocal problems
problems += not ok
print(("OK " if ok else "ISSUE ") + message)
report(len(chunks) == len(vectors), f"{len(chunks)} chunks and {len(vectors)} vectors")
words = np.array([len(c["text"].split()) for c in chunks])
tiny, huge = int((words < 20).sum()), int((words > 800).sum())
report(tiny == 0, f"{tiny} chunks under 20 words (headers, page numbers, fragments?)")
report(huge == 0, f"{huge} chunks over 800 words (may exceed the embedding model's limit)")
print(f" chunk length: median {int(np.median(words))} words, max {int(words.max())}")
hashes = Counter(hashlib.sha1(c["text"].strip().lower().encode()).hexdigest() for c in chunks)
duplicates = sum(count - 1 for count in hashes.values() if count > 1)
report(duplicates == 0, f"{duplicates} duplicate chunks")
norms = np.linalg.norm(vectors, axis=1)
report(bool(np.allclose(norms, 1.0, atol=1e-3)), f"vector norms between {norms.min():.3f} and {norms.max():.3f}")
report(not np.isnan(vectors).any(), "no NaN values in vectors")
missing_source = sum(1 for c in chunks if not c.get("metadata", {}).get("source"))
report(missing_source == 0, f"{missing_source} chunks without a source (citations will fail)")
ids = {c["id"]: i for i, c in enumerate(chunks)}
for question, expected_id in probes:
scores = vectors @ embed(question, query=True)[0]
rank = int((scores > scores[ids[expected_id]]).sum()) + 1
report(rank <= 5, f"probe '{question[:40]}': expected chunk at rank {rank}")
print(f"\n{problems} issue(s) found")
OK 1184 chunks and 1184 vectors
ISSUE 37 chunks under 20 words (headers, page numbers, fragments?)
OK 0 chunks over 800 words (may exceed the embedding model's limit)
chunk length: median 241 words, max 412
ISSUE 12 duplicate chunks
OK vector norms between 1.000 and 1.000
OK no NaN values in vectors
OK 0 chunks without a source (citations will fail)
OK probe 'How many leave days do new employees g': expected chunk at rank 1
ISSUE probe 'What is the refund window for annual pl': expected chunk at rank 9
3 issue(s) found
Probes are a handful of questions whose correct chunk you know. They are a quick smoke test after every change to chunking, embeddings or the index, and a stepping stone to a full golden test set.
Debugging one bad answer: a routine
- Reproduce it and log the exact question, the retrieved chunk ids and scores, the final prompt and the answer.
- Find the right chunk: search the chunk texts for the answer. If no chunk contains it, check parsing and whether the document was indexed.
- Check its rank for the question. If it is outside the top k, try hybrid search, query rewriting, reranking or different chunking.
- If it was retrieved, read the prompt the model received. Tighten grounding instructions, reduce noise, or put the best chunks first.
- Add the question to your test set so the fix stays fixed.
Key takeaways
- Most loud errors come from model mismatches, limits (tokens, rates, memory) and missing configuration.
- For wrong answers, first decide whether retrieval, generation or missing content is to blame.
- Run a health check for tiny, huge and duplicate chunks, bad vectors and missing sources.
- Use probe questions as a smoke test after every pipeline change.
Frequently asked questions
Why does my RAG system answer from general knowledge instead of my documents?
Either retrieval returned nothing useful, or the prompt did not require answers from the sources. Check the retrieved chunks first, then make the grounding instruction explicit and allow "I don't know".
Why do results change between runs?
Model outputs vary, approximate indexes can return slightly different neighbours, and data may have changed. Log the retrieved chunk ids so you can tell which part changed.
Practice exercises
- Run the health check on your own index and fix every issue it reports.
- Write ten probe questions and add the probe step to your ingestion job so it fails when a probe drops out of the top five.
Related tutorials
- Debugging LangChain and LlamaIndex Applications
- LLM Hallucinations
- Observability and Tracing