{"slug": "my-rag-answers-were-wrong-and-it-wasn-t-the-model-fixing-pdf-extraction-in-a", "title": "My RAG Answers Were Wrong, and It Wasn't the Model: Fixing PDF Extraction in a LangGraph Pipeline", "summary": "Backend and AI engineer Sachin Shah traced a wrong answer in a LangGraph-based loan application review pipeline to broken PDF extraction and chunking rather than the GPT model, after a LangSmith trace showed the retrieved chunks never contained the income requirement the model was accused of ignoring. He built a small retrieval-inspection script that prints returned chunks with scores and metadata, which surfaced flattened tables, interleaved multi-column text, and repeated headers and footers. The pipeline, running on LangGraph, FastAPI, Azure OpenAI and Pinecone, cut review time from about 30 minutes to 2 across roughly 400 applications a day.", "body_md": "*By Sachin Shah · Backend & AI Engineer*\n\nA few weeks after our review pipeline went live, a back-office reviewer pinged me with a screenshot. The system had flagged an application as missing a minimum income requirement. The applicant's payslips were right there in the file. The requirement itself was in our rules. And the model had stated, very politely, that no such threshold existed.\n\nMy first reaction was the one most of us have. The model got it wrong, so I should fix the prompt.\n\nI spent most of two days doing exactly that. I rewrote the instructions, added examples, told it to be careful, told it to quote its sources. Some cases improved. Others got worse. It felt like adjusting a dial with no numbers on it.\n\nThe problem was never in the prompt. This post is about how I finally found that out, and what I changed so that the same class of mistake shows up in a test run instead of a reviewer's screenshot.\n\nAt work I built a multi-agent pipeline for reviewing loan broker applications. A broker sends in a set of documents, agents pull out the details, a validation agent checks them against lender requirements stored in Pinecone, and the result is either a drafted reply or a case for a human to look at. It runs on LangGraph for orchestration, FastAPI for the service, Azure OpenAI GPT models for the reasoning, and LangSmith for tracing. Review time dropped from about 30 minutes to 2, at roughly 400 applications a day.\n\nThe retrieval step is where this story lives. Here is the full path, with the debugging loop drawn underneath it.\n\nThe short version: the model only ever sees what retrieval hands it, and retrieval can only return what extraction and chunking managed to preserve. If the first three boxes are broken, nothing after them can be right.\n\nThe thing that finally moved me was a LangSmith trace. I had been looking at the model's output. I had never looked, properly, at what went into it.\n\nEvery LangGraph node shows up as a span in LangSmith, and the retrieval call inside the validation node shows its inputs and outputs. I opened the trace for the screenshot case and scrolled to the retrieved chunks. The income requirement was not in them. Five chunks came back, and none contained the number.\n\nSo the model hadn't ignored the rule. It had never been shown the rule. It answered from what it had, and what it had was the wrong material.\n\nAfter that I stopped debugging through the model and wrote a small script that prints what retrieval returns for any question:\n\n``` python\ndef show_retrieval(question: str, top_k: int = 5, **filters):\n    vec = embed(question)  # same embedding deployment used at index time\n    res = index.query(\n        vector=vec,\n        top_k=top_k,\n        include_metadata=True,\n        filter=filters or None,\n    )\n    for m in res.matches:\n        meta = m.metadata\n        print(f\"{m.score:.3f}  p.{meta['page']}  {meta['section']}\")\n        print(\"   \", meta[\"text\"][:300].replace(\"\\n\", \" \"))\n        print()\n```\n\nI ran this on the failing question and read the chunks the way the model would. It took about a minute, and it showed me things two days of prompt edits had hidden.\n\nReading chunk after chunk, the same four problems kept showing up. None of them had anything to do with GPT.\n\n**Tables came out flattened.** A requirements table with columns for loan type, minimum income and maximum exposure turned into one long line of numbers with no labels. A figure like `85,000` could belong to any row. Retrieval would sometimes find that chunk, and the model had no way to tell which number answered which question.\n\n**Multi-column pages interleaved.** Some lender documents use two columns. The extractor read straight across the page, so a sentence from the left column was spliced into the middle of one from the right. Embeddings of that text are a blur of two topics, so it matched neither well.\n\n**Headers and footers repeated everywhere.** Every page carried the lender name, a document title and a page number. Those lines ended up in every chunk. When a question mentioned the lender, half the index looked equally relevant, and the real answer lost out to boilerplate.\n\n**Scanned pages were empty.** A few documents were photographs of printed pages. The text layer was blank, so those pages went into the index as nothing. The rule existed in the source and didn't exist in the system.\n\nI had been treating the PDF as text. It's actually a drawing instruction set that happens to contain text, and the order, labels and structure I assumed were not guaranteed to survive extraction.\n\nI started with the pages that were empty, because they were the easiest to detect. If a page has almost no extractable text, treat it as a scan and send it to OCR.\n\n``` php\ndef extract_pages(path: str) -> list[dict]:\n    pages = []\n    with fitz.open(path) as doc:\n        for i, page in enumerate(doc, start=1):\n            text = page.get_text(\"text\", sort=True).strip()\n            source = \"text-layer\"\n            if len(text) < 40:                      # nothing usable on this page\n                text = ocr_page(page)               # render to image, run OCR\n                source = \"ocr\"\n            pages.append({\"page\": i, \"text\": text, \"source\": source})\n    return pages\n```\n\nThe `sort=True` flag matters more than it looks. It asks the parser to order text blocks by position, which went a long way toward fixing the two-column mess. For the worst layouts I split the page into column regions and read them one at a time.\n\nI also kept the `source` field. When something looks off later, I want to know whether that chunk came from the text layer or from OCR, because OCR errors look different from parsing errors.\n\nHeaders and footers were a simple counting problem. A line that appears on most pages after you strip the digits is boilerplate:\n\n``` php\ndef strip_repeated_lines(pages: list[dict], threshold: float = 0.6) -> list[dict]:\n    def norm(line: str) -> str:\n        return re.sub(r\"\\d+\", \"#\", line.strip().lower())\n\n    counts = Counter(\n        norm(l) for p in pages for l in set(p[\"text\"].splitlines()) if l.strip()\n    )\n    cutoff = max(3, int(len(pages) * threshold))\n    boilerplate = {line for line, n in counts.items() if n >= cutoff}\n\n    for p in pages:\n        p[\"text\"] = \"\\n\".join(\n            l for l in p[\"text\"].splitlines() if norm(l) not in boilerplate\n        )\n    return pages\n```\n\nReplacing digits with a placeholder is what lets \"Page 3 of 40\" and \"Page 4 of 40\" count as the same line. It caught footers I would never have thought to list by hand.\n\nMy first chunker split every 800 characters with some overlap. It's what the tutorials show, and it's what cut that requirements table into pieces.\n\nThe better approach was to respect the document. Headings start new chunks. A paragraph stays with its heading. A table is never split in the middle, and each of its rows is rewritten as a sentence-like line that carries its own column names:\n\n``` php\ndef table_to_rows(table: list[list[str]]) -> list[str]:\n    header, *rows = table\n    return [\n        \"; \".join(f\"{h}: {c}\" for h, c in zip(header, row) if c)\n        for row in rows\n    ]\n```\n\nA row now reads like `Loan type: Personal; Minimum income: 85,000; Maximum exposure: 40,000` instead of three loose numbers. The figure and its label travel together, so a chunk that gets retrieved can be understood on its own.\n\nEvery chunk also gets metadata, which ended up being as useful as the text:\n\n```\nchunk = {\n    \"id\": f\"{doc_id}-{section_id}-{n}\",\n    \"text\": f\"{section_title}\\n{body}\",   # heading is part of the embedded text\n    \"metadata\": {\n        \"doc_id\": doc_id,\n        \"lender\": lender,\n        \"section\": section_title,\n        \"page\": page_no,\n        \"kind\": \"table_row\" if is_table else \"paragraph\",\n        \"source\": page_source,           # text-layer or ocr\n    },\n}\n```\n\nPutting the section title in the embedded text helps the vector side. Putting the lender in the metadata lets me filter on it, so a question about one lender stops pulling in another's rules.\n\nAfter all of that I re-embedded the whole index from the cleaned chunks. That is slower than patching, but a half-fixed index leaves you unsure which version of a document you're testing.\n\nThis was the part I most wish I had done on day one. Prompt edits felt like progress because I had no way to say whether they were. I needed a yardstick that didn't depend on my mood.\n\nI collected real questions that reviewers actually ask, such as \"What is the minimum income for this loan type?\" and \"Does this lender accept this kind of document as proof?\" For each one I wrote down the document and page where the answer lives. It took an afternoon and about 60 questions, and it was dull work.\n\nThen a function that asks one thing: did the right source show up in the top results?\n\n``` php\ndef hit_rate(cases: list[dict], k: int = 5) -> float:\n    hits = 0\n    for case in cases:\n        res = index.query(\n            vector=embed(case[\"question\"]),\n            top_k=k,\n            include_metadata=True,\n            filter={\"lender\": case[\"lender\"]},\n        )\n        found = {(m.metadata[\"doc_id\"], m.metadata[\"page\"]) for m in res.matches}\n        if (case[\"doc_id\"], case[\"page\"]) in found:\n            hits += 1\n    return hits / len(cases)\n```\n\nI ran it before touching anything, and the number was embarrassing. I ran it again after each fix. The OCR fallback helped on a small slice of questions. The header and footer cleanup helped on many more. Table handling fixed almost all of the numeric questions that had been failing. Structure-aware chunking with metadata was the biggest single improvement overall, and by the end the hit rate was clearly higher than where it started, on a set that never changed between runs.\n\nI'm deliberately not putting a percentage on it here. The exact figure depends on my questions and my documents, and it wouldn't transfer to yours. What transfers is the habit: measure retrieval by itself, away from the model, before you touch the prompt.\n\nThe eval set also became a regression test. It lives in the repo and runs in CI, so a change to the chunker that quietly breaks table retrieval fails a build instead of reaching a reviewer.\n\nOnce retrieval returned the right material, the prompt edits I had been agonising over stopped being important. The original, plain prompt worked. The model was good at reading a clear table row and comparing it to an applicant's income. It had been good all along.\n\nThat was the humbling part. For two days I had been teaching a capable model to cope with bad context, and the right fix was to give it good context.\n\nBetter extraction didn't make the system perfect, and I never expected it to. Some documents are still bad. A faded scan, a handwritten note in a margin, a table that spans three pages with no repeated header.\n\nSo the confidence check from the start of the project stayed. A case goes to a human when the agent's confidence is low, when retrieval comes back with weak scores, or when a chunk it relies on came from OCR on a poor page:\n\n``` php\ndef route(state: ReviewState) -> str:\n    weak_retrieval = max(state.retrieval_scores, default=0) < MIN_RETRIEVAL_SCORE\n    shaky_source = any(c.source == \"ocr\" and c.ocr_conf < 0.8 for c in state.chunks)\n\n    if state.confidence < CONFIDENCE_THRESHOLD or weak_retrieval or shaky_source:\n        return \"human_review\"\n    return \"draft_reply\"\n```\n\nThe retrieval score and the OCR flag are the useful additions. They let the system admit when its evidence is thin, which is often a better signal than the model's own stated confidence. Reviewers get the uncertain cases with the retrieved chunks attached, so they can see what the agent saw in a few seconds and don't have to start from scratch.\n\nThe reviewer's screenshot looked like a model failure, and for two days I treated it as one. The real fault was upstream, in text that had been mangled before the model ever saw it. Fixing extraction and chunking, then measuring retrieval on its own, did more than any prompt change I made.\n\nIf your RAG answers are wrong, open the trace and read what was retrieved. It's usually the faster way to find out.\n\nI'm a Python backend and AI engineer working with FastAPI, Django, PostgreSQL, LangGraph and RAG, and I'm open to mid-level backend and AI engineering roles in India or remote. You can find me on [LinkedIn](https://www.linkedin.com/in/imsachinshah/), [GitHub](https://github.com/imsachinshah), or [X](https://x.com/imsachinshah0).", "url": "https://wpnews.pro/news/my-rag-answers-were-wrong-and-it-wasn-t-the-model-fixing-pdf-extraction-in-a", "canonical_source": "https://dev.to/imsachinshah/my-rag-answers-were-wrong-and-it-wasnt-the-model-fixing-pdf-extraction-in-a-langgraph-pipeline-13g1", "published_at": "2026-12-04 19:13:08+00:00", "updated_at": "2026-12-04 19:14:13.624792+00:00", "lang": "en", "topics": ["large-language-models", "ai-agents", "mlops"], "entities": ["Sachin Shah", "LangGraph", "LangSmith", "FastAPI", "Azure OpenAI", "Pinecone"], "also_reported_by": [], "takeaway": "Inspect the chunks retrieval actually returns, with scores and page/section metadata, before editing prompts — in this case the income requirement was absent from all five retrieved chunks, and flattened tables, interleaved two-column text and repeated headers were the real cause.", "recommendation": {"advice": "Print the top-k retrieved chunks with scores and metadata for every failing question before touching the prompt, and fix table, column and header extraction so the needed text survives chunking.", "playbook": "rag-retrieval", "playbook_url": "https://wpnews.pro/playbooks/rag-retrieval"}, "alternates": {"html": "https://wpnews.pro/news/my-rag-answers-were-wrong-and-it-wasn-t-the-model-fixing-pdf-extraction-in-a", "markdown": "https://wpnews.pro/news/my-rag-answers-were-wrong-and-it-wasn-t-the-model-fixing-pdf-extraction-in-a.md", "text": "https://wpnews.pro/news/my-rag-answers-were-wrong-and-it-wasn-t-the-model-fixing-pdf-extraction-in-a.txt", "jsonld": "https://wpnews.pro/news/my-rag-answers-were-wrong-and-it-wasn-t-the-model-fixing-pdf-extraction-in-a.jsonld"}}