Build a Document-Grounded Q&A Assistant for One Domain
Machine LearningModel answerLast updated
Design an enterprise conversational system that answers questions from a curated knowledge base with citations, handles multi-turn dialogue, and escalates when uncertain.
You're building a question-answering assistant for a company's specific knowledge domain—think customer support for a product family or internal policy documentation for HR.
Your system needs to:
- Sustain back-and-forth conversations where context carries across turns
- Pull answers exclusively from the company's approved content (docs, FAQs, policies)
- Show which sources support each claim in the response
- Refuse to fabricate information when the knowledge base doesn't cover a question
- Let admins refresh the underlying content
- Route unclear or difficult queries to human specialists
- Operate within realistic performance and budget constraints
Cover the complete architecture:
- How clients interact and how you track conversation state
- Getting documents into the system and keeping them searchable
- Finding and ranking relevant content for each query
- Constructing inputs for the language model and serving responses
- Protecting against misuse and enforcing access rules
- Measuring quality and diagnosing failures
- Handling load and ensuring reliability
Hints
Hint 1
Start by quantifying scale: how many users, documents, and queries? This determines whether you need distributed infrastructure or simpler components.
Hint 2
The core challenge is retrieval quality and hallucination prevention—most complexity lives in finding the right passages and verifying the model only says what those passages support.
Hint 3
Think through the document lifecycle: ingestion, chunking strategy, versioning, and how updates propagate without breaking active sessions.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests whether you understand retrieval-augmented generation as a production system, not just an LLM API call. The interviewer wants to see you handle freshness, retrieval precision, refusal mechanisms, human handoff logic, and measurement.
Start by scoping the problem with concrete numbers, then build from the data layer upward.
Scope and Requirements
Establish baseline assumptions through clarifying questions:
- Traffic: 50k monthly active users, peak 2k concurrent conversations, roughly 1M messages/month. Average session is 6 turns. Peak query rate around 30/second.
- Content: 20k documents totaling maybe 200k chunks after segmentation. Daily updates are routine; critical changes need to appear within minutes.
- Performance: Initial response token under 1.5 seconds (p50), complete answer under 6 seconds (p95).
- Budget: Target $0.01–0.02 per interaction, which rules out expensive frontier models on every call.
- Quality bar: 95%+ of answers must be grounded in cited sources. Escalation decisions should be correct 90%+ of the time. Hallucination rate under 1% on held-out test queries.
- Operational: 99.9% uptime, PII handling, audit trails, document-level permissions (some content is internal-only).
Assume the assistant is read-only: it answers questions and can hand off to agents, but doesn't execute actions like refunds or account changes.
API and Session Design
POST /api/conversations → {conversation_id}
POST /api/conversations/{id}/turn {message, user_context} → SSE stream
→ tokens, {sources:[{doc_id, chunk_id, title, excerpt}]}, {status: answered|escalated}
POST /api/conversations/{id}/feedback {turn_id, thumbs, comment}
POST /api/conversations/{id}/transfer → {ticket_id}
Admin: POST/PUT/DELETE /api/knowledge/documents
State management: Store recent turns, a running summary, and user attributes (role, region, subscription tier) in Redis with 24-hour TTL. Write full transcripts to Postgres for compliance and evaluation. API servers are stateless—any instance can handle any turn using the session key.
Data Schema
documents(id, version, source_url, title, access_groups, ingested_at, active)chunks(id, doc_id, version, content, section_path, vector_embedding, access_groups)—these populate both vector and keyword indexesturns(conversation_id, sequence, role, text, retrieved_chunks, model_used, confidence, latency_ms)feedbackandeval_set(query, golden_doc_ids, reference_answer, should_transfer)
Architecture Overview
Client → Gateway (authn, rate limit) → Orchestration Service
Orchestration flow:
1. Input validation (redact PII, check for injection attempts)
2. Query reformulation (conversation context + new message → standalone question)
3. Hybrid retrieval (keyword + semantic, filtered by access rules) → top 50 candidates
4. Neural reranking → top 5–8 passages
5. Confidence gate → if weak match, skip generation and transfer or clarify
6. Prompt assembly → LLM streaming call
7. Output validation (verify citations exist, check groundedness)
→ Stream response or initiate handoff
Ingestion Pipeline: Source connectors → Queue → Parser → Chunker → Embedder → Index (atomic swap)
Observability: Distributed traces, quality metrics, automated eval runs, feedback aggregation
Document Ingestion
Collection: Connectors for help centers, wikis, file uploads emit change events to a queue. Workers parse HTML, PDF, DOCX, preserving structure (headings, tables). OCR for scanned documents when needed.
Chunking: Segment by logical structure—sections or subsections—targeting 300–500 tokens with small overlap. Prefix each chunk with document title and heading hierarchy so it's interpretable in isolation.
Embedding: Generate vectors and write chunks to both a vector store (HNSW in pgvector or a managed service) and a keyword index (Elasticsearch or similar). Tag each chunk with doc_id, version, and access_groups.
Versioning: Index new versions alongside old ones, flip an active-version pointer atomically, then prune outdated chunks. This enables rollback and zero-downtime updates. Content hashing skips re-indexing unchanged documents. Deletes apply immediately via a tombstone check at query time.
At 200k chunks, a single replicated index suffices. Full re-embedding on model upgrades is a batch job of a few hours.
Retrieval and Ranking
Query rewriting: Multi-turn dialogue produces ambiguous follow-ups ("What about the premium tier?"). A lightweight model converts conversation history plus the new message into a self-contained query.
Hybrid search: Combine dense retrieval (semantic similarity) with BM25 (exact keyword matching) using reciprocal rank fusion. Dense embeddings capture paraphrases; keywords catch SKUs, error codes, and exact phrases. Apply access filters and metadata constraints (product version, geography) during retrieval, not after.
Reranking: A cross-encoder model scores the top 50 candidates and selects the best 5–8. This typically adds ~100ms and is the single largest quality improvement.
Boosting: Hand-curated FAQs or high-confidence answers get a small score lift.
Caching: Normalize and cache embeddings for frequent queries to cut latency and cost.
Prompt Engineering and Model Serving
System prompt: Define the assistant's role and explicit constraints: answer only from provided sources, mark citations as [1], [2], and explicitly say "I don't have information on that" when sources don't cover the question.
Context construction: Assemble numbered sources (the reranked chunks with titles), conversation summary, and last 3–4 turns. Budget roughly 4–6k input tokens.
Isolation: Use clear delimiters around retrieved text and mark it as untrusted data to mitigate indirect prompt injection from malicious documents.
Model selection: Route most queries to a mid-tier model (cost ~$0.005–0.01 per turn). Reserve larger models for complex or long-form queries based on query classifier signals.
Streaming: Return tokens incrementally for better perceived latency. Use provider-side prompt caching for static system instructions.
Fallback: Circuit-breaker pattern with a secondary model or provider. If both fail, degrade to showing top FAQ links and a transfer button.
Hallucination Prevention
Multiple defense layers:
-
Pre-generation gate: If top reranked passage scores below a calibrated threshold or the query is classified as out-of-scope, skip generation entirely. Offer clarification or transfer instead.
-
Constrained generation: Low temperature, explicit citation requirement, allow "I don't know" responses.
-
Post-generation verification: Validate that all cited IDs appear in the context. Run a small NLI model or LLM-as-judge to check each sentence against its cited passages. If unsupported claims are detected, regenerate once or fall back to retrieval results only.
-
Confidence scoring: Combine retrieval quality, groundedness score, and behavioral signals (user frustration, repeated question, explicit request for human). Tune the escalation threshold using labeled feedback data.
Access Control and Safety
Document-level ACL: Tag documents with access_groups. At retrieval time, filter by the user's group membership from their session context.
PII redaction: Strip credit card numbers, SSNs, emails from user input before logging or passing to the model.
Injection defense: Classify inputs for jailbreak attempts. Structure prompts to clearly separate instructions from data.
Content policy: Post-filter generated responses for prohibited topics or toxic language.
Evaluation and Monitoring
Automated eval: Maintain a test set with golden document IDs and reference answers. Run nightly: retrieval recall@5, answer accuracy, escalation precision/recall, latency, cost per turn.
Live metrics: Track thumbs-up/down rate, transfer rate by query type, answer latency, retrieval score distributions, cache hit rate, model error rate.
Trace sampling: Log full request traces for a percentage of traffic to diagnose retrieval misses and prompt issues.
Feedback loop: Collect user ratings and comments. Mine transfer transcripts for coverage gaps. Use disagreement cases to expand the eval set.
Scaling and Reliability
Horizontal scaling: Stateless orchestrators behind a load balancer. Redis session store with replica sets. Vector and keyword indexes with read replicas.
Graceful degradation: If embeddings fail, fall back to keyword-only retrieval. If the LLM times out, show retrieved passages and a transfer option.
Rate limiting: Per-user and global QPS limits to prevent abuse and cost spikes.
Cost controls: Cap context length, cache aggressively, route to smaller models by default, set per-session turn limits.
At 30 QPS peak and 200k chunks, vertical scaling of individual components is sufficient. Sharding becomes relevant only at 10× scale or multi-tenant isolation requirements.
Common Mistakes
- Over-indexing on the LLM: Candidates often jump to model selection and ignore retrieval quality, which determines the ceiling for answer quality.
- Ignoring updates: How do you handle content changes mid-conversation? Versioning and atomic swaps prevent inconsistency.
- No refusal mechanism: A chatbot that always generates an answer will hallucinate. Confidence gating and escalation are non-negotiable.
- Weak evaluation: "We'll use BLEU" or "check logs manually" doesn't cut it. You need automated eval on a labeled test set with retrieval and end-to-end metrics.