Retrieval and memory
Embeddings, vector search, hybrid retrieval and memory: how a model gets the right context into a small window.
By the end of this chapter
- Explain embeddings and nearest-neighbour search visually
- Compare chunking and retrieval strategies under a token budget
- Know what a retrieval pipeline for a real site looks like
Why a model needs retrieval
A model only sees what is in its context window, the text you send with each request. Text is counted in tokens, which are word pieces. Everything else the model knows is baked into its weights during training, and that knowledge goes stale and cannot be checked. Retrieval-augmented generation, or RAG, fixes this by looking up relevant text first and putting only that text into the window.
The window is a limited budget, so the question is always which text earns a place in it. Aditya's paper on this, CAG: chunked augmented generation for Google Chrome's built-in Gemini Nano (arXiv:2412.18708, with V. Vellaiyappan Surulimuthu), is the title of that work. This course does not summarise its results. Read the paper for those.
The rest of the chapter works up from the smallest piece, the embedding, to a retrieval pipeline running on this site.
Embeddings and nearest neighbours
An embedding is a list of numbers, a vector, that a model produces for a piece of text so that similar meanings get nearby vectors. You can think of each vector as a point in space. Real embeddings have hundreds of dimensions. The plot below uses two so you can see it, with made-up positions.
To search, embed the query, then find the k nearest neighbours: the k stored points closest to it. "Closest" can mean straight-line distance, or cosine similarity, which compares the angle between two vectors and ignores their length. Switch between the two below. In embenx, the library from the embenx post, the scores printed for a plain search are distances, so lower is better: in the post's example, Apple scores 0.0000, Strawberry 0.0200 and Blueberry 2.0000 for the query [1, 0, 0, 0].
Top 3 by straight-line distance: 1. adapter, 2. rank, 3. LoRA. Click the plot or use the sliders to move the query.
Searching every point works for small collections. Larger ones use an approximate index such as HNSW, which finds close neighbours without comparing against everything. embenx puts one Collection interface over more than 15 such backends, so changing the index is a one-line change to indexer_type.
Chunking under a token budget
You rarely embed a whole document. You cut it into chunks and embed each one, so a hit returns a passage, not a book. Chunk size is a trade-off. Large chunks blur several topics into one vector. Small chunks lose their surroundings. And whatever you retrieve must fit the budget.
Chunks are taken best first. A chunk that would overflow the budget is skipped. The whole toy document is 2,800 tokens, so a smaller budget means leaving out lower-ranked chunks. Schematic: sizes and scores are invented.
Tokens per paper measured this on a 23-page Nature paper. The extracted text was 21,736 tokens. Cutting the reference list and journal boilerplate left 13,483, which is 38% less. Three ways of preparing the same paper for embedding, all using the same embedding model (all-MiniLM-L6-v2), the same 512-token window and the same eight questions, gave Recall@3 of 6 of 8 for raw PDF text, 6 of 8 for DocLang markup, and 7 of 8 for Docling's structured text. Docling's text also indexed the fewest tokens, 23,136, against 27,856 for raw PDF text and 70,535 for DocLang. The post says that 6 versus 7 is within noise at this sample size.
Two cautions from the same post. First, retrieval can be the wrong tool. For a briefing that needs ten specific facts, retrieving 19 chunks for 4,625 tokens found 7 of 10, while filtering the document by section found all 10 at 13,483 tokens. For questions like "list every named agent", vector top-5 found 12 of 122 items, and scanning the document structure found all 122. Second, chunkers can break the budget: at a default of 256 tokens, one table came out at 267 and would have been silently cut off when embedded, so the post asserts that no chunk exceeds the embedding window.
Hybrid search, filters and memory
Embeddings match meaning but can miss an exact word. A keyword method such as BM25 scores documents by how many query words they contain and how rare those words are, which gets exact terms right but misses paraphrases. Hybrid search runs both and fuses the two ranked lists. embenx uses Reciprocal Rank Fusion (RRF): each list gives a document a score based on its rank, 1 over (a constant plus rank), and the scores are added with weights you choose.
Query: a vector that matches doc1, plus the word "lazy". At 1.0 only meaning counts and doc1 wins. At 0.0 only the keyword counts and doc2 wins. In between, documents that rank in both lists rise. Schematic: the ranks are invented to match the example's comments, and the fusion constant is 1 (textbook value 60) so the effect is visible.
In the post's example the call is hybrid_search(query_vector=[1, 0, 0, 0], query_text="lazy", top_k=3, dense_weight=0.5, sparse_weight=0.5). Aditya's own observation from testing was that about 0.6 dense and 0.4 sparse suited conversational queries, and the reverse suited structured documents where terminology matters. Treat that as one author's rule of thumb, not a law.
The same library covers two more ideas. A where clause filters on metadata before the nearest-neighbour search, so the top k comes only from allowed documents. And memory is retrieval over what an assistant has seen before. TemporalCollection, based on arXiv:2502.16090, adds a recency_weight: 0.0 means pure semantic similarity and 1.0 means pure recency. The post says most practical assistants land around 0.3 to 0.5.
A real pipeline: the chat on this site
The hero chat post describes the retrieval system behind the chat on the homepage. It has two lanes. At build time, a script turns every post and a few project pages into one markdown document each and uploads them to an R2 bucket, and a GitHub Actions run triggers Cloudflare AI Search to re-index. The index reported 17 items indexed and 0 errors. At request time, a Cloudflare Pages Function answers questions.
HeroChat sends the messages and the chosen persona. Credentials never reach the browser. It only talks to POST /api/hero-chat.
The design choice worth copying is the guardrail. The system prompt tells the model to answer only from retrieved sources, and a relevance threshold of 0.4 decides which chunks count as citations. When nothing clears it, the user gets a plain fallback, not a guess. The post also notes the total cost shown on Cloudflare's billing page was $0.00 at this site's traffic, on a pay-as-you-go account, and says it would not stay at zero if traffic grew.
Try it yourself
embenx is on PyPI. Install it and run the filter example from the post:
pip install embenx
from embenx import Collection
import numpy as np
col = Collection(dimension=4, indexer_type="faiss")
vectors = np.array([
[1.0, 0.0, 0.0, 0.0],
[0.9, 0.1, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
], dtype=np.float32)
metadata = [
{"text": "Apple", "category": "fruit", "id": 1},
{"text": "Strawberry", "category": "fruit", "id": 2},
{"text": "Blueberry", "category": "berry", "id": 3},
{"text": "Broccoli", "category": "vegetable", "id": 4},
]
col.add(vectors, metadata)
all_results = col.search([1, 0, 0, 0], top_k=3)
fruit_results = col.search([1, 0, 0, 0], top_k=5, where={"category": "fruit"})The post says the unfiltered search returns Apple, Strawberry, Blueberry, and the filtered one returns only Apple and Strawberry. Check that, then try a different top_k. The post also mentions embenx explorer, a local web UI with a RAG Playground, and embenx mcp-start, which exposes collections as memory tools to MCP clients.
Conceptual exercise: take any long document you know. Decide how you would chunk it, what budget you would allow, and one question that vector search would answer well and one "list every" question that it would not.