RAG pipeline from scratch
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Build retrieval-augmented generation (RAG) from scratch: answer questions about a company's documents by finding the relevant passages and handing only those to the model. No vector database and no framework, just the three pieces every RAG system is made of.
The model API
vectors = client.embed(["text one", "text two"]) # one list of floats per text, in order
response = client.chat(messages) # messages are {"role": ..., "content": ...} dicts
response.content # the model's answerThe embedding model here is a small bag-of-words model, so runs are deterministic: texts that share content words point the same way. Its vectors are not normalized, like many real models' output. Every call costs a network round trip, so client.embed takes a whole list at once.
Part 1: chunk_text(text, size=40, overlap=10)
Split text into chunks of size words, joined by single spaces. Each chunk starts size - overlap words after the previous one, so neighbours share overlap words and a sentence cut at a boundary still appears whole in one of them.
- Words are separated by any whitespace (
text.split()). - Stop once a chunk reaches the end of the text: never add a chunk that only repeats the overlap.
- Empty text gives
[]. - Raise
ValueErrorunlesssize > 0and0 <= overlap < size(otherwise the window never moves forward).
chunk_text("one two three four five six seven eight", size=4, overlap=2)
# ["one two three four", "three four five six", "five six seven eight"]Part 2: search(client, chunks, question, k=3)
Return the indices of the k chunks most similar to question, best first.
- Embed the chunks in one call, and the question.
- Rank by cosine similarity. A raw dot product rewards long chunks that repeat the query's words.
- Ties keep the chunks' original order.
- An empty
chunkslist returns[]without calling the API.
Part 3: answer(client, docs, question, k=3, min_score=0.2)
docs is a list of {"id": "refund-policy", "text": "..."}.
- Chunk every doc with the defaults from Part 1, remembering which doc each chunk came from.
- Retrieve the top
kchunks, and keep only those that score at leastmin_score. - If none is left, return
NO_ANSWERwithout calling the chat model: it could only guess. - Otherwise call
client.chatwith a prompt that tells the model to answer only from the sources and to cite them, and that holds the question and every kept chunk tagged with its doc id, like[refund-policy] Refunds are issued.... Return the model's answer.
Note
Run plays the scenarios in tests.json, which you can edit: each one calls one of your functions and, for answer, scripts the model's reply and checks what your prompt included. Submit runs all the hidden scenarios. The Trace tab shows every text you embedded and every prompt you sent.
Follow-up questions interviewers ask
- Chunking by words cuts sentences and tables in half. What would you split on instead, and how do you pick the chunk size?
- Embedding every chunk on each question is wasteful. What do you store, and when do you re-embed?
- A million chunks: what replaces the linear scan, and what do you give up?
- The answer is in the docs, but under different words ("money back" vs "refund"). How do hybrid search (BM25 + vectors) and re-ranking help?
- How would you measure whether retrieval is good, separately from whether the answers are good?
- How do you check that every claim in the answer is supported by a cited source?
The approach
RAG is search glued to a prompt. The model doesn't learn your documents: on every question you find the few passages that matter and paste them in, so the answer is grounded in text you control and can cite. Three steps, each its own function:
- Chunk the documents into passages small enough to be specific, with some overlap.
- Retrieve the passages whose embeddings point the same way as the question's.
- Generate an answer from only those passages, or refuse when none is relevant.
Chunking
A sliding window over the words: each chunk starts size - overlap words after the previous one. The overlap means a sentence cut at a boundary still appears whole in one of the chunks.
The subtle part is the end. range(0, len(words), size - overlap) adds one last start too many: once a window reaches the end, the next window only repeats the overlap. Those duplicate chunks waste embedding calls and fill the prompt twice. The loop breaks as soon as a chunk covers the last word. Checking 0 <= overlap < size up front matters too: with overlap == size the window never moves and the loop never ends.
Retrieval
The vectors aren't normalized, so the dot product grows with chunk length: a long chunk that repeats "refund" eight times beats a short chunk that is exactly about refunds. Cosine similarity divides by both lengths and compares only direction:
All chunks go to client.embed in one call. Embedding them one by one gives the same numbers, but at one network round trip per chunk it is the most common reason a RAG demo is slow. sorted is stable, so sorting by (-score, index) keeps the original order for ties.
Generation
Two decisions make the answers trustworthy:
- The threshold. Top-k always returns something, even when nothing is relevant. Below
min_scorethe code returnsNO_ANSWERwithout calling the model: it saves the call, and it stops the model from answering from its own memory ("I think the CEO likes blue"). - Tagged sources. Each chunk goes into the prompt as
[doc-id] text, and the system prompt asks for those tags as citations. The user can check every claim, and you can check automatically that every cited id was actually retrieved.
The instructions go in the system message and the data in the user message, so text inside a document is less likely to be read as an instruction.
Complexity
With n chunks of d dimensions, search is O(n·d) for the scores plus O(n log n) to sort. heapq.nlargest(k, ...) would make the selection O(n log k). Real systems don't rescan at all: they embed the chunks once at index time, store the vectors, and use an approximate nearest-neighbour index (HNSW, IVF) to find the top k in sub-linear time.
Reference solution
import math
CHUNK_SIZE = 40
CHUNK_OVERLAP = 10
NO_ANSWER = "I don't know based on the provided documents."
SYSTEM_PROMPT = (
"Answer the question using only the sources below. After each fact, cite its source id "
"in brackets, like [doc-id]. If the sources don't contain the answer, say you don't know."
)
def chunk_text(text, size=CHUNK_SIZE, overlap=CHUNK_OVERLAP):
if size <= 0 or not 0 <= overlap < size:
raise ValueError("chunk_text needs size > 0 and 0 <= overlap < size")
words = text.split()
chunks = []
start = 0
while start < len(words):
chunks.append(" ".join(words[start:start + size]))
if start + size >= len(words):
break # This chunk reached the end; another would only repeat the overlap.
start += size - overlap
return chunks
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
norms = math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b))
return dot / norms if norms else 0.0
def rank(client, chunks, question):
"""(index, score) for every chunk, best first; ties keep the original order."""
if not chunks:
return []
vectors = client.embed(chunks) # One batched call for all chunks.
[query] = client.embed([question])
scored = [(i, cosine(query, vector)) for i, vector in enumerate(vectors)]
return sorted(scored, key=lambda item: (-item[1], item[0]))
def search(client, chunks, question, k=3):
return [i for i, _ in rank(client, chunks, question)[:k]]
def answer(client, docs, question, k=3, min_score=0.2):
chunks, sources = [], []
for doc in docs:
for piece in chunk_text(doc["text"]):
chunks.append(piece)
sources.append(doc["id"])
hits = [(i, score) for i, score in rank(client, chunks, question)[:k] if score >= min_score]
if not hits:
return NO_ANSWER # Nothing relevant: don't pay for a call that can only guess.
context = "\n\n".join(f"[{sources[i]}] {chunks[i]}" for i, _ in hits)
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": f"Sources:\n\n{context}\n\nQuestion: {question}"},
]
return client.chat(messages).content