Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

How to Reduce AI Hallucinations with RAG

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Retrieval-Augmented Generation (RAG) is one of the most effective ways to ground large language models in factual data and reduce hallucinations. By feeding the model relevant documents at query time, you shift its output from “guessing from memory” to “summarizing retrieved evidence.” This guide walks you through building a RAG pipeline that minimizes false or unsupported claims in enterprise AI applications.

What You'll Need

  • A document corpus (PDFs, wikis, databases, or internal knowledge bases) that contains the authoritative answers you want the AI to use.
  • An embedding model (e.g., OpenAI’s text-embedding-3-small, Cohere embed, or an open-source model like BGE-M3).
  • A vector database (e.g., Pinecone, Weaviate, Qdrant, or pgvector).
  • An LLM with a chat or completion API (e.g., GPT-4o, Claude, Llama 3).
  • Basic Python skills and a development environment with your preferred SDKs installed.

Step-by-Step

  1. Chunk your documents intelligently. Split each document into overlapping chunks of 300–800 tokens. Use a chunking strategy that respects section boundaries (e.g., markdown headers, paragraphs) rather than blindly cutting at token counts. Overlap by 10–20% to avoid losing context at boundaries.
  2. Embed each chunk. Pass each chunk through your embedding model to create a vector representation. Store the vector along with the original text and metadata (source, page number, section title) in your vector database.
  3. Set up retrieval. For a user query, embed the query and search for the top-k most similar chunks (k usually 5–15). Use cosine similarity or dot-product depending on your vector DB. Consider hybrid search (combining vector and keyword search) for better recall on exact terms.
  4. Build a prompt that forces grounding. Construct a prompt that includes the retrieved chunks and instructs the LLM to answer only from the provided context. For example: “Answer the question using only the following excerpts. If the answer is not present, say ‘I don’t know.’ Do not use outside knowledge.”
  5. Add citations and confidence thresholds. Ask the model to cite which chunk it used for each claim. Set a minimum similarity score for retrieval results; if the top chunk scores below that threshold, return a fallback response like “I couldn’t find reliable information on that.”
  6. Implement a re-ranking step (optional but recommended). Use a cross-encoder model (e.g., Cohere Rerank) to re-order the retrieved chunks by relevance before feeding them to the LLM. This improves precision and reduces noise.
  7. Test with adversarial queries. Create a test set of questions that are out-of-domain, ambiguous, or contain false premises. Run them through your pipeline and verify the model refuses to answer or corrects the premise rather than hallucinating.
  8. Monitor and iterate. Log every query, retrieved chunks, and response. Periodically review cases where the model hallucinated and adjust chunking, retrieval parameters, or prompt wording.

Common Mistakes

  • Chunking too small or too large. Very small chunks lose context; very large chunks dilute relevance. Test different sizes for your specific corpus.
  • Ignoring metadata. Without source and page info, you can’t verify or cite answers, and the model may mix up facts from different documents.
  • Prompting without grounding instructions. If you don’t explicitly say “use only the provided context,” the model will still rely on its parametric memory.
  • Retrieving too many irrelevant chunks. More retrieved chunks isn’t better; it can confuse the model. Use re-ranking and limit the context window to the most relevant pieces.
  • Not handling “no answer” cases. Without a fallback, the model will invent an answer even when retrieval fails.

Tips

  • Use metadata filters. If your corpus spans multiple domains, filter by department, date, or document type before retrieval.
  • Update embeddings regularly. When documents change, re-embed the affected chunks so your vector index stays current.
  • Add a “source quality” field. Weight official documents higher than informal notes in retrieval scoring.
  • Use a smaller LLM for simpler tasks. A smaller model with strong grounding instructions can be more reliable and cheaper than a large model that “knows too much.”
  • Consider fine-tuning on your domain. If you have labeled Q&A pairs, fine-tuning can improve the model’s ability to follow RAG instructions.

Troubleshooting

  • Model still hallucinates on out-of-scope queries. Tighten the prompt: add “If the context does not contain the answer, respond with exactly ‘I don’t know’ and nothing else.” Also lower the retrieval threshold.
  • Retrieved chunks are irrelevant. Check your embedding model—are you using one that matches your data type (e.g., code vs. natural language)? Increase k, add hybrid search, or use a re-ranker.
  • Answers are inconsistent across similar queries. Add a deterministic step: normalize the query (e.g., spell-check, synonym expansion) before embedding.
  • Context window overflow. Reduce the number of chunks or chunk size. Use a model with a larger context, but remember that too much irrelevant text hurts performance.
  • Retrieval is slow. Optimize your vector index (e.g., HNSW with appropriate parameters) and consider caching frequent queries.

Frequently Asked Questions

What is the ideal chunk size for RAG?

There’s no universal number; it depends on your content. Start with 300–500 tokens with 10–20% overlap, then test different sizes on a validation set to see which yields the best retrieval accuracy.

Do I need a vector database, or can I use a regular database?

You need a database that supports efficient vector similarity search. Regular SQL databases can store vectors but will be slow for large-scale search. Use a vector database or a SQL extension like pgvector.

Can RAG completely eliminate hallucinations?

No. RAG reduces hallucinations by grounding responses in retrieved evidence, but it can still fail if the corpus is incomplete, retrieval is poor, or the model misinterprets context. Always implement fallback responses and human review for critical applications.

Should I use a commercial embedding model or open-source?

Commercial models are easier to use and often better for general text. Open-source models give you control and privacy. Test a few options on your data to see which performs best.

How do I handle multi-document answers?

Retrieve chunks from multiple documents and let the model synthesize. Clearly instruct it to cite each source. If the documents conflict, the model should flag the discrepancy rather than pick one arbitrarily.

What is re-ranking and why is it important?

Re-ranking uses a cross-encoder to score retrieved chunks against the query after initial retrieval. It improves precision by filtering out irrelevant chunks that vector similarity missed. It’s especially useful when your corpus is large or heterogeneous.