Retrieval Augmented
Generation

How to give a language model access to a hundred thousand documents without ever putting a hundred thousand documents in the prompt.

Wil A decade in AI  ·  incentivised data training with NEAR AI  ·  retrieval and ingestion systems in production
RETRIEVAL LESSON  ·  the theory, then the code
YOU NEED  ·  Python 3.10+, an editor, one OpenAI API key
COST  ·  Well under a cent of embeddings
EIGHT DEMOS  ·  one per concept, each one runnable
00  ·  How this session runs

Two windows, eight demos

Slides on one side, a terminal on the other. Whenever you see an orange bar, I stop talking and run the command in it. The output on the slide is the real output from that command.

Demo 00 ./run.sh check
Follow along One entry point for everything: ./run.sh setup once, then ./run.sh slides for this deck and ./run.sh demo 5 for any demo. demo/ingestion_pipeline.py is the finished file we build up to.
Part one

Why RAG exists

The problem is not that models are stupid.
The problem is that they are small.

01  ·  Definition

Retrieval Augmented Generation

A language model combined with a retrieval system. The retrieval system searches external sources — documents, databases, knowledge bases — and pulls only the relevant pieces into the prompt, at the moment the model needs them.

The model does not get everything. It gets the right few pages.

This is not a niche technique Almost every language-model product you have used is doing this underneath — a model that searches the web, an assistant that answers from your own files, a support bot that cites the article it used. Retrieval is the default way a model is given anything it was not trained on.

That is the entire idea. Everything else in this session is mechanics.

01  ·  Why anyone builds one

Where you have met one — and why

Where you have met it

  • The support assistant that answers and links the help article.
  • A model that searches the web and cites what it found.
  • A coding assistant that answers about your repository.
  • Internal Q&A over policy, security questionnaires, runbooks.

Why teams build it

  • Your data. No model was trained on your contracts or your tickets.
  • Today's data. A policy changed this morning. Index it; done.
  • Receipts. The retriever knows which chunks it used, so the answer can point at them.
The question everyone asks: why not fine-tune? Fine-tuning teaches a model a style — a format, a voice, a way of reasoning. It is an expensive way to teach it a fact, and a hopeless way to teach it a fact that changes on Tuesday. Retrieval gives a model facts it can point at.
02  ·  Tokens

Models do not read words

A token is the unit of text a model processes. Sometimes a whole word. Often a fragment of one. Models do not read letters and they do not read words.

Demo 01 python 01_tokens.py
text : 'Retrieval augmented generation is powerful' words : 5 tokens : 7 split as : Ret | rie | val | _augmented | _generation | _is | _powerful

One token is roughly three quarters of an English word. Common words are one token; rare or long words split into several. Spaces travel with the token that follows.

02  ·  The context window

Everything has to fit inside one window

The context window is the total number of tokens a model can hold in a single request. Everything you send and everything it writes back has to fit. Past that limit, the information is simply not there.

Where the frontier sits As of 2026 the major models have converged on 1 million tokens — GPT-5.5, Gemini 3.1 Pro, Claude Opus 4.8 and Sonnet 5 all sit there. A few advertise up to 10 million, though no published benchmark shows quality holding near that.
Verify before you quote it. These figures move every few months.
02  ·  The scale gap

Read the scale carefully

How much text, in tokens — logarithmic scale One chunk ███ 1,000 These 5 articles ████████ 72,169 A frontier model window ███████████ 1,000,000 The largest advertised ██████████████ 10,000,000 A mid sized company, 1 TB █████████████████████████ 250,000,000,000 An enterprise archive, 1 PB ██████████████████████████████████ 250,000,000,000,000

Each step to the right is ten times larger, not one step larger. The gap between a model window and an enterprise archive is not a gap you close by waiting for bigger models.

Part two

The shape of the system

Two pipelines, not one.
Learn them separately and the rest is easy.

03  ·  The whole system in one picture

Two pipelines

Pipeline 01  ·  INGESTION  ·  runs once, before any question
Sourcedocuments
→
Chunkingcut to size
→
Embeddingmodel
→
Vectorslists of numbers
→
Vectordatabase
Pipeline 02  ·  RETRIEVAL  ·  runs on every question
Userquestion
→
Embeddingmodel
→
Retrieverranks by closeness
→
Top matchingchunks
→
LLM writesthe answer
Not a drawing shortcut The same embedding model appears in both rows. That is the single most important detail on this slide, and we will break it on purpose at the end to show you why.
04  ·  Chunking

