Build a Document Q&A Pipeline with Retrieval and Grounded Prompts
Machine LearningModel answerLast updated
Wire together a given embedder, vector store and LLM into a retrieval-augmented question-answering flow, then justify vector similarity search and when this approach beats alternatives.
You are given three ready-made components and a small data class for documents. Your job is to write the glue code that turns a pile of documents into a question-answering system, and then to explain the reasoning behind it. Pseudocode is fine.
from dataclasses import dataclass
@dataclass
class Document:
doc_id: str
text: str
source: str
@dataclass
class Hit:
chunk_id: str
score: float # similarity computed by the store
metadata: dict # whatever was passed to add() for this chunk
class Embedder:
def embed(self, texts: list[str]) -> list[list[float]]: ...
class VectorStore:
def add(self, ids: list[str], vectors: list[list[float]], metadata: list[dict]) -> None: ...
def query(self, vector: list[float], k: int) -> list[Hit]: ...
class LLM:
def generate(self, prompt: str) -> str: ...
Embedder, VectorStore and LLM already work. You write chunking, indexing and answering. Some of this tooling may be unfamiliar, so state your assumptions out loud and ask focused questions (for example: does the store use cosine, dot product or distance? Are vectors normalized? How big is the corpus and how often does it change? Should answers cite sources? What is the context limit?).
Part 1: Build it. Write the indexing path (documents in, searchable entries out) and the query path (question in, answer out). Cover:
- Chunking with stable IDs and metadata that allow citations
- Batched embedding and insertion
- Embedding the question, retrieving the top-k chunks, and building a prompt that keeps the model grounded in them
- What happens when nothing relevant is retrieved
Part 2: Explain retrieval. Why are embeddings needed? How does the search find relevant chunks? Why is cosine similarity a sensible way to compare the question vector with stored vectors? Discuss exact versus approximate nearest-neighbor search, the relationship between cosine, dot product and Euclidean distance, and the limits of cosine.
Part 3: Choose the right tool. When is this retrieval approach the right choice, and when would you pick fine-tuning, stuffing the whole corpus into the prompt, or a plain keyword search or database query instead? Address cost, latency and maintenance.
Hints
Hint 1
Store the chunk text and its source inside the metadata dictionary passed to add(); the Hit objects returned by query() are then all you need to build the prompt and the citations.
Hint 2
Give each chunk a deterministic ID such as doc_id plus chunk index, split with a small overlap so sentences are not cut off from their context, and embed in batches rather than one call per chunk.
Hint 3
Decide what 'nothing relevant' means before writing the prompt: compare the top score to a threshold, and also instruct the model to say it cannot answer when the context lacks the information.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying assumptions
I would confirm: the store's metric (I assume cosine, or dot product on normalized vectors), the corpus size and update rate (assume tens of thousands of documents, updated daily), whether citations are required (yes), and the context budget (assume roughly 8k tokens, so a handful of chunks fit comfortably).
Part 1: The pipeline
Indexing path
def chunk(doc, size=800, overlap=100):
text, out, start, i = doc.text, [], 0, 0
while start < len(text):
piece = text[start:start + size]
out.append((f"{doc.doc_id}#{i}", piece))
i += 1
start += size - overlap
return out
def index(docs, embedder, store, batch=64):
ids, texts, metas = [], [], []
for d in docs:
for cid, piece in chunk(d):
ids.append(cid)
texts.append(piece)
metas.append({"doc_id": d.doc_id, "source": d.source, "text": piece})
for i in range(0, len(ids), batch):
vecs = embedder.embed(texts[i:i + batch])
store.add(ids[i:i + batch], vecs, metas[i:i + batch])
Key choices: deterministic IDs (doc_id#n) make re-indexing idempotent and allow updates or deletes of a changed document. Overlap keeps boundary sentences retrievable. In practice I would split on paragraph or sentence boundaries first and fall back to character windows. The text goes into metadata so no second lookup is needed. Batching cuts network round trips.
Query path
NOT_FOUND = "I could not find this in the provided documents."
def answer(question, embedder, store, llm, k=5, min_score=0.3):
qvec = embedder.embed([question])[0]
hits = store.query(qvec, k)
hits = [h for h in hits if h.score >= min_score]
if not hits:
return NOT_FOUND
context = "\n\n".join(
f"[{n+1}] ({h.metadata['source']})\n{h.metadata['text']}"
for n, h in enumerate(hits))
prompt = (
"Answer using ONLY the numbered context below. Cite sources like [1]. "
f"If the context does not contain the answer, reply exactly: {NOT_FOUND}\n\n"
f"Context:\n{context}\n\nQuestion: {question}\nAnswer:")
return llm.generate(prompt)
The threshold is only meaningful if I know the metric's scale, so it must be tuned on real queries. The instruction in the prompt is a second line of defense, since a threshold alone will not catch chunks that are on-topic but do not answer the question.
Cost: indexing is O(N) embedding calls (batched); a query is one embedding, one nearest-neighbor search and one generation, with generation dominating latency.
Part 2: Why this works
Why embeddings. Keyword matching misses paraphrases ("reset my password" versus "recover account access") and is thrown off by vocabulary mismatch. An embedding model maps text to a vector where semantically similar passages land near each other, because it was trained so that related texts have close vectors. Retrieval then becomes a geometry problem.
Finding neighbors. Exact search compares the query to every vector: O(N·d) per query. That is fine up to roughly a few hundred thousand vectors, and gives perfect recall. Approximate indexes (HNSW graphs, IVF clustering, product quantization) reach sub-linear time by examining a small portion of the space, trading a few percent of recall for large speedups and some extra memory and build time. Tune recall against latency on your own data.
Cosine similarity. cos(a, b) = a·b / (‖a‖‖b‖). It measures the angle between vectors and ignores magnitude, which is desirable because vector length often reflects text length or noise rather than meaning. For unit-normalized vectors, cosine equals the dot product, and squared Euclidean distance is 2 − 2·cos, so all three produce the same ranking. That is why normalizing once lets you use the cheapest operation.
Limits. Cosine scores are not calibrated across queries or models, so a fixed threshold needs tuning. Embeddings can miss exact identifiers, rare names and numbers, so hybrid search (BM25 plus vectors, merged with reciprocal rank fusion) often helps. A reranker over the top 20–50 candidates improves precision. Similarity is not the same as "answers the question".
Part 3: When to use it
Favors retrieval-augmented generation: knowledge that is private, large, or changes often; a need for citations and auditability; the need to remove or update a fact immediately (re-index one document). Updates cost an embedding call, not a training run.
Fine-tuning wins when the goal is behavior rather than facts: style, output format, domain-specific reasoning, or latency-sensitive tasks where a smaller tuned model replaces a long prompt. It is poor at injecting facts that change, and it cannot cite.
Long context wins for small corpora (a few documents), one-off analyses, or tasks needing global reasoning over a whole document, like summarization. Cost and latency scale with every token sent per query, and accuracy often drops for details buried mid-context. Past a few hundred thousand tokens or with many queries, retrieval is cheaper.
Plain search or SQL wins when the question is structured ("orders over $500 last week") or an exact lookup. Do not use an LLM where a query is deterministic and cheaper.
These combine well: fine-tune for format and tone, retrieve for facts, and use SQL tools for structured data.
Evaluation and common mistakes
Measure retrieval and generation separately. For retrieval, build a labeled set of question and relevant-chunk pairs and track recall@k and MRR. For generation, check faithfulness (is each claim supported by the context?) and answer correctness. Common mistakes: chunks that are too large or too small, no overlap, embedding queries and documents with different models, forgetting to normalize when the store assumes it, mixing up scores and distances (higher is not always better), no empty-result path, trusting the model to refuse without an instruction, and judging the system only by how good the final answer reads.