cd /news/large-language-models/my-rag-answers-were-wrong-and-it-was… · home › topics › large-language-models › article
[ARTICLE · art-182000] src=dev.to ↗ pub= topic=large-language-models verified=true sentiment=↑ positive

My RAG Answers Were Wrong, and It Wasn't the Model: Fixing PDF Extraction in a LangGraph Pipeline

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.

recommendation

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.

more in playbook: Retrieval and RAG
by read10 min views1 publishedDec 4, 2026

By Sachin Shah · Backend & AI Engineer

A 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.

My first reaction was the one most of us have. The model got it wrong, so I should fix the prompt.

I 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.

The 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.

At 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.

The retrieval step is where this story lives. Here is the full path, with the debugging loop drawn underneath it.

The 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.

The 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.

Every 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.

So 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.

After that I stopped debugging through the model and wrote a small script that prints what retrieval returns for any question:

def show_retrieval(question: str, top_k: int = 5, **filters):
    vec = embed(question)  # same embedding deployment used at index time
    res = index.query(
        vector=vec,
        top_k=top_k,
        include_metadata=True,
        filter=filters or None,
    )
    for m in res.matches:
        meta = m.metadata
        print(f"{m.score:.3f}  p.{meta['page']}  {meta['section']}")
        print("   ", meta["text"][:300].replace("\n", " "))
        print()

I 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.

Reading chunk after chunk, the same four problems kept showing up. None of them had anything to do with GPT.

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.

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.

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.

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.

I 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.

I 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.

def extract_pages(path: str) -> list[dict]:
    pages = []
    with fitz.open(path) as doc:
        for i, page in enumerate(doc, start=1):
            text = page.get_text("text", sort=True).strip()
            source = "text-layer"
            if len(text) < 40:                      # nothing usable on this page
                text = ocr_page(page)               # render to image, run OCR
                source = "ocr"
            pages.append({"page": i, "text": text, "source": source})
    return pages

The 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.

I 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.

Headers and footers were a simple counting problem. A line that appears on most pages after you strip the digits is boilerplate:

def strip_repeated_lines(pages: list[dict], threshold: float = 0.6) -> list[dict]:
    def norm(line: str) -> str:
        return re.sub(r"\d+", "#", line.strip().lower())

    counts = Counter(
        norm(l) for p in pages for l in set(p["text"].splitlines()) if l.strip()
    )
    cutoff = max(3, int(len(pages) * threshold))
    boilerplate = {line for line, n in counts.items() if n >= cutoff}

    for p in pages:
        p["text"] = "\n".join(
            l for l in p["text"].splitlines() if norm(l) not in boilerplate
        )
    return pages

Replacing 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.

My 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.

The 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:

def table_to_rows(table: list[list[str]]) -> list[str]:
    header, *rows = table
    return [
        "; ".join(f"{h}: {c}" for h, c in zip(header, row) if c)
        for row in rows
    ]

A 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.

Every chunk also gets metadata, which ended up being as useful as the text:

chunk = {
    "id": f"{doc_id}-{section_id}-{n}",
    "text": f"{section_title}\n{body}",   # heading is part of the embedded text
    "metadata": {
        "doc_id": doc_id,
        "lender": lender,
        "section": section_title,
        "page": page_no,
        "kind": "table_row" if is_table else "paragraph",
        "source": page_source,           # text-layer or ocr
    },
}

Putting 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.

After 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.

This 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.

I 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.

Then a function that asks one thing: did the right source show up in the top results?

def hit_rate(cases: list[dict], k: int = 5) -> float:
    hits = 0
    for case in cases:
        res = index.query(
            vector=embed(case["question"]),
            top_k=k,
            include_metadata=True,
            filter={"lender": case["lender"]},
        )
        found = {(m.metadata["doc_id"], m.metadata["page"]) for m in res.matches}
        if (case["doc_id"], case["page"]) in found:
            hits += 1
    return hits / len(cases)

I 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.

I'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.

The 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.

Once 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.

That 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.

Better 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.

So 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:

def route(state: ReviewState) -> str:
    weak_retrieval = max(state.retrieval_scores, default=0) < MIN_RETRIEVAL_SCORE
    shaky_source = any(c.source == "ocr" and c.ocr_conf < 0.8 for c in state.chunks)

    if state.confidence < CONFIDENCE_THRESHOLD or weak_retrieval or shaky_source:
        return "human_review"
    return "draft_reply"

The 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.

The 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.

If your RAG answers are wrong, open the trace and read what was retrieved. It's usually the faster way to find out.

I'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, GitHub, or X.

── more in #large-language-models 4 stories · sorted by recency
── more on @sachin shah 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/my-rag-answers-were-…] indexed:0 read:10min 2026-12-04 · —