A chunk is a slice, not a section

Chunking is breaking large documents into small pieces. You choose the size. Set it to 1,000 tokens and 10 million tokens of documents becomes 10,000 chunks.

The word "chunk" is doing work here Chunks are cut by size, not by meaning. They do not respect chapters, headings or arguments. A naive splitter will cut through the middle of a sentence or a table without hesitating.

Why cut at all? Because nobody wants an entire Wikipedia article returned because one sentence in it matched. The chunk is your unit of retrieval — it is the smallest thing the system can hand back.

04  ·  The embedding model

This is not an LLM

Different model, different job. It does not generate text. Text goes in; a list of numbers comes out.

Demo 02 python 02_embedding_shape.py
one word 1 words in -> 1536 numbers out one sentence 8 words in -> 1536 numbers out a paragraph 337 words in -> 1536 numbers out [ -0.0616 +0.0554 +0.0004 +0.0124 +0.0016 -0.0123 ... ]

Fixed length output. One word in or nine hundred words in, the vector that comes out is always the same length.

Why it is always the same length

The model reads the text once and produces one vector per token, then pools them into a single vector. Pooling is what throws the length away.

Three properties worth knowing

  • Unit length. Every vector comes back normalised, so cosine similarity is just a dot product.
  • 8,192 token cap. Longer input is truncated silently — another reason to chunk.
  • The dimensions are ordered. Keep the first 512 and renormalise and it still works — a third of the storage.
05  ·  What an embedding is

Similar meaning, similar numbers

A vector embedding is a list of numbers that stands in for a piece of text. Each number is called a dimension.

Text with similar meaning produces similar numbers.
Nothing else about embeddings matters as much as that sentence.
WordDim 1 · sizeDim 2 · domesticatedDim 3 · sound
cat3487.5
kitten3387.1
dog4086.9
elephant210621.2

Real dimensions are not labelled and nobody knows what any single one means. These labels are a teaching device only.

05  ·  Eight real words

Does that actually hold?

Demo 03 python 03_similar_meaning.py
cat -> dog 0.603 ████████████████████████ cat -> kitten 0.570 ███████████████████████ cat -> coffee 0.385 ███████████████ cat -> tea 0.358 ██████████████ cat -> apple 0.357 ██████████████ cat -> elephant 0.319 █████████████ cat -> mango 0.264 ███████████ DOMESTIC ANIMALS inside 0.531 outside 0.316 DRINKS inside 0.611 outside 0.313

Every group is tighter inside than out. That is a neighbourhood — and nobody labelled any of it.

06  ·  Where the vectors live

The vector database stores both

IDVectorOriginal textSource
0001[0.021, -0.884, ...]Refunds are issued within 30 days.policy.pdf
0002[-0.412, 0.663, ...]Q1 revenue reached 4.2 million.sales.xlsx
0003[0.907, 0.115, ...]Guest wifi resets every Monday.itwiki.md
One row per chunk The vector is how it gets found. The original text is what gets used. Store only the numbers and you have nothing to send the model.

Purpose built: Pinecone, Weaviate, Chroma, Qdrant. FAISS is a library rather than a service. Or add pgvector to a Postgres you already run.

Part three

Retrieval, in principle

Ingestion is finished. Nothing above runs again
until your documents change.

07  ·  Retrieval, step by step

The question takes the same road

  1. The question goes through the same embedding model the documents went through.
  2. It comes out as a vector of the same length.
  3. The retriever compares that one vector against every stored vector.
  4. It ranks them by closeness and returns the top k.
— worked example, not a program run — THE QUESTION "What were our sales in the first quarter?" ↓ [-0.398, 0.671, 1.194, ...] same model, same dimensions 0.91 Q1 revenue reached 4.2 million. ┐ 0.88 Quarterly sales by region, Jan to Mar. ├ top 3 to the LLM 0.84 Revenue targets for the first quarter. ┘ 0.42 Annual headcount summary. 0.31 Refunds are issued within 30 days. 0.19 Guest wifi resets every Monday.
Part four

Build the ingestion pipeline

Five articles in. A searchable vector database out.
About sixty lines of Python and one API key.

Five articles go in. A searchable database comes out.
Three steps — and what each one actually produces.

08  ·  Step one

