Design a Grounded Document Q&A Assistant on a Hosted LLM API
System DesignModel answerLast updated
Build a small retrieval-augmented chat tool with streaming answers, short memory, resilient API calls and tests, then justify the key design trade-offs.
Task
You are asked to build, and then defend, a small command-line assistant that answers questions about a local set of documents using a hosted LLM provider's embedding and chat endpoints.
Part 1: Implementation
Write a compact Python tool that:
- Ingests a small local corpus (Markdown and/or PDF files), splits the text into chunks, computes embeddings, and stores them in a searchable index.
- Retrieves the top-k most relevant passages for a user question.
- Builds a prompt from the retrieved passages and calls the provider's chat completion endpoint with streaming output.
- Maintains short-term conversation memory so follow-up questions work.
- Reads the API credential from an environment variable (never hard-coded).
- Handles errors, retries and rate limits sensibly.
- Ships with a short README and a few smoke tests.
Part 2: Design discussion
Explain and justify your choices for:
- Chunking strategy
- Embedding model selection
- Vector index choice
- Latency and cost budget
- Caching
- Prompt templating
- Safety and PII handling
- Logging and monitoring
- Offline evaluation of retrieval and answer quality
- Fallback behavior when retrieval finds nothing useful
State your assumptions about corpus size, traffic and latency targets up front. A strong answer shows working, minimal code and quantified trade-offs.
Hints
Hint 1
Start by estimating scale: a few thousand chunks fit in memory as a normalized matrix, so brute-force cosine similarity may be all you need before reaching for a vector database.
Hint 2
Separate retryable failures (rate limits, 5xx, timeouts) from non-retryable ones (other 4xx). Use exponential backoff with jitter and respect any server-provided wait hint.
Hint 3
Decide up front what happens when the best similarity score is low: tell the model there is no context and instruct it to say it does not know, rather than letting it guess.
Hint 4
For evaluation, build a small labeled set of question and source-chunk pairs and measure recall@k and MRR for retrieval separately from answer faithfulness.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing
Spend roughly 40% of the time on a minimal working tool and 60% on defending the decisions with numbers.
Assumptions
- Corpus: ~100 documents, 1-5 MB of text, so about 2k-10k chunks. This fits in memory.
- Traffic: a single-user CLI today, perhaps a team service at ~5 QPS later.
- Latency: time-to-first-token under ~1.5 s, full answer under ~6 s.
- Cost: well under one cent per query using a small chat model. Corpus embedding is a one-time cost.
- Quality: answers must be grounded and cite sources. If the corpus lacks the answer, say so.
Architecture
ingest: files -> loader -> cleaner -> chunker -> batched embeddings -> index (matrix + metadata)
query: question (+memory) -> embed -> top-k cosine -> score threshold
-> prompt (system + context + history + question) -> streaming chat -> citations
- Loader: a PDF library for PDFs, plain reads for Markdown. Keep source, page and heading as metadata on each chunk.
- Index: a normalized float32 matrix (N x dim) plus a JSONL metadata file. At 10k chunks and ~1k dimensions that is about 40 MB, and brute-force search takes a few milliseconds.
- Memory: a rolling window of the last few turns, trimmed to a token budget.
Core implementation sketch
import os, json, time, random, re, numpy as np, requests
API = "https://<provider-base-url>/v1"
KEY = os.environ.get("LLM_API_KEY") or exit("Set LLM_API_KEY")
H = {"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"}
def call(path, payload, stream=False, retries=5):
for attempt in range(retries):
try:
r = requests.post(f"{API}/{path}", headers=H, json=payload,
stream=stream, timeout=(5, 60))
if r.status_code == 429 or r.status_code >= 500:
wait = float(r.headers.get("Retry-After", 2 ** attempt))
time.sleep(wait + random.random())
continue
r.raise_for_status() # other 4xx: fail fast
return r
except (requests.ConnectionError, requests.Timeout):
time.sleep(2 ** attempt + random.random())
raise RuntimeError(f"{path} failed after {retries} retries")
def chunk(text, size=800, overlap=120):
out, cur = [], ""
for p in re.split(r"\n\s*\n", text):
if len(cur) + len(p) > size and cur:
out.append(cur); cur = cur[-overlap:]
cur += "\n\n" + p
return out + ([cur] if cur.strip() else [])
def embed(texts, bs=32):
vecs = []
for i in range(0, len(texts), bs):
d = call("embeddings", {"model": EMBED_MODEL, "input": texts[i:i+bs]}).json()
vecs += [e["embedding"] for e in d["data"]]
v = np.array(vecs, dtype=np.float32)
return v / np.linalg.norm(v, axis=1, keepdims=True)
The RAG class holds the chunk metadata and matrix. retrieve embeds the query, takes the dot product against the matrix, returns the top-k hits at or above a minimum score. ask formats the context with numbered citations, prepends a system instruction ("answer only from context, cite as [n], say you don't know otherwise"), appends trimmed history, streams the SSE response line by line (data: ... until [DONE]), prints deltas as they arrive and appends the turn to memory.
README and smoke tests
README: install, export LLM_API_KEY=..., ingest and chat commands, config knobs, known limits. Tests (HTTP mocked in CI):
- Chunker respects the size cap and keeps overlap.
- Retrieval with fake embeddings returns the planted document.
- A 429 followed by a 200 succeeds and honors
Retry-After. - A canned SSE stream reassembles into the right text.
- A missing key gives a clear error.
- One optional live test, marked separately.
Design deep dives
Chunking. Structure-aware chunks of ~200-400 tokens with 10-15% overlap; split on headings and paragraphs first, characters last. Prepend document title and section heading to each chunk, which improves recall. Small chunks are precise but lose context; large chunks dilute the embedding. Tune on the eval set.
Embedding model. Use the provider's embedding model for one key, one bill and consistent tokenization. Batch requests and cache by hash of chunk text so re-ingest only embeds changes. Consider a local open model (bge, e5) for data residency or very large corpora. Mention hybrid retrieval: BM25 plus dense vectors fused with reciprocal rank fusion helps with identifiers, error codes and acronyms.
Vector index.
| Scale | Choice |
|---|---|
| < ~100k chunks | Brute-force matrix product in NumPy |
| 100k-10M | HNSW (FAISS, hnswlib) or a pgvector index |
| > 10M or multi-tenant | Managed or sharded vector DB with metadata filtering |
Latency and cost. Budget: embed query ~100 ms, search <10 ms, prompt build negligible, TTFT ~500-1000 ms. Streaming makes perceived latency the TTFT. Cost is dominated by prompt tokens: 4 chunks x ~300 tokens plus history is about 2k input tokens, so a small model costs a fraction of a cent. Control cost with k, history trimming, and routing only hard questions to a larger model.
Caching. Embedding cache keyed by content hash; query-embedding cache; optional answer cache keyed by normalized question plus corpus version, with invalidation on re-ingest.
Prompt templating. Fixed system block with grounding rules, numbered context with source labels, then history, then question. Keep retrieved text clearly delimited and tell the model to treat it as data, not instructions, which mitigates prompt injection from documents. Rewrite follow-up questions into standalone queries using memory before retrieval.
Safety and PII. Scan at ingest and optionally redact emails, phone numbers and IDs; respect document-level access control through metadata filters; never log raw secrets or full prompts at info level; keep the key in the environment and out of logs and repos.
Logging and monitoring. Structured logs per request with a request ID, retrieved chunk IDs and scores, token counts, TTFT, total latency, retry count and error class. Alert on error rate, p95 latency, rising "no context" rate and cost per query.
Offline evaluation. Build 50-200 labeled question-to-chunk pairs. Retrieval: recall@k, MRR, nDCG. Generation: faithfulness (is each claim supported by cited text), answer relevance and correct abstention on unanswerable questions, scored by humans or a calibrated LLM judge. Use it to compare chunk sizes, k, thresholds and hybrid versus dense.
Fallbacks when retrieval fails. If the top score is below threshold: say so explicitly, optionally retry with a rewritten or expanded query, or fall back to keyword search; suggest clarifying questions. If the embedding service is down, degrade to BM25. If chat fails after retries, return the top passages with sources instead of an error.
Common mistakes
- Retrying non-retryable 4xx errors, or retrying without jitter.
- No score threshold, so the model confidently answers from irrelevant context.
- Embedding the full history instead of a rewritten standalone query.
- Unbounded memory that blows the context window.
- Re-embedding the whole corpus on every run.
- Evaluating only the final answer, so retrieval and generation failures are indistinguishable.