Design a Question-Answering System with Document Retrieval
Machine LearningModel answerLast updated
Build a production-ready system that answers questions from local documents using an LLM API, vector search, and streaming responses.
Design and implement a question-answering system that can respond to queries about a collection of local documents using a large language model. Your system should retrieve relevant passages and generate answers with proper citations.
Core Requirements:
- Document Processing: Ingest a directory containing text files (Markdown and PDF formats), split them into manageable pieces, and create searchable representations
- Query Interface: Support both command-line usage and an HTTP API endpoint for asking questions
- Answer Generation: Use an LLM API to generate responses that reference the retrieved content, with streaming output and source attribution
- Reliability: Handle API failures gracefully with appropriate retry logic and error responses
- Configuration: Support environment-based configuration for credentials and settings
- Documentation: Provide setup instructions and basic validation tests
Technical Specifications:
- Assume approximately 1,000 documents totaling around 5 million tokens
- Target sub-2-second time to first response token
- Use embedding dimensions of 1024 with cosine similarity
- Retrieve 5 context passages per query
- Stream generated tokens as they arrive
Deliverables:
Explain your approach to the following:
- How you would structure the document chunks and why
- Your retrieval strategy and the trade-offs involved
- The prompting technique for generating cited answers
- Failure handling for network and API errors
- A lightweight method to assess whether answers are accurate and well-grounded
Include code sketches for the critical components and discuss production considerations.
Hints
Hint 1
Consider combining multiple retrieval methods rather than relying on embeddings alone
Hint 2
Think about how chunk size affects both retrieval quality and generation context
Hint 3
Design your retry logic to handle rate limits differently than transient failures
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
This problem tests your ability to build a practical machine learning system that integrates multiple components: document processing, vector retrieval, LLM interaction, and robust error handling. I'll walk through a complete architecture with concrete decisions.
1. Scope and Scale Analysis
First, let me establish what we're working with:
- Data volume: 1,000 documents, ~5M tokens means roughly 10,000 chunks at 500 tokens each
- Memory footprint: 10k vectors × 1024 dimensions × 4 bytes = ~40MB for embeddings
- Retrieval complexity: At this scale, brute-force cosine similarity (a single matrix-vector multiply) completes in milliseconds. We don't need approximate nearest neighbor libraries like FAISS or Annoy—adding them would be premature optimization
This scoping exercise is important to demonstrate: it shows I'm choosing simplicity where appropriate rather than adding unnecessary infrastructure.
2. System Architecture
Documents → Loader → Chunker → Embedder → Index (vectors + metadata)
↓
Query → Embed → Hybrid Retrieval → Prompt Construction → LLM Stream → Citations
Data model:
@dataclass
class DocumentChunk:
chunk_id: str # hash of file path + offset
source_file: str
page_number: Optional[int] # for PDFs
section_path: str # e.g., "Installation > Linux"
content: str
class VectorIndex:
embeddings: np.ndarray # shape (N, 1024), L2-normalized
chunks: List[DocumentChunk]
file_manifest: Dict[str, str] # path -> checksum for incremental updates
3. Document Chunking Strategy
Why chunking matters: Chunks that are too small lose surrounding context; chunks that are too large dilute the embedding signal and waste prompt tokens.
Approach by file type:
-
Markdown files:
- Split on headers first to respect document structure
- Pack paragraphs into ~500-token chunks with 75-token overlap
- Prepend the full heading path ("Setup > Installation > Linux") to each chunk before embedding—this gives the embedding model crucial context
-
PDF files:
- Chunk per page to enable page-number citations
- If a page exceeds token limits, split it but keep page metadata
Why 500 tokens with 75-token overlap? This balances specificity with context. The overlap ensures that content spanning chunk boundaries isn't lost. Research suggests 400-600 tokens is a sweet spot for most retrieval tasks.
4. Hybrid Retrieval Strategy
Pure vector search has a weakness: it struggles with exact matches like function names, error codes, or specific identifiers. The solution is hybrid retrieval:
def retrieve(self, query: str, k: int = 5) -> List[Tuple[DocumentChunk, float]]:
# Dense retrieval (semantic similarity)
query_embedding = self.embed_text(query)
query_embedding /= np.linalg.norm(query_embedding)
dense_scores = self.embeddings @ query_embedding
dense_top_20 = np.argsort(-dense_scores)[:20]
# Sparse retrieval (keyword matching)
bm25_scores = self.bm25_index.score(tokenize(query))
sparse_top_20 = np.argsort(-bm25_scores)[:20]
# Reciprocal Rank Fusion
combined_scores = defaultdict(float)
for rank, idx in enumerate(dense_top_20):
combined_scores[idx] += 1.0 / (60 + rank)
for rank, idx in enumerate(sparse_top_20):
combined_scores[idx] += 1.0 / (60 + rank)
# Return top k with minimum relevance threshold
top_indices = sorted(combined_scores.keys(),
key=lambda i: combined_scores[i],
reverse=True)[:k]
results = [(self.chunks[i], combined_scores[i]) for i in top_indices]
return [r for r in results if r[1] > 0.1] # relevance threshold
Why Reciprocal Rank Fusion? It combines rankings without needing to normalize incompatible score scales. The formula 1/(60+rank) gives diminishing returns to lower-ranked results.
Relevance threshold: If no chunks score above the threshold, return empty results so the system can respond "I don't have information about that" instead of hallucinating from irrelevant context.
5. Prompt Engineering for Citations
The key challenge: getting the LLM to cite its sources reliably.
Prompt structure:
System: You are a helpful assistant that answers questions based solely
on the provided context. Cite sources inline using [n] notation. If the
answer isn't in the context, say so clearly.
Context:
[1] (installation.md > Setup)
Run `pip install package-name` to install...
[2] (config.md > Environment)
Set the API_KEY environment variable...
User: How do I install the package?
Citation extraction:
- Number each context block in the prompt
- After generation completes, extract all
[n]patterns from the response - Map them back to the original chunks using the numbering
- Return these as structured source references
This approach prevents the model from inventing file names while still allowing natural citation flow.
6. Streaming Implementation
def generate_with_citations(self, query: str, context_chunks: List[DocumentChunk]):
prompt = self.build_prompt(query, context_chunks)
# Stream tokens
collected_text = []
for token in self.llm_client.stream(prompt):
yield {"type": "token", "content": token}
collected_text.append(token)
# Extract and return citations
full_response = "".join(collected_text)
cited_indices = re.findall(r'\[(\d+)\]', full_response)
cited_chunks = [context_chunks[int(i)-1] for i in cited_indices
if 0 < int(i) <= len(context_chunks)]
yield {
"type": "sources",
"sources": [{"file": c.source_file, "page": c.page_number,
"snippet": c.content[:200]} for c in cited_chunks]
}
Streaming provides immediate feedback while still allowing post-processing for citations.
7. Robust Error Handling
This is often the differentiator in ML system design questions.
class RetryConfig:
retryable_status_codes = {429, 500, 502, 503, 504}
max_attempts = 5
base_delay = 0.5
max_delay = 20.0
def api_call_with_retry(self, func):
for attempt in range(self.config.max_attempts):
try:
return func()
except HTTPError as e:
if e.status_code not in self.config.retryable_status_codes:
raise SystemError(f"API error: {e.status_code}", retryable=False)
if attempt == self.config.max_attempts - 1:
raise SystemError("Max retries exceeded", retryable=True)
# Respect server's retry-after if provided
retry_after = e.headers.get("Retry-After")
if retry_after:
delay = float(retry_after)
else:
# Exponential backoff with full jitter
delay = random.uniform(0, min(self.config.max_delay,
self.config.base_delay * (2 ** attempt)))
time.sleep(delay)
except TimeoutError:
if attempt == self.config.max_attempts - 1:
raise SystemError("Connection timeout", retryable=True)
# Apply same backoff for timeouts
Critical points:
- Full jitter prevents thundering herd when multiple requests retry simultaneously
- Never retry 4xx errors (except 429) since they indicate client problems
- Respect
Retry-Afterheaders when the server provides them - Different handling for streaming: only retry before the first token; mid-stream failures should propagate to the client
8. Evaluation Strategy
For a lightweight evaluation approach without labeled data:
Automated metrics:
- Retrieval precision: Sample 50 questions, manually verify that top-5 chunks contain relevant information
- Citation rate: Measure what percentage of answers include at least one citation
- Hallucination detection: Check for information in answers that isn't present in retrieved chunks (requires an LLM-as-judge)
Human evaluation framework:
- Randomly sample 20 question-answer pairs per week
- Rate on three dimensions: correctness (1-3), completeness (1-3), citation quality (1-3)
- Track trends over time as the document collection evolves
Production monitoring:
- Log queries that return zero results (indicates coverage gaps)
- Track average response latency by component (retrieval vs generation)
- Alert on error rate thresholds or sudden drops in citation rate
9. Production Considerations
Persistence: Save index to disk (embeddings as numpy array, metadata as JSON) so the query process can load it without re-embedding:
def save_index(self, path: Path):
np.save(path / "embeddings.npy", self.embeddings)
with open(path / "chunks.json", "w") as f:
json.dump([asdict(c) for c in self.chunks], f)
with open(path / "manifest.json", "w") as f:
json.dump(self.file_manifest, f)
Incremental updates: Store file checksums in the manifest. On re-indexing, only re-embed documents whose checksums changed.
Configuration management:
# .env file
MISTRAL_API_KEY=xxx
EMBEDDING_MODEL=mistral-embed
CHAT_MODEL=mistral-medium
CHUNK_SIZE=500
CHUNK_OVERLAP=75
TOP_K_RESULTS=5
Load with a library like python-dotenv to keep secrets out of code.
Common mistakes to avoid:
- Embedding queries and documents with different models
- Not normalizing embeddings before cosine similarity
- Retrying non-idempotent operations like writes
- Ignoring token limits when constructing prompts
- Missing error context (which file failed during ingestion)
This design balances simplicity with production-readiness, making intentional trade-offs appropriate for the specified scale while remaining extensible for growth.