Load the files

def load_documents(docs_path):
    # Fail loudly and early rather than silently loading nothing
    folder = Path(docs_path)
    if not folder.is_dir():
        raise FileNotFoundError(f"Directory not found: {docs_path}")

    documents = [
        Document(
            page_content=path.read_text(encoding="utf-8"),
            metadata={"source": f"{docs_path}/{path.name}"},
        )
        for path in sorted(folder.glob("*.txt"))   # sorted = reproducible
    ]

    if len(documents) == 0:
        raise ValueError(f"No .txt files found in {docs_path}")

    return documents
Demo 04 python 04_load.py
08  ·  What comes back

Five files in, five Documents out

Loaded 5 documents google.txt 68,012 characters microsoft.txt 67,411 characters nvidia.txt 62,402 characters spacex.txt 55,954 characters tesla.txt 93,916 characters .page_contentthe text 'Google LLC ( , GOO-gəl) is an American multinational...' .metadataits source {'source': 'docs/google.txt'}docs/google.txt
Learn these two attributes now .page_content is the entire text of the file as one long string. .metadata is a dictionary — here, the file we read it from. This object shows up everywhere from here on. Two halves, and you need both Every record is the text itself — the whole file as one long run of characters — and where it came from. The second half is what lets an answer cite its source.
09  ·  Step two

Chunk them

def split_documents(documents, chunk_size=800, chunk_overlap=0):
    splitter = CharacterTextSplitter(
        chunk_size=chunk_size,
        chunk_overlap=chunk_overlap,
        separator="\n\n",         # prefer to break at paragraph boundaries
    )
    return splitter.split_documents(documents)
Demo 05 python 05_chunk.py
Note the unit chunk_size=800 means 800 characters, not 800 tokens. Roughly 200 tokens. Different splitters count differently — always check which unit you are in.
09  ·  The result

800 is a target, not a cap

Split 5 documents into 539 chunks chunks 539 smallest 15 characters largest 1,719 characters average 643 characters 79 of 539 chunks came out longer than the 800 target
Why CharacterTextSplitter splits on the separator first, then merges pieces up to chunk_size. It never breaks a paragraph in half to hit the number. So you will see warnings — they are warnings, not errors.
RecursiveCharacterTextSplitter handles this better and is what you would use in a real project. We stay on the simple one so the mechanics show.
The splitter breaks on blank lines first, then glues the pieces back together up towards your target. What it will never do is cut a paragraph in half to hit the number — so a long paragraph gives you a long chunk.
09  ·  Overlap

What chunk_overlap actually does

chunk_overlap = 0overlap = 0 characters [0] Tesla was incorporated in July 2003 by Martin Eberhard and Marc Tarpenning as Tesla Motors. Its name is a tribute to the [1] inventor Nikola Tesla. In February 2004 Elon Musk led Tesla's... chunk_overlap = 40overlap = 40 characters [0] Tesla was incorporated in July 2003 by Martin Eberhard and Marc Tarpenning as Tesla Motors. Its name is a tribute to the [1] Motors. Its name is a tribute to the inventor Nikola Tesla. In...

With overlap at zero, a sentence that straddles the boundary ends up half in one chunk and half in another — and neither half matches the question well.

Rule of thumb: 10–20% of chunk size. For 800 characters, 100 is a reasonable default.

10  ·  Step three

Embed and store — one call does both

def create_vector_store(chunks, db_path):
    embeddings = OpenAIEmbeddings(model="text-embedding-3-small")

    vector_store = Chroma.from_documents(
        documents=chunks,
        embedding=embeddings,
        persist_directory=db_path,
        collection_metadata={"hnsw:space": "cosine"},
    )
    return vector_store
Demo 06 python 06_embed_store.py
This is the step that costs money and takes time Every chunk is a call to OpenAI. Expect thirty seconds to a couple of minutes.
10  ·  What landed on disk

One row per chunk

Stored 547 vectors in db_chroma/ the collection now holds 547 vectors the vector 1,536 numbers [+0.0223, -0.0135, -0.0015, ...] the original text 'Google LLC ( , GOO-gəl) is an American multinational...' the metadata {'source': 'docs/google.txt'}
db_chroma/
├── chroma.sqlite3          text, metadata, ids
└── a1b2c3d4-.../           the collection
    ├── data_level0.bin     the vectors
    └── link_lists.bin      the search index

