About Skills Projects Blog Contact View my CV ↗ Español
RAG without magic: embeddings, chunks, and why your bot lies

RAG without magic: embeddings, chunks, and why your bot lies

Understand RAG without hype: embeddings, chunking, retrieval, and why your bot lies even with perfect documents.

By Omar Flores
Table of Contents

Imagine a student who shows up to an exam without studying, but with permission to consult an encyclopedia during the test. If the encyclopedia is well indexed, they find the answer. If it is disorganized, they cite the wrong page and convince the teacher it is true. The student did not lie: they just did not know how to search.

An LLM without RAG is that student without an encyclopedia: it answers from what it memorized during training, which is already outdated and does not include your private documents. An LLM with RAG is the same student with an encyclopedia, but the quality of the answer depends on which page they opened and how they read it. The model is not the problem. The index is.


The problem RAG solves (and the one it does not)

Language models have two limits that a longer prompt does not fix. The first is temporal: they were trained on data up to a cutoff date, and know nothing about what happened after. The second is private: they do not know your internal documents, your tickets, your knowledge base, your contracts.

RAG (Retrieval-Augmented Generation) solves both by connecting the model to an external source at answer time. Instead of asking the model to remember, you give it the relevant documents in the prompt and ask it to answer based on them.

What RAG does not solve is the quality of that source. If your documents are contradictory, outdated, or poorly organized, RAG does not fix them: it amplifies them. The model will generate a convincing answer supported by bad information. And a convincing answer built on bad information is worse than a vague one, because the user believes it.


RAG in five minutes

RAG is a six-step pipeline. Three happen once (ingestion) and three on every question (query).

graph LR
    subgraph "Ingestion (once)"
        A["Documents"] --> B["Chunking"]
        B --> C["Embeddings"]
        C --> D["Vector Store"]
    end
    subgraph "Query (per question)"
        E["User question"] --> F["Question embedding"]
        F --> G["Retrieval (top-k)"]
        G --> H["Augmented prompt"]
        H --> I["LLM generates answer"]
    end
    D -.-> G

The six steps:

  1. Ingestion: load documents (PDFs, web pages, tickets, code).
  2. Chunking: split them into small fragments.
  3. Embeddings: convert each fragment into a numeric vector.
  4. Indexing: store the vectors in a vector database.
  5. Retrieval: given a question, find the most similar fragments.
  6. Generation: pass those fragments to the model as context and ask for the answer.

The magic is not in any single step. It is in all six aligning. An error in step 2 (bad chunking) ruins step 5 (retrieval) even if the model is excellent.


Chunking: the art of cutting without losing meaning

A 50-page document does not fit in a prompt. But you cannot dump it whole either: context has a limit and the model gets distracted by noise. You need fragments that contain a complete idea and fit in context.

Size

The practical rule: a chunk must be large enough to contain a complete idea, and small enough for search to be precise. In most cases, 300 to 800 tokens per chunk works well. Under 200 tokens loses context; over 1000 dilutes relevance.

Overlap

If you cut a paragraph in half, the half that stayed in the previous chunk loses meaning and the half that moved to the next has no antecedent. Overlap copies the last N tokens of a chunk to the start of the next. An overlap of 10-20% of chunk size is usually enough.

Strategies

  • Fixed size: cut every N tokens ignoring paragraphs. Simple, but breaks ideas in half.
  • By paragraphs or sections: respect document structure. Better, but chunks end up very uneven in size.
  • Recursive by separators: try cutting by \n\n, then \n, then space. This is the default in most frameworks (LangChain, LlamaIndex) and is usually the best starting point.

The mistake that ruins everything

Cutting without preserving metadata. Every chunk must carry the document title, section, date, and source URL. Without that, when the model receives the chunk it does not know where it comes from, and cannot cite or verify. And you cannot debug why that fragment was retrieved.


Embeddings: turning text into numbers that mean something

An embedding is a vector of numbers (typically 384 to 3072 dimensions) that represents the meaning of a text. Texts with similar meaning produce nearby vectors in space. “Dog” and “puppy” end up close. “Dog” and “bolt” end up far.

How they are compared

The most common metric is cosine similarity: it measures the angle between two vectors, ignoring magnitude. A value of 1.0 is identical in direction, 0.0 is orthogonal (no relation), -1.0 is opposite. In practice, related texts usually score between 0.7 and 0.95.

Choosing an embedding model

Not all models are equal. The trade-offs that matter:

  • Quality vs cost: larger models (OpenAI text-embedding-3-large, Cohere embed-v3) give better retrieval but cost more per token.
  • Dimensions: more dimensions = more precision, but more memory and more latency. 384 dimensions (small model) vs 1536 (large model) is a real trade-off.
  • Maximum context: if your chunk has 800 tokens, the embedding model must accept at least 800. Some models only accept 512.
  • Language: if your documents are in Spanish, verify the model performs well in Spanish. Not all English models work equally well.

Practical rule: start with a model proven in your language and domain, measure retrieval, and only change if the metric justifies it. Changing embedding model means re-indexing everything.

The same model for question and documents

The question embedding and the chunk embeddings must use the same model. If you index with one model and query with another, the vectors live in different spaces and similarity means nothing.


Retrieval: finding what is relevant

This is where most RAG systems fail silently. Retrieval seems to work (it returns results), but returns the wrong results.

Top-k

You retrieve the k most similar chunks to the question. A typical k is 3 to 8. More is not always better: each additional chunk consumes context and can introduce noise. If k=20, the model has to read 20 fragments and separate relevant from irrelevant, which is exactly what you wanted to avoid.

Similarity vs relevance

Cosine similarity measures semantic closeness, not relevance. “What is the vacation policy?” and “The vacation policy is 15 days” are similar. But “The vacation policy changed in 2023” is also similar and may be the wrong chunk if the question is about the current policy. Similarity does not understand negation, time, or condition.

Pure vector search misses exact matches (proper names, error codes, identifiers). Keyword search (BM25) finds them, but does not understand synonyms. The solution is to combine both: hybrid search with result fusion (reciprocal rank fusion). More complex, but it is what separates a toy RAG from one that works in production.

Reranking

After retrieving the top-k candidates, a reranking model (cross-encoder) reorders results by evaluating each (question, chunk) pair together, not separately. Slower than vector search, but much more precise. Typical pattern: retrieve 20 candidates with cheap vector search, rerank the 20 with a cross-encoder, keep the top 5.

Metadata filtering

Before searching, filter by metadata: date, department, user permissions, language. If the user asks about the 2024 policy, do not search 2020 documents. If the user has no access to a document, do not retrieve it. Filtering shrinks the search space and improves precision.

Similarity threshold

If the closest chunk has similarity 0.4, there is probably no answer in your documents. In that case, it is better to say “I do not know” than to pass irrelevant context to the model. Define a minimum threshold (for example, 0.65) and if no chunk clears it, respond that there is not enough information.


Generation: give the model only what it needs

The generation prompt is where many teams waste the retrieval work. They pass chunks to the model with no clear instructions and expect magic.

The prompt

An effective RAG prompt has four parts:

  1. Role: “You are an assistant that answers based on the provided documents.”
  2. Grounding instruction: “Use only the information in the documents. If the answer is not in the documents, say you do not have enough information.”
  3. Context: the retrieved chunks, each with its source.
  4. Question: the user’s question.

Citations

Ask the model to cite the source of each statement. Not perfect (the model can cite wrong), but it forces the model to link each answer to a chunk, which reduces fabrication and makes verification easier.

“I do not know” is a valid answer

If retrieval found nothing relevant, the best answer is “I have no information about that in my documents.” Training the model to say “I do not know” instead of inventing is more important than any retrieval improvement. A bot that admits ignorance builds trust. A bot that invents destroys it.

Context budget

Context has a limit. If you retrieve 8 chunks of 800 tokens each, that is 6400 tokens of context alone, without counting the prompt, the question, or the answer. Manage the budget explicitly: allocate tokens to context, conversation history, and the question. If history is long, trim chunks, not the question.


Why your bot lies

Here is the answer to the title’s question. A RAG bot lies for four reasons, and none is that the model is bad.

1. Retrieval failed

The correct chunk exists, but retrieval did not find it. The question used a different word than the document, similarity was low, and irrelevant chunks were retrieved. The model, with irrelevant context, invents a plausible answer. This is the most common case and the hardest to detect, because the system does not error: it answers.

2. The chunk does not contain the complete answer

The document states the answer across two paragraphs, but chunking cut between them. Retrieval brought the half that mentions the topic, but not the half with the answer. The model fills the gap with its training knowledge, which may be wrong or outdated.

3. The documents are contradictory

Two documents say different things about the same topic. Retrieval brings both. The model picks one (or mixes both) without knowing which is current. This is a data problem, not a model problem. RAG does not resolve the contradiction; it exposes it.

4. The model ignores the context

Sometimes retrieval is perfect, the correct chunk is in the prompt, and the model answers from its training knowledge anyway. This happens with models not instructed to prioritize context, or when context is very long and the model “loses” the information in the middle. The solution is a stronger grounding prompt and, if possible, a model with a larger context window.

The uncomfortable conclusion: RAG reduces hallucinations, but does not eliminate them. The reduction is proportional to retrieval quality. Perfect retrieval nearly eliminates hallucinations. Bad retrieval amplifies them, because it gives the model a false base with an air of authority.


Evaluation: measure retrieval and generation separately

If you do not measure, you do not know if your RAG works. And if you measure only the final answer, you do not know where it fails.

Measuring retrieval

You need a dataset of questions with correct answers and the chunks that should be retrieved. With that you measure:

  • Precision@k: of the k retrieved chunks, how many are relevant.
  • Recall@k: of the relevant chunks that exist, how many were retrieved.
  • MRR (Mean Reciprocal Rank): at what position the first relevant chunk appears.

If precision@5 is 0.2, it means 4 of every 5 retrieved chunks are noise. The model has to filter that noise, and sometimes it does not.

Measuring generation

With generated answers and retrieved chunks, you measure:

  • Faithfulness: does the answer rely only on retrieved context, or does it invent information?
  • Answer relevancy: does the answer address the question?
  • Groundedness: does each statement in the answer have support in a chunk?

Faithfulness is the most important metric. An answer can be relevant and completely fabricated. Faithfulness detects that.

The evaluation dataset

Building the dataset is the most tedious and most important work. You need 50 to 200 representative questions from real usage, with expected answer and identified relevant chunks. Without this, you optimize blind.

Evaluation is not a one-time event. Data changes, questions change, the model changes. Re-evaluate every time you change a component (chunking, embedding model, prompt, generation model).


Code: a minimal RAG in Python

This is the minimal skeleton. Not production, but it shows the six steps:

from openai import OpenAI
import chromadb

client = OpenAI()
chroma = chromadb.Client()
collection = chroma.create_collection("docs")

# 1-4: Ingestion (once)
chunks = [
    "The vacation policy is 15 business days per year.",
    "Remote work is allowed up to 3 days per week.",
    "Office hours are 9:00 to 18:00.",
]
embeddings = client.embeddings.create(
    model="text-embedding-3-small", input=chunks
).data
collection.add(
    documents=chunks,
    embeddings=[e.embedding for e in embeddings],
    ids=[f"chunk-{i}" for i in range(len(chunks))],
)

# 5-6: Query
question = "How many vacation days do I have?"
q_emb = client.embeddings.create(
    model="text-embedding-3-small", input=question
).data[0].embedding
results = collection.query(query_embeddings=[q_emb], n_results=3)
context = "\n".join(results["documents"][0])

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {
            "role": "system",
            "content": (
                "Answer only based on the provided context. "
                "If the answer is not in the context, say you do not have "
                "enough information. Cite the source."
            ),
        },
        {"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}"},
    ],
)
print(response.choices[0].message.content)

Three details that matter more than the code:

  1. The same embedding model for documents and question. If you change one, re-index everything.
  2. The similarity threshold. If the closest chunk has low similarity, do not pass context to the model; answer “I do not know”.
  3. Metadata. Every chunk must carry source, date, and section. Without that, you cannot cite or debug.

When NOT to use RAG

RAG is not the answer to everything. Do not use it when:

  • The question requires reasoning over structured data (tables, relationships). Use Text-to-SQL or a direct API.
  • The corpus is small (under 50 documents) and fits in context. Pass it directly to the prompt.
  • You need real-time answers with sub-second latency. Retrieval adds latency.
  • Documents change every minute. The index becomes stale before you update it.
  • You cannot maintain the pipeline. A stale index is worse than no index.

Checklist before putting a RAG in production

  • Chunks are between 300 and 800 tokens with 10-20% overlap.
  • Every chunk carries metadata (source, date, section).
  • The embedding model is the same for documents and questions.
  • Retrieval uses hybrid search (vector + keyword) with reranking.
  • There is a minimum similarity threshold; below it, answer “I do not know”.
  • The generation prompt instructs the model to use only the context.
  • There is an evaluation dataset with at least 50 questions.
  • Faithfulness and retrieval precision are measured separately.
  • The index updates automatically when documents change.
  • Retrieval, context used, and answer are logged for debugging.

RAG does not make your model smarter. It gives it better notes. And a student with bad notes does not get better grades: they get better excuses.