RAG: Chat With Your Own Documents

Generative & Agentic AI · Retrieval-Augmented Generation · Intermediate · 16 min

Retrieval-Augmented Generation: give the model an open-book exam.

A librarian who cuts every book into index cards, files the cards by meaning, and for each question pulls the two best cards and answers by reading from them.

The idea in everyday words

A closed-book exam: the student (LLM) answers from memory and might make things up. An open-book exam: before answering, the student flips to the right page of the textbook (your documents) and answers using it. RAG = open-book exam for AI.

The pipeline

Indexing (once): load docs → split into chunks → embed → store in a vector DB. Answering (each question): embed question → find top-k similar chunks → put them in the prompt → LLM answers using only that context, ideally with citations.

Chunking matters

  • Too big → irrelevant noise, expensive. Too small → loses meaning.
  • Typical: 300–800 tokens with 10–20% overlap so sentences at edges aren't cut off.
  • Better: split on headings/paragraphs.
  • The challenge below works like real chunkers: it stops as soon as a chunk reaches the end of the text. A naive loop (keep going until the start passes the end) adds a tiny tail that is already inside the previous chunk: "abcdefghij", size 4, overlap 1 would end with "ghij" and then a useless extra "j".

Stack options

  • Open source: LangChain / LlamaIndex + Chroma/Qdrant + Llama/Mistral via Ollama.
  • AWS: Bedrock Knowledge Bases + OpenSearch.
  • GCP: Vertex AI Search / RAG Engine.
  • Azure: Azure AI Search + Azure OpenAI.

Debugging RAG: check retrieval before blaming the model

When an answer is wrong, walk the pipeline backwards:

  1. Was the right chunk retrieved? Log the top-k chunks for the question. If the answer is not in them, the LLM never had a chance.
  2. If it was not retrieved, ask why: is the fact split across two chunks (add overlap or chunk by section)? Is the question worded differently from the document (try hybrid keyword + vector search, or rewrite the query)? Is k too small? Did a metadata filter exclude it?
  3. Retrieved but ignored? Fix the prompt: put the context before the question, ask for citations, and add "If the answer is not in the context, say you don't know."
  4. Turn every bad case into an eval test (context recall, faithfulness) so it never comes back.

The visual shows step 2 live: with size 40 and no overlap, "free on orders over $50" is cut in half and the shipping answer fails.

Step by step

  1. Question:

    'What is our refund policy?'

  2. Embed:

    Question → vector.

  3. Retrieve:

    Top 3 chunks from 'policies.pdf'.

  4. Augment:

    Prompt = rules + chunks + question.

  5. Generate:

    LLM: 'Refunds within 30 days [policies.pdf p.2]'.

Code example

def chunk(text, size, overlap):
    chunks, start = [], 0
    while start < len(text):
        chunks.append(text[start:start + size])
        if start + size >= len(text):
            break  # this chunk already reaches the end
        start += size - overlap
    return chunks

docs = chunk("Refunds are allowed within 30 days. Shipping is free over $50.", 30, 5)
question = "refund"
best = [c for c in docs if question in c.lower()]
prompt = "Answer using ONLY this context: " + " | ".join(best) + " Question: What is the refund policy?"
print(docs)
print(prompt)

Interview tips

  • RAG vs fine-tuning: RAG for knowledge, fine-tuning for style/behaviour.

  • Evaluation: faithfulness, answer relevance, context recall (e.g. RAGAS).

  • Mention metadata filters (by user, by date) for security.

Challenge: Chunk With Overlap

Split text into chunks of length size, where each new chunk starts size - overlap characters after the previous one. Stop as soon as a chunk reaches the end of the text, like real chunkers do, so you never add a tiny tail that is already inside the previous chunk.

  • Check the settings first. If overlap >= size the window could never move forward: raise a ValueError (JavaScript: throw new Error(...)) instead of looping forever. Do this even when text is empty: bad settings are a bug no matter what text arrives.

Examples:

  • chunk_text("abcdefgh", 4, 1) → ["abcd", "defg", "gh"]
  • chunk_text("abcdefghij", 4, 1) → ["abcd", "defg", "ghij"] ("ghij" reaches the end, so we stop: no extra "j")

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Retrieval-Augmented Generation

Previous: Open Source vs Cloud LLMs · Next: Vector Databases & Similarity Search