The original text is not optional. Without it you have numbers and nothing to send an LLM.

11  ·  Confirm it worked

Ask it something

Demo 07 python 07_query.py "Who founded SpaceX?"
question 'Who founded SpaceX?' collection 547 vectors 0.662 ███████████████ spacex.txt In early 2002, Elon Musk started to look... 0.628 ██████████████ spacex.txt SpaceX was founded in 2002 by Elon Musk... 0.627 ██████████████ spacex.txt Space Exploration Technologies Corp., ... 0.598 █████████████ spacex.txt The company is credited with advances... 0.591 █████████████ spacex.txt In early 2012, approximately two-thirds...

All five from spacex.txt, out of a store containing four other companies. Your ingestion pipeline is finished and correct.

11  ·  The actual prompt

This is what reaches the model

│ Answer the question using only the context below. │ │ CONTEXT: │ In early 2002, Elon Musk started to look for staff for his company, │ soon to be named SpaceX. Musk approached five people for the initial │ positions, including Griffin, who declined the position of Chief │ Engineer, Jim Cantrell and John Garvey ... │ │ SpaceX was founded in 2002 by Elon Musk with the goal of reducing │ spaceflight costs ... │ │ QUESTION: Who founded SpaceX? prompt length: 2,972 characters, built from the top 3 chunks

Sent: the question, plus the original English text.  Not sent: the vectors. Their job finished the moment the matching was done.

Part five

The mistake that breaks
most first builds

Nothing crashes. There is no error message.

12  ·  The consistency rule

The consistency rule

Use the same embedding model and the same dimension count for your documents and for your queries. Every time. No exceptions.

Documents embedded in January

text-embedding-3-large
3,072 dimensions

Queries embedded in March

text-embedding-3-small
1,536 dimensions

Think of them as separate languages A vector written by one model means nothing to another. The two systems cannot understand each other, and neither one will tell you.
12  ·  Break it on purpose

Same store. Same question. Nothing crashes.

Demo 08 python 08_model_mismatch.py
question: 'Who founded SpaceX?' (answer lives in spacex.txt) RIGHT model text-embedding-3-small 0.662 spacex.txt In early 2002, Elon Musk started to look... 0.628 spacex.txt SpaceX was founded in 2002 by Elon Musk... 0.627 spacex.txt Space Exploration Technologies Corp., ... WRONG model text-embedding-3-large@1536 0.064 spacex.txt === Starbase, Texas === SpaceX manufact... 0.055 spacex.txt In December 2022, the U.S. Federal Comm... 0.052 microsoft.txt Microsoft became the third publicly ... ← WRONG FILE

Scores collapse from 0.66 to 0.06, and a Microsoft chunk is returned for a question about SpaceX.

13  ·  Summary

The whole session in ten lines

  1. Models have a token limit. Real document stores are millions of times larger.
  2. So you retrieve the relevant pieces instead of sending everything.
  3. A RAG system is two pipelines. Ingestion runs once; retrieval runs per question.
  4. Ingestion: cut documents into chunks, embed each chunk, store vectors with their text.
  5. An embedding is a fixed-length list of numbers where similar meaning gives similar numbers.
  6. A vector database stores those numbers and searches them fast.
  7. Retrieval: embed the question the same way, rank by closeness, take the top k.
  8. Send the model the question plus the original text. Never the vectors.
  9. Set chunk_overlap so sentences on the seam survive. Set persist_directory or you lose the work.Overlap your chunks so sentences on the seam survive. Tell the database where to save, or you lose the work.
  10. One embedding model, one dimension count, everywhere. Breaking this fails silently.

Next: the retrieval
pipeline

You take a question, embed it with that same model, pull the closest chunks out of db_chroma/, and hand them to an LLM to answer.

Two pipelines. Chunk, embed, store the text with the numbers. Ask with the same model, rank by closeness, send the paragraphs — never the vectors.

THE RESULT  ·  547 vectors on disk, searchable, with sources
LOCKED IN  ·  text-embedding-3-small at 1,536 dimensions
BRING  ·  a set of documents you actually want to ask questions about
YOU CAN NOW  ·  draw both pipelines and say what each box is for
YOU KNOW THE TRAP  ·  one embedding model, one dimension count, everywhere
TO GO FURTHER  ·  the playgrounds, the code, and the long version
ALL OF IT  ·  ragverse.diy