# RAG Explained: How Chunking and Embeddings Decide Answer Quality

## Why an LLM alone isn't enough

A language model knows what it learned in training. It doesn't know your documents. If you ask it about a resume, a contract or an internal policy, it will either say it can't help or, worse, produce a confident answer that isn't based on anything you gave it.

Retrieval-Augmented Generation (RAG) fixes this by fetching relevant passages from your own documents at question time and handing them to the model as context. Most of the quality in a RAG system is decided before the model ever sees a question: how you split documents, and how you turn those pieces into searchable vectors.

I'll use [AI Career Coach](https://github.com/Janardhan-AIConsultant/ai-career-coach), an open-source project I'm building, to show real choices rather than toy examples.

## The pipeline in one view

In that project, a document goes through these stages:

1. **Validate:** check file type, size and structure before reading anything.
2. **Extract:** pull text from PDF, DOCX or TXT, in memory only.
3. **Clean:** normalise Unicode, strip control characters, collapse whitespace.
4. **Scan:** flag instruction-like text, but still store it as data.
5. **Chunk:** split the text into overlapping pieces.
6. **Embed:** turn each chunk into a vector.
7. **Store:** save vectors in ChromaDB, with the owner and document ID attached.

Questions then follow the reverse path: retrieve the closest chunks, build a context block, ask the model, and validate the answer. This article covers steps 5 and 6, because they quietly decide whether retrieval finds the right passage.

For context, here is the project these examples come from. The AI career coach and mock interviews in the screenshot answer from the user's own uploaded documents, which is the RAG pipeline described here:

![AI Career Coach project overview: upload a resume and job description for an explainable match score and skill gaps, then follow a 7, 15 or 60 day roadmap with assessments, mock interviews, an AI career coach and verifiable certificates](https://raw.githubusercontent.com/Janardhan-AIConsultant/ai-career-coach/main/docs/images/ai-career-coach-showcase-1080p.jpg)

*Project overview image, from the project's repository.*

## Chunking: where answers are won or lost

A chunk is the unit of retrieval. If chunks are too large, each one mixes several topics and the match gets blurry. If they're too small, a chunk loses the context that makes it meaningful, and a single answer gets scattered across several pieces.

Here is the chunking code from the project:

```python
from langchain_text_splitters import RecursiveCharacterTextSplitter

def chunk_text(text: str, chunk_size: int, chunk_overlap: int) -> list[Chunk]:
    if chunk_overlap >= chunk_size:
        raise ValueError("chunk_overlap must be smaller than chunk_size")
    splitter = RecursiveCharacterTextSplitter(
        chunk_size=chunk_size,
        chunk_overlap=chunk_overlap,
        separators=["\n\n", "\n", ". ", " ", ""],
    )
    return [Chunk(i, t) for i, t in enumerate(splitter.split_text(text)) if t.strip()]
```

Three decisions are worth noticing:

- **Recursive splitting:** the splitter tries paragraph breaks first, then line breaks, then sentences, then words. It only cuts mid-sentence as a last resort. For a resume or a job description, that keeps a role's bullet points together.
- **Overlap:** neighbouring chunks share some text, so a sentence cut at a boundary still appears whole in one of them.
- **A guard clause:** overlap must be smaller than size, otherwise the splitter can loop or produce duplicates. Failing loudly is better than failing quietly.

`chunk_size` and `chunk_overlap` come from settings, not from the code, so you can tune them per document type without a redeploy. I don't have an evaluation set yet, so I won't claim a "best" value. Pick a starting point, then measure it against real questions.

## Embeddings: turning text into something searchable

An embedding model maps each chunk to a vector, so that chunks with similar meaning end up close together. At question time the question is embedded the same way, and the store returns the nearest chunks.

The project puts embeddings behind a provider adapter with two options:

| Provider | What it is | Use |
|---|---|---|
| `local-hf` (default) | MiniLM, 384 dimensions, via `langchain-huggingface` | Real semantic search; needs a heavier install with PyTorch |
| `hash` | Deterministic lexical feature hashing, 384 dimensions | Development and tests only; not semantic |

The `hash` option is the useful lesson. It lets tests and quick local runs work without downloading a model, but it only matches on word overlap, not meaning. It is labelled as dev and test only so nobody mistakes it for real semantic retrieval.

One more safeguard: each Chroma collection records which embedding model and dimension created it. Opening it with a different model raises an error. Mixing vectors from two models silently ruins retrieval, since the numbers look valid but mean different things. A loud error is far better.

## Retrieval and trust

Two details connect chunking to security:

- **Owner isolation:** every chunk carries an owner type, owner ID and document ID. The store builds the owner filter itself and exposes no filter parameter, so a caller can't ask for someone else's chunks.
- **Untrusted text:** retrieved chunks go into the prompt inside delimited blocks, and the system prompt tells the model they are data, not instructions. If nothing relevant is retrieved, the model isn't called at all.

I'll cover prompt injection and guardrails in their own article.

## What I haven't done

Being upfront about the limits matters more than a tidy story:

- No hybrid search or reranking yet. Retrieval is vector similarity only.
- No evaluation set, so I can't say which chunk size works best.
- Scanned PDFs are rejected because there is no OCR.
- Injection detection is heuristic. The delimiting, system prompt and output validation are the real defences, and none is a guarantee.
- The Chroma Cloud and HTTP server paths are written but untested, and no live Groq request has been made. Local Chroma is tested.

## What to take away

1. Chunking and embeddings decide retrieval quality before the model sees a question.
2. Prefer structure-aware splitting with overlap, and make size a setting.
3. Record which embedding model built your index, and fail loudly on a mismatch.
4. Keep a cheap lexical fallback for tests, and label it clearly.
5. Measure before you tune. Build a small question set first.

Next in this series: a full walkthrough of the pipeline with FastAPI, followed by hybrid search and reranking. The code is at [github.com/Janardhan-AIConsultant/ai-career-coach](https://github.com/Janardhan-AIConsultant/ai-career-coach).

Which should I cover next: hybrid search and reranking, or prompt-injection guardrails? Tell me in the comments.

