DEV Community

Abuzar Zulfiqar
Abuzar Zulfiqar

Posted on Edited on Originally published at abuzar18.github.io AI-assisted

Building a RAG System That Says "I Don't Know": Self-Correcting RAG with Llama 3.1 and LangGraph

Most RAG demos have the same flaw: ask them something the documents never mention, and they answer anyway, confidently and wrongly. In a demo that is a curiosity. In production it is how a support bot invents a refund policy.

I built Llama Agentic RAG around the opposite rule: an answer must be supported by cited sources, or the system says "I don't know." It runs fully locally on Llama 3.1 8B through Ollama, which fits in 8 GB of VRAM, so private documents never leave the machine.

This post walks through the design and the choices that made it work on a small model.

The workflow

The pipeline is a LangGraph state machine with five stages:

  1. Retrieve the top-k chunks from a vector index. Every chunk has a stable id such as handbook.md#3, so citations stay traceable.
  2. Grade each chunk for relevance with the LLM before anything is generated. Off-topic context never reaches the answer.
  3. Rewrite the query once if no chunk is relevant. Vague questions often recover here; if they don't, the graph refuses.
  4. Generate an answer only from the numbered context, citing [n] after each claim.
  5. Check groundedness: a judge prompt verifies the answer against the context. An unsupported answer is replaced by a refusal.

The key idea is that hallucinations become refusals, not wrong answers. A refusal is annoying; a confident wrong answer is expensive.

Making it work on an 8B model

Large models forgive sloppy prompts. Small models don't, so a few details mattered more than any framework choice:

  • One-word verdicts. Llama 3.1 8B is unreliable with complex JSON schemas, so the grading and groundedness prompts ask for yes or no, and parsing is tolerant of extra words.
  • Strip reasoning tags. If you swap in a reasoning model, its <think> blocks are removed before parsing.
  • Citations are enforced, not requested. An answer without valid [n] citations is treated as ungrounded, even if it sounds right.
  • Config over code. Every model, path and threshold is an environment variable, so trying another Ollama model is a one-line change.

Measure the refusals

A RAG system that never says "I don't know" isn't production-ready, so the evaluation set deliberately includes unanswerable questions. The harness reports:

Metric What it tells you
Retrieval hit rate Did we retrieve an expected source for answerable questions?
Citation precision Do cited chunks come from expected sources?
Refusal accuracy Were unanswerable questions correctly refused?
False-refusal rate Were answerable questions wrongly refused?
Judge correctness LLM-as-judge score against a reference answer
p50 / p95 latency What does it cost the user in time?

Refusal accuracy and false-refusal rate pull against each other, which is exactly why you need both. Tighten the groundedness check and refusals get safer while false refusals rise. The numbers make that trade-off visible instead of a matter of opinion.

Treat prompt and model changes like code changes: they ship only if the evals hold.

Tests that don't need a GPU

CI runs the full graph with scripted fake LLM replies and deterministic embeddings. That covers the happy path, query rewrite, refusal, ungrounded answers, missing citations and reasoning-tag stripping, all without a model or a GPU. It is the cheapest way to keep a graph's control flow honest as it grows.

Use it from Claude with MCP

The same graph is exposed as an MCP tool, ask_documents, so Claude Desktop, Claude Code or any MCP client can query your documents and get cited answers back. The FastAPI service exposes /ask, /ingest and /health for everything else.

What's next

The roadmap is the usual path from reference to production: hybrid retrieval with BM25 and a cross-encoder reranker, a persistent vector database such as pgvector or Qdrant, tracing with Langfuse, streaming, and PDF and DOCX ingestion.

The code is MIT-licensed: github.com/abuzar18/llama-agentic-rag.

I'm Abuzar Zulfiqar, an AI/ML engineer who builds production AI agents, RAG assistants and LLM automation. More at abuzar18.github.io.

Top comments (14)

Collapse
 
kami_butt_69b922ade8de012 profile image
Agentic Affairs •

Turning hallucinations into refusals instead of wrong answers is the right trade, and measuring refusal accuracy against false-refusal rate is what makes it honest — most RAG posts only report the first. The one-word verdict trick for the 8B model is a nice detail: small models punish complex JSON schemas, so you shaped the prompt to the model instead of the other way round. One question: with citations enforced rather than requested, what happens when the groundedness judge itself is wrong — do you have a case where the judge overruled a correct answer?

Collapse
 
abuzar18 profile image
Abuzar Zulfiqar •

When the judge is wrong, a correct answer turns into a refusal, so it shows up in the false-refusal rate rather than as a wrong answer. That's why both numbers are tracked: tighten the judge and refusals get safer while false refusals rise. Judge prompt changes go through the same eval gate as any other change.

Collapse
 
kami_butt_69b922ade8de012 profile image
Agentic Affairs •

That's a clean answer — tracking both rates keeps the trade visible instead of letting a stricter judge quietly look like progress. The eval gate on judge-prompt changes is the part most teams skip. Has a judge change ever failed the gate in practice, and did the failure show up in false refusals first or in something subtler?

Thread Thread
 
abuzar18 profile image
Abuzar Zulfiqar •

Not on this project yet. The judge prompt hasn't changed since the eval set was built, so the gate hasn't had to block anything. Where I'd expect it to show first is false refusals on answers that paraphrase the source instead of quoting it, because a stricter judge tends to read paraphrase as unsupported. That's the case worth adding to the eval set before anyone tightens the judge.

Thread Thread
 
kami_butt_69b922ade8de012 profile image
Agentic Affairs •

That paraphrase case is a sharp prediction — a judge that only trusts verbatim quotes would quietly punish the most natural answers. Adding it to the eval set before tightening the judge is the right order; otherwise the gate only ever measures the easy cases. Do you think the fix there is a looser judge prompt, or a second check that distinguishes paraphrase from invention?

Thread Thread
 
abuzar18 profile image
Abuzar Zulfiqar •

A second check. Loosening the judge trades one failure for another: paraphrase passes, but so does invention. I'd split the answer into individual claims and ask, for each one, whether the cited chunk supports it, with paraphrase explicitly allowed. That changes the question from "does this look like the source" to "does the source support this", and a failure points to one claim you can debug instead of a refused answer.

Thread Thread
 
kami_butt_69b922ade8de012 profile image
Agentic Affairs •

Claim-level checking is the right granularity — it turns a binary refusal into something you can actually debug, one claim at a time. The cost is the obvious trade: N judge calls per answer instead of one. Would you run it on every answer, or only when the first-pass judge is uncertain?

Thread Thread
 
abuzar18 profile image
Abuzar Zulfiqar •

Not on every answer. With one-word verdicts there is no confidence score to gate on, so "uncertain" would need defining first. The cheaper version I'd start with: run the claim-level check only when the first judge says no. That rescues false refusals and adds nothing to answers that already pass.

What it doesn't catch is a wrong yes. For that I'd sample a slice of passing answers and run the claim-level check offline, as part of the eval, rather than paying for it on every request.

Thread Thread
 
kami_butt_69b922ade8de012 profile image
Agentic Affairs •

The asymmetry is the right design — paying for the claim-level check only on the 'no' verdicts keeps the request path cheap, and sampling passing answers offline catches the wrong-yes cases without taxing every request. The sampling choice is the part I'd watch: random slice, or stratified toward the answers most likely to be wrong? Either way, separating the two failure modes instead of averaging them is what makes the numbers honest.

Collapse
 
mateo_ruiz_6992b1fce47843 profile image
Mateo Ruiz •

The refusal mechanism is important, but I'd pay particular attention to the difference between retrieval relevance and answer groundedness. A retrieved chunk can be relevant to the question without actually supporting the specific claim the model generates. That's where many production RAG systems still fail. At IT Path Solutions, this distinction matters when building RAG workflows for business documents: citations should be validated against the exact claims they support, not just attached because a relevant document was retrieved. I'd also test conflicting documents, outdated policies, and questions that are only partially answerable. In those cases, the best response isn't always a complete refusal; it may be to answer the supported portion and explicitly identify what the available evidence cannot establish. That makes "I don't know" a useful reliability feature rather than just a fallback.

Collapse
 
abuzar18 profile image
Abuzar Zulfiqar •

Agreed, relevant and supporting are different checks. Relevance is graded per chunk before generation, and groundedness is checked against the cited context afterwards, so an answer that cites a relevant but non-supporting chunk should fail. Conflicting and outdated documents are a good addition to the eval set.

Collapse
 
abuzar18 profile image
Abuzar Zulfiqar •

One more on your last point, because I skipped it earlier: partial answers. The graph is binary today, it answers or it refuses. For questions that are only partly covered, answering the supported part and naming what the evidence can't establish is the better behaviour, and that's a fair gap in the current design. It belongs on the roadmap next to the conflicting-document cases.

Collapse
 
maxmartella profile image
Massimiliano Martella •

Groundedness check with a yes/no verdict. If the judge is the same Llama 3.1 8B, it might let through a response that only half-follows the context, especially when two chunks say slightly different things. The rate of incorrect rejections should show whether the judge is too strict. Question: do the judge’s errors concentrate on the responses that combine two chunks?

Collapse
 
abuzar18 profile image
Abuzar Zulfiqar •

By default, yes: RAG_JUDGE_MODEL defaults to llama3.1:8b, the same model that generates. That is the weak spot you're pointing at, since a judge from the same model tends to share the generator's blind spots. The judge is a separate setting so it can be a larger model without touching generation, and that's the first thing I'd change outside a laptop setup.

On your question: I don't know yet. The harness reports false refusals and judge correctness in aggregate, not by how many chunks an answer draws on. It's a cheap slice to add: tag each answerable question with the number of chunks its reference answer needs, split both metrics by that tag, and add a few cases where two chunks disagree. If your hunch is right, the multi-chunk bucket will show it.