On real client files, RAG usually breaks before retrieval
Split tables, tone marks lost in OCR and contract codes treated as noise are the usual culprits, so sort the files before parsing them.
In brief
- RAG failures on real documents usually start in parsing and OCR, ahead of embedding.
- Tables must be extracted separately and chunked by heading. Vietnamese scans need a tone-mark check.
- Add context to chunks, combine BM25 with embeddings and rerank. In its own tests, Anthropic measured a reduction in retrieval failures of up to 67%.
Anthropic cut retrieval failures by 67% in its own tests by adding context to chunks, combining embeddings with keyword search, and reranking. None of those steps can recover a table that was already broken when the file was read.
Take a hypothetical first week at a client. You get access to a shared folder of several hundred files: contract PDFs exported from Word, quarterly reports dense with tables, and a stack of crooked invoice scans with red stamps over the text.
The RAG demo ran smoothly on sample files. Here it gets the very first question wrong: “What is the payment deadline for contract 0457?”
Many engineers respond by swapping the embedding model or raising top-k, but the fault usually lies elsewhere. The answer is missing from the top 20 because the system never read that page correctly: the table was cut in half, OCR dropped the tone marks, and the embedding treated the code “0457” as noise.
The remedy is to trace the data from raw file to retrieval result, one stage at a time. For an FDE, the most valuable skill is identifying which stage failed before starting to fix anything.
Sort the files before parsing them
Avoid pushing the whole folder through a single parser. Open a few dozen files at random and divide them into three groups. Each fails in its own way and needs its own processing branch.
| Document type | Main risk | Suggested approach |
|---|---|---|
| PDF with a text layer (exported from Word) | Lost heading structure, repeated headers and footers | Layout-aware parser, chunk by heading |
| Table-heavy PDF | Rows cut apart, columns merged into one line of text | Extract tables separately, keep each with its heading |
| Scan or photo | Wrong tone marks from OCR, noise, stamps | Specialized Vietnamese OCR, or retrieval directly from page images |
The test is simple: try to select the text in the file. If you can, the file has a text layer. If you cannot, it is an image and needs OCR.
This step alone gives you a number to report to the client in the first week, such as the percentage of the archive that is scanned. That number determines most of the effort that follows.
Keep the parser from cutting a row in half
Read as ordinary text, a price list or payment schedule becomes a string of numbers with no record of which column each belongs to. Worse, a chunker that splits by token count can put the column headings in one chunk and the data rows in the next.
Cohere’s documentation on RAG over mixed data recommends Unstructured for parsing PDFs because it can separate tables from text. It also chunks tables and text by heading during parsing, so related elements stay in the same group.
IBM’s Docling takes a similar approach, using specialized models for layout analysis (trained on DocLayNet) and table structure recognition. A minimal starting point:
from docling.document_converter import DocumentConverter
converter = DocumentConverter()
result = converter.convert("q3_report.pdf")
markdown = result.document.export_to_markdown()
# Open the markdown and read it: does every table have all its rows and columns?
The final comment is the important part. Before indexing, read through a few of the hardest tables, such as those with merged cells or those that run across two pages. If a table is already broken here, no reranker will save it.
In Vietnamese scans, tone marks break first
Vietnamese uses the Latin alphabet with a large number of marks that indicate tone and distinguish vowels. To an OCR engine, each mark is a tiny detail that noise, faint strokes or a red stamp can erase.
A 2025 survey of Vietnamese document recognition observes that Tesseract supports Vietnamese, but its accuracy remains limited by how it handles diacritics and document noise.
When “Hạn thanh toán” (payment deadline) becomes “Han thanh toan”, BM25 can no longer match the words in the user’s question. When “bảo hành” (warranty) is read as “bào hành”, the embedding may pull in an entirely different topic.
So measure mark errors before indexing. Retype one page by hand as the reference, run Tesseract with lang="vie", then count the words whose letters are right but whose marks are wrong:
import difflib, unicodedata
import pytesseract
from PIL import Image
def strip_marks(s):
# U+0111 and U+0110 (d with stroke) do not decompose under NFD
s = s.replace(chr(0x0111), "d").replace(chr(0x0110), "D")
return "".join(c for c in unicodedata.normalize("NFD", s)
if unicodedata.category(c) != "Mn")
ocr = pytesseract.image_to_string(Image.open("invoice_01.png"), lang="vie")
ref = open("invoice_01_reference.txt", encoding="utf-8").read() # typed by hand
ocr_w = unicodedata.normalize("NFC", ocr).split()
ref_w = unicodedata.normalize("NFC", ref).split()
mark_errors = 0
sm = difflib.SequenceMatcher(a=ref_w, b=ocr_w, autojunk=False)
for tag, i1, i2, j1, j2 in sm.get_opcodes():
if tag == "replace":
for r, o in zip(ref_w[i1:i2], ocr_w[j1:j2]):
if strip_marks(r) == strip_marks(o): # same letters, different marks
mark_errors += 1
print(f"Words with wrong marks: {mark_errors}/{len(ref_w)}")
The NFC normalization step matters. The same character “ệ” can be stored as two different Unicode sequences, and without normalization you will count words that are in fact correct as errors.
The same survey describes a typical pipeline from the MC-OCR 2021 competition on invoices: CRAFT detects text regions, VietOCR recognizes the text, and rules then extract the information. The lesson is to split OCR into two stages, detection and recognition, so you can tell which one failed.
Another option is to skip OCR altogether. ColPali uses a Vision Language Model to create multi-vector embeddings directly from page images, avoiding the fragile text extraction step. For an archive of poor-quality scans, try ColPali alongside OCR and compare the results on the same set of questions.
Chunks need to know where they belong
Suppose parsing and OCR are clean. One problem remains: the chunk “Party B shall pay within 30 days of acceptance” does not say which contract it comes from, or which client.
Anthropic’s Contextual Retrieval addresses this gap. Before indexing, a model writes a short passage of context, usually 50 to 100 tokens, which is prepended to each chunk. For example: “From Article 5 of contract 0457 between company A and company B, payment terms section.”
That context also goes beyond the embedding. With Contextual BM25, the same contextualized chunk enters the BM25 index, so a question containing “0457” matches the clause even though the clause itself never mentions the code.
This is why BM25 earns its place. It is a ranking function based on exact word matches, so it catches what embeddings tend to miss: contract codes, reference numbers and proper names, all of which are plentiful in client documents.
By Anthropic’s own measurements, Contextual Embeddings reduced the top-20-chunk retrieval failure rate by 35%. Adding Contextual BM25 brought the reduction to 49%, and adding reranking took it to 67%. Applied to a test set with 100 failed retrievals, purely as arithmetic, the count would fall to 65, then 51, then 33.
Do not promise clients these figures. They were measured on Anthropic’s data, and your client’s invoice archive is a different matter. What carries over is the method: measure the failure rate on that particular archive after every single change.
Work through it in order
- Collect 20 to 30 real questions from the client’s users, each with the page containing the answer. This set is the yardstick for every later decision.
- Sort the files into three groups: PDFs with text, table-heavy PDFs and scans.
- Choose a branch for each group: a layout-aware parser (Unstructured, Docling) for files with tables, and Vietnamese OCR or ColPali for scans.
- Check a small sample from each group by eye, and run the mark-error script on the scans.
- Chunk by heading, then prepend the context passage to each chunk.
- Index the contextualized chunks in both embeddings and BM25, and add a reranker.
- Measure again how often the right chunk reaches the top 20 on your question set. Change one variable at a time, or you will not know where the improvement came from.
Common mistakes
The most common mistake is to judge the final answer without looking at the top-20 chunks. When an answer is wrong, you need to know whether retrieval or generation failed. The two call for completely different fixes.
The second is to strip Vietnamese marks from both index and query for “consistency”. Doing so erases the distinction between words with different meanings. If you need to normalize, keep a parallel version with the marks intact.
The third is to test only on clean files. The question set must include answers in tables with merged cells, answers on faint scanned pages, and questions containing codes. Real users will ask those questions.
When reading FDE job descriptions, look for phrases such as “document ingestion”, “OCR” and “unstructured data”. On a CV, a line such as “raised the correct-retrieval rate on an archive of scanned Vietnamese invoices from X to Y” carries far more weight than “built a RAG system”.
Clients never hand you clean data. The people who get the job done open the PDF and read it before they open a notebook.
Was this article useful?
Thanks for the feedback!
5 sources
- Introducing Contextual Retrieval · 2024-09-19
- Agentic RAG with mixed data (Cohere docs)
- Docling Technical Report · 2024-08-19
- A Survey on Vietnamese Document Analysis and Recognition: Challenges and Future Directions · 2025-06-05
- ColPali: Efficient Document Retrieval with Vision Language Models · 2024-06-27