DEV Community

crabcheng
crabcheng

Posted on Originally published at mryk123.cn AI-assisted

Why Your RAG Agent Answers the Wrong Question: A 6-Step Debug Playbook

A team spends two weeks wiring up a knowledge-base agent in Coze. It goes live on Monday. By Wednesday, employees are asking "how do I request annual leave" and getting back "the company was founded in 2010." Someone asks for the hotel reimbursement cap in tier-2 cities and gets an answer that expired three years ago.

The builder is confused, and reasonably so. The documents are current. The prompt says "answer based on the knowledge base." So why is the thing hallucinating?

Here is the part nobody tells you when you ship an agent: launching is about 30% of the work. The other 70% is debugging. And "the model is dumb" is almost never the root cause. What actually breaks is the alignment between three layers — retrieval, prompt boundaries, and flow logic. Fix the prompt while the retrieval layer is feeding garbage, and you will loop forever: edit prompt, test, wrong answer, edit prompt again.

This post is the order I debug in, and the specific checks at each step. No ML background required.

Debug in the right order: retrieval → boundaries → flow

The single most common mistake is starting at the prompt layer. It feels productive because you can edit text and immediately see a change. But if the retrieval layer is handing the model the wrong chunk, no amount of prompt engineering will help — the model is answering faithfully from bad context.

So the order matters:

Layer Typical symptom How to confirm
Retrieval (knowledge base) Answer comes from a document but doesn't match the question Look at the Top-3 retrieved chunks; do they actually contain the answer?
Prompt boundaries Tone drifts, sometimes professional, sometimes chatty Clear history, keep only the prompt, detach the KB — observe baseline behavior
Flow logic After a few turns, the agent jumps to an unrelated branch Inspect upstream variable output and downstream branch conditions for overlap

Work top-down. Most incidents resolve at layer one.

Step 1: Reproduce with three different phrasings

Never debug a single phrasing. Ask the same thing three ways and see whether the failure is stable:

  • "How much can I expense for a hotel on a business trip?"
  • "Tier-2 city hotel cap"
  • "Out-of-town lodging reimbursement standard"

If all three fail, it is systematic — go to retrieval. If only one fails, you have a matching/vocabulary problem, which is a much narrower fix.

Step 2: Read the actual retrieved chunks, not the answer

Every platform (Coze, Dify, LangChain, whatever you're on) exposes retrieval details somewhere in the test console. Open it and read the Top-3 chunks verbatim.

In the case I hit, the Top-1 chunk was the first chapter of the travel policy PDF — the "general provisions" section. It scored high because the words "business trip" and "out-of-town" appear there repeatedly. The actual numbers lived in Chapter 3 and never made it into the context window.

That is the whole bug. The model wasn't hallucinating; it was answering from a page that contained the question's vocabulary but not its answer.

Step 3: Fix chunk granularity — one rule per chunk

This is where most knowledge bases go wrong. Uploading a 50-page PDF and letting the platform auto-chunk at 512 characters produces chunks that mix several rules together. Retrieval then has to guess which part you meant.

The fix is boring and effective: one rule per chunk, 80–150 characters.

Before (one auto-chunk, ~512 chars):

Chapter 3 Travel Standards
3.1 All employees on business travel shall comply with finance
policy and reimburse against receipts. 3.2 Lodging caps by city
tier: tier-1 (Beijing, Shanghai, Guangzhou, Shenzhen) 500/night;
tier-2 400/night; other cities 300/night. 3.3 ...
Enter fullscreen mode Exit fullscreen mode

After (three independent chunks, each ~30 chars):

Tier-1 city lodging cap: 500 per night (Beijing, Shanghai, Guangzhou, Shenzhen)
Tier-2 city lodging cap: 400 per night
Other cities lodging cap: 300 per night
Enter fullscreen mode Exit fullscreen mode

After re-chunking, the Top-1 hit became the chunk literally titled "Tier-2 city lodging cap." Zero prompt changes needed for that half of the problem.

Two practical notes:

  • Keep the section heading inside the chunk text. Headings carry a lot of retrieval signal.
  • Tag metadata explicitly, e.g. finance / reimbursement / travel / lodging-cap / 2025-edition. When two document versions conflict, tag filtering is how you find out which one is winning.

Step 4: Add boundaries and a refusal script

"Answer based on the knowledge base" is not a boundary. It's a wish. When retrieved context is weak, models quietly fall back on training data — which is exactly how a policy bot starts inventing a founding year.

A prompt that actually constrains:

# Role
You are the administrative policy assistant for [Company].
Scope: HR and admin policy questions only. Refuse technical,
financial, and personal topics.

# Rules
1. Every answer must cite a specific clause or figure from the
   reference document. Quote figures verbatim.
2. If the reference document does not contain the answer, reply
   exactly: "Not found in current policy — please confirm with
   the admin team." Do not infer, do not use outside knowledge.
3. If two clauses conflict, prefer the newer effective date and
   state both dates.

# Output
- Conclusion first (<= 20 words), then the clause it comes from
- No greetings, no filler, no follow-up questions
Enter fullscreen mode Exit fullscreen mode

The before/after that mattered most in practice:

Dimension Weak Working
Role "You are an assistant." Named role + explicit scope + refusal list
KB boundary "Answer from the materials." "Only from [reference]. If absent, use the fixed refusal string."
Output "Explain in detail." Fixed three-part structure with a length cap
Unknowns "If you don't know, say so." Fixed refusal string with a named escalation contact

Step 5: Check for variable pollution across turns

If the agent is fine on a fresh session but degrades after two or three turns, you have a state problem, not a model problem.

Two things to check:

  1. Global variables that don't get reset. A welcome-node variable set in turn one can bleed into the query used for retrieval in turn two, pulling the embedding toward the wrong topic.
  2. Overlapping branch conditions. If branch A triggers on "expense" and branch B triggers on "reimbursement," a question containing both will land wherever the router happens to check first.

Turn off "inherit previous intent" while debugging and test single-turn accuracy first. Only re-enable context once single-turn is clean. A surprising share of "the agent forgot what I said" tickets are actually "the retrieval query was contaminated by the previous turn."

Step 6: Regress against real questions, not invented ones

Before you declare victory, pull the last month of actual user questions from your ticket queue or group chat. Twenty is enough.

We ran 20 real admin questions against the fixed agent: accuracy went from 45% to 90%, and numeric questions hit 100%. The remaining failures clustered in one area — policy documents that only existed as scanned images — which told us the next fix was OCR, not prompting.

That is the value of a real regression set: it tells you where the next bug is, instead of leaving you guessing whether the whole thing works.

Build an adversarial set and a bad-case ledger

Two cheap habits that compound:

Adversarial questions, weekly. Have a colleague deliberately ask out-of-scope things: "how old is the company," "recommend a phone," "what's the CEO's salary." Track the refusal rate. Five new hostile questions a week is enough to keep the guardrails honest.

A bad-case ledger. One spreadsheet, five columns: user's exact words, agent's answer, correct answer, root-cause layer (retrieval / prompt / flow), date. After 20 rows the distribution of root causes is obvious, and you stop re-fixing the same class of bug. Ours was 60% retrieval, 30% prompt, 10% flow — which is precisely why starting at the prompt layer wastes so much time.

Upgrading the model is the last step, not the first

When an agent gives wrong answers, the reflex is to switch to a bigger, more expensive model. On domestic platforms this is almost always wasted money. Chunk granularity and prompt boundaries account for the overwhelming majority of failures. Swap the model after you've fixed retrieval and boundaries — and if the failure rate doesn't move, you'll know the model was never the problem.


The short version: a knowledge-base agent that answers the wrong question is usually a retrieval problem wearing a model costume. Read the retrieved chunks before you touch the prompt. Fix chunk granularity before you add more rules. And keep a ledger, because the second incident is always a repeat of the first.

Originally published at mryk123.cn — a Chinese-language AI office training site.

Top comments (2)

Collapse
 
ahmetozel profile image
Ahmet Özel •

Reproducing a bug with three distinct phrasings immediately separates vocabulary mismatch from systematic indexing or chunking failures. Teams burn hours editing system prompts because prompt tweaks feel fast, yet reading the verbatim Top-3 retrieved chunks almost always exposes the real fault in two minutes.

Detaching the knowledge base and clearing history to test prompt boundaries in isolation is another smart diagnostic step. Once you confirm the base prompt behaves consistently without retrieved noise, any remaining drift points straight to context pollution or overlapping branch conditions in the flow.

Collapse
 
makeyouragent profile image
MakeYourAgent •

The tier-2 example is a good one, and the re-chunk clearly fixed it, but splitting down to one rule per line can move the bug instead of removing it. The chunk "Tier-2 city lodging cap: 400 per night" no longer says which cities are tier-2. In most policies that list lives in an appendix or a separate table, so a question that names a city now matches neither chunk well: the city is in one place and the number is in another. We ended up folding the definition into every rule chunk that depends on it, something like "Tier-2 cities (the full list): lodging cap 400 per night", even though it repeats the list a few times.

The same thing happens with exceptions. Policies love a clause two lines later saying managers above some grade can claim 1.5x the cap. Once every rule is its own short chunk, the base number wins retrieval for everyone and the exception never shows up next to it. A cheap check is to search the source for "except", "unless" and "above grade" and make sure each of those clauses is stitched into the chunk it modifies.

On rule 3 of the prompt, "prefer the newer effective date" only works if the date is in the text the model actually sees. Metadata tags help with filtering, but most platforms don't pass the tags into the context, so the model ends up comparing two numbers with no dates attached. Putting "(2025 edition)" inside the chunk text is what made that rule fire for us.

Did the answer that expired three years ago come from an old PDF still sitting in the knowledge base, or from an old clause inside the current one?