{"slug": "your-rag-chatbot-hallucinates-debugging-retrieval-before-changing-the-ai-model", "title": "Your RAG Chatbot Hallucinates: Debugging Retrieval Before Changing the AI Model", "summary": "A developer outlines a debugging workflow for RAG chatbots that give wrong answers, arguing that most failures originate in the retrieval pipeline rather than the LLM. The approach starts by logging the exact chunks, scores, and metadata returned by the vector database before touching the system prompt or switching models, and warns that naive fixed-character chunking can split conditions like refund windows away from their policy text.", "body_md": "*Your chatbot keeps inventing product details, getting pricing wrong, or confidently answering questions that aren't in your documents. Before upgrading to a bigger LLM, check what your vector database is actually returning.*\n\nI've seen developers spend hours changing system prompts, switching models, and increasing context windows because their RAG chatbot keeps giving incorrect answers.\n\nThe interesting part? Sometimes the model isn't the main problem at all.\n\nImagine your chatbot tells a customer that your basic subscription includes five team members when your actual plan only supports three.\n\nYou check the system prompt. Nothing looks wrong.\n\nYou switch to a more powerful model. The answer still isn't reliable.\n\nAt this point, I'd stop changing the model and inspect the retrieval pipeline.\n\nA large share of RAG failures start before the LLM generates a single token. The system retrieves irrelevant information, misses the correct document, or passes incomplete context to the model.\n\nThe model then tries to produce an answer using whatever information it receives.\n\nThat's not always a generation problem. Often, it's a retrieval problem.\n\nI wouldn't attach a universal 80% statistic to this claim without a defined benchmark, but retrieval is one of the first places I'd investigate when debugging a RAG application.\n\nHere's the order I'd follow.\n\nThis is the first thing I'd do when a RAG chatbot gives an incorrect answer.\n\nDon't start with the system prompt. Don't switch to another model. Don't immediately increase your top-k value.\n\nOpen your retrieval logs and read the exact chunks returned by your vector database.\n\nLet's say a customer asks:\n\n\"What is the refund policy for annual subscriptions?\"\n\nYour chatbot responds:\n\n\"We offer a 30-day money-back guarantee on all annual subscriptions.\"\n\nBut your company actually offers refunds only within seven days.\n\nBefore blaming the LLM, inspect the retrieved results.\n\nYou might discover that your vector database returned:\n\nThe search found text with similar words, but it didn't find the actual refund policy.\n\nThat's a retrieval failure.\n\nI usually want to see the following information for every retrieved chunk:\n\nA simple Python debugging function could look like this:\n\n``` python\ndef debug_retrieval(query, results):\n    print(f\"\\nQUERY: {query}\")\n    print(\"=\" * 80)\n\n    for rank, result in enumerate(results, start=1):\n        print(f\"\\nRank: {rank}\")\n        print(f\"Score: {result.score:.4f}\")\n        print(f\"Source: {result.metadata.get('source')}\")\n        print(f\"Section: {result.metadata.get('section')}\")\n        print(f\"Chunk ID: {result.metadata.get('chunk_id')}\")\n\n        print(\"\\nRetrieved content:\")\n        print(result.page_content[:1200])\n        print(\"-\" * 80)\n```\n\nRun this before passing the chunks to your LLM.\n\nYou may find that the correct document isn't being retrieved at all. Or perhaps it's present but ranked below several irrelevant chunks.\n\nThose are two different problems, and they need different fixes.\n\n**My rule: Never debug the generated answer without first checking the retrieved context.**\n\nSuppose your website contains the correct refund policy, and your vector database has indexed it.\n\nBut the chatbot still can't retrieve the complete answer.\n\nTake a look at how the document was divided into chunks.\n\nA common mistake is using fixed character splitting without considering the structure of the content.\n\nFor example, imagine this paragraph:\n\n\"Annual subscriptions can be refunded within seven days of purchase, provided the customer has not exceeded the usage limit...\"\n\nA naive character splitter might produce:\n\n**Chunk 1:**\n\n\"Annual subscriptions can be refunded within seven days of purchase, provided the customer has not\"\n\n**Chunk 2:**\n\n\"exceeded the usage limit...\"\n\nNow the information is separated from part of its condition.\n\nThe problem becomes worse with pricing tables, product specifications, FAQs, and technical documentation.\n\nA model might retrieve the first chunk and confidently explain the refund period without retrieving the condition.\n\nInstead of splitting everything after an arbitrary number of characters, consider how the content is organized.\n\nFor Markdown documents, use headings as natural boundaries.\n\nFor website content, preserve related paragraphs and sections.\n\nFor tables, keep the column headers with their corresponding rows.\n\nPractical improvements include:\n\nOverlap helps when useful information sits near a chunk boundary. But don't increase it blindly. Too much overlap creates duplicate content and can fill retrieval results with nearly identical chunks.\n\nThis is another issue I frequently recommend checking.\n\nWhen you crawl website pages, you don't necessarily get only the main article content.\n\nYou might also extract:\n\nImagine indexing 100 pages where every page contains the same footer.\n\nYour vector database may end up with hundreds of similar chunks containing repeated navigation and footer information.\n\nThat noise makes retrieval less useful.\n\nBefore generating embeddings, extract the main content and remove unnecessary HTML boilerplate.\n\nKeep useful information such as page titles, headings, product names, and section metadata.\n\nThe goal isn't to store as much website text as possible. It's to store information that can actually answer customer questions.\n\nMicrosoft's RAG architecture guidance also discusses format-aware chunking, overlap, and semantic coherence as factors that affect retrieval quality.\n\nYour ingestion pipeline now looks better, but another problem remains.\n\nPure vector search isn't always reliable for exact information.\n\nImagine a customer asking:\n\n\"Does product XR-450 support firmware version 2.8.1?\"\n\nOr:\n\n\"What does error code AUTH-403 mean?\"\n\nThese questions contain exact identifiers.\n\nAn embedding model may understand the general meaning of the question but fail to rank the exact matching document highly enough.\n\nThis happens because semantic similarity and exact keyword matching solve different problems.\n\nThis is where hybrid search becomes useful.\n\nYou combine two retrieval methods:\n\n**Vector search**\n\nUses embeddings to find content with similar meaning.\n\nFor example:\n\n\"How do I get my money back?\"\n\nIt might retrieve content titled \"Refund and Cancellation Policy.\"\n\n**Keyword search (BM25)**\n\nFinds documents containing important matching terms.\n\n\"AUTH-403\"\n\nIt can locate the exact error code even when semantic similarity isn't particularly strong.\n\nCombining both gives your retrieval pipeline a better chance of finding relevant information.\n\nA practical flow looks like this:\n\n```\nCustomer Question\n       |\n       v\n  Normalize Query\n       |\n       +------------------+\n       |                  |\n       v                  v\n  Vector Search       BM25 Search\n       |                  |\n       +--------+---------+\n                |\n                v\n       Merge Candidate Results\n          (Reciprocal Rank Fusion)\n                |\n                v\n         Cross-Encoder Reranker\n                |\n                v\n          Select Best Chunks\n                |\n                v\n              LLM\n                |\n                v\n             Answer\n```\n\nEven after hybrid search, your top results might not be in the best order.\n\nA cross-encoder helps solve this.\n\nUnlike a typical bi-encoder search, which independently converts the query and documents into vectors, a cross-encoder examines the query and candidate document together.\n\nIt then estimates how relevant that particular document is to the question.\n\nFor example, your initial retrieval might return 30 candidate chunks.\n\nA reranker can evaluate those candidates and move the most relevant ones to the top.\n\nYou can then pass perhaps the best four or five chunks to the LLM.\n\nThis adds some latency and inference cost, so benchmark it against your actual workload rather than enabling it without testing.\n\nMicrosoft's retrieval guidance describes this common pattern: retrieve broadly, merge results, rerank candidates, and pass the strongest results to generation.\n\nThe improvement can be significant when your document collection contains similar product pages, technical specifications, or large amounts of overlapping content.\n\nHere's another mistake that causes problems.\n\nDevelopers configure retrieval, connect their documents, and then instruct the chatbot to answer every customer question.\n\nThat's a bad combination.\n\nSometimes the correct answer simply isn't available in your knowledge base.\n\nYour chatbot shouldn't invent one.\n\nFor example, a customer asks:\n\n\"Do you offer a 40% discount for enterprise customers?\"\n\nYour documents contain no information about that discount.\n\nA chatbot without proper guardrails might generate a plausible response based on general pricing patterns.\n\nThat's exactly what you want to prevent.\n\nI'd start with a system prompt similar to this:\n\n```\nSYSTEM_PROMPT = \"\"\"\nYou are a business support assistant.\n\nAnswer questions using only the information\nprovided in the retrieved documents.\n\nRules:\n1. Do not invent prices, policies, or features.\n2. Do not use general knowledge as a replacement\n   for missing business information.\n3. If the provided documents do not contain\n   enough evidence, respond with:\n\n   \"I don't have enough information in the\n   provided docs to answer that accurately.\"\n\n4. Do not make assumptions about missing details.\n5. Keep answers clear and directly related\n   to the customer's question.\n\"\"\"\n```\n\nThis gives the model clear boundaries.\n\nHowever, a system prompt alone isn't enough.\n\nYou should also implement a retrieval-level confidence check.\n\nFor example, if your vector search returns no relevant results, don't send an empty or unrelated context to the model and hope for the best.\n\nYou can reject weak retrieval results before generation:\n\n```\nMIN_RETRIEVAL_SCORE = 0.72  # Example only.\n                         # Calibrate using evaluation data.\n\nif not results or results[0].score < MIN_RETRIEVAL_SCORE:\n    return (\n        \"I don't have enough information in the \"\n        \"provided docs to answer that accurately.\"\n    )\n```\n\nDon't copy `0.72` into every project.\n\nSimilarity scores depend on the embedding model, vector database, distance metric, and document collection. Build a small evaluation dataset with questions whose answers you already know, then determine an appropriate threshold.\n\nAlso, don't confuse a cross-encoder's relevance score with a vector similarity score. They're different scoring systems.\n\nFor production systems, I'd test the threshold against both answerable and unanswerable questions.\n\nA good chatbot should know when the available evidence isn't sufficient.\n\nAfter checking retrieval, cleaning ingestion, improving search, and adding proper grounding instructions, you may still have incorrect answers.\n\nNow it's reasonable to investigate the generation layer.\n\nCheck whether:\n\nAt this stage, compare models using the same questions, retrieved chunks, and system prompt.\n\nDon't compare two different models with two different retrieval pipelines and assume the difference comes from the model.\n\nKeep the experiment controlled.\n\nAnd measure more than whether an answer sounds convincing. Check factual accuracy, evidence support, and whether the chatbot correctly abstains when information is missing.\n\nA bigger model can sometimes improve reasoning and instruction following. But it cannot reliably recover information that your retrieval pipeline never supplied.\n\nFor businesses looking to implement this kind of system on their websites, [custom AI chatbot development by TechHowdy](https://techowdy.com/ai-chatbot/) offers an approach that combines RAG, website content, PDFs, and business knowledge to provide more relevant customer responses. Having the right retrieval setup, fallback rules, and testing process is just as important as choosing the AI model.\n\nWhen my chatbot starts making up product details, pricing tiers, or business policies, this is the sequence I'd follow:\n\nThe next time your RAG chatbot gives a completely wrong answer, resist the temptation to upgrade your LLM immediately.\n\nCheck what you gave it first.\n\nSometimes the model isn't making things up because it's too small or not intelligent enough.\n\nIt's making things up because your retrieval pipeline never found the answer in the first place.\n\n**Fix what goes into the model before paying more for what comes out of it.**", "url": "https://wpnews.pro/news/your-rag-chatbot-hallucinates-debugging-retrieval-before-changing-the-ai-model", "canonical_source": "https://dev.to/techowdy_llc/your-rag-chatbot-hallucinates-debugging-retrieval-before-changing-the-ai-model-28ik", "published_at": "2026-12-01 12:05:13+00:00", "updated_at": "2026-12-01 12:13:30.575104+00:00", "lang": "en", "topics": ["large-language-models", "ai-agents", "ai-tools"], "entities": [], "also_reported_by": [], "takeaway": "Log every retrieved chunk's score, source, section and chunk ID before changing the model, since a missing document and a correctly retrieved but low-ranked one require different fixes.", "recommendation": {"advice": "Inspect retrieval logs and chunk metadata before altering prompts or models, and chunk by document structure rather than fixed character counts so conditions stay with their policy text.", "playbook": "rag-retrieval", "playbook_url": "https://wpnews.pro/playbooks/rag-retrieval"}, "alternates": {"html": "https://wpnews.pro/news/your-rag-chatbot-hallucinates-debugging-retrieval-before-changing-the-ai-model", "markdown": "https://wpnews.pro/news/your-rag-chatbot-hallucinates-debugging-retrieval-before-changing-the-ai-model.md", "text": "https://wpnews.pro/news/your-rag-chatbot-hallucinates-debugging-retrieval-before-changing-the-ai-model.txt", "jsonld": "https://wpnews.pro/news/your-rag-chatbot-hallucinates-debugging-retrieval-before-changing-the-ai-model.jsonld"}}