Building a Cited Question-Answering Service Over Text, PDFs and Images
System DesignModel answerLast updated
Design an enterprise assistant that retrieves evidence from text, PDFs and images, then generates answers with citations while respecting access controls, latency and cost limits.
Problem
Your company wants an internal assistant that answers employees' natural-language questions using the company's own knowledge base. Every answer must be backed by evidence the user can inspect.
The knowledge base contains several kinds of content:
- Text documents, such as wiki pages and support tickets.
- PDFs that mix prose, tables and embedded figures.
- Standalone images, such as architecture diagrams and screenshots, which have little or no descriptive metadata.
The assistant must find relevant evidence across these formats, hand it to an LLM, and return an answer that cites its sources.
What to cover
- How each content type is ingested and preprocessed.
- The indexing approach (dense, keyword or hybrid) and how metadata is stored.
- Query-time retrieval, including how a text question can surface an image.
- Chunking, embedding choices and re-ranking.
- Prompting, grounding and how citations are produced and validated.
- Evaluation (offline and online), latency and cost.
- Failure modes (fabricated claims, outdated content, a modality that cannot be parsed) and how you would mitigate them.
State your assumptions about scale, latency targets and security up front. Use rough numbers where they help justify a decision.
Hints
Hint 1
Give every chunk, whatever its modality, a text surrogate (raw text, a table as markdown, or caption plus OCR for an image). That lets one text query search everything, and you can add a true image-embedding index on top for cases where captions miss detail.
Hint 2
Use a staged retrieval funnel: parallel dense, keyword and visual candidate generation, merge with rank fusion, then a cross-encoder re-ranker to keep only a handful of items. Apply access-control filters inside the search, not afterward.
Hint 3
Treat grounding as a pipeline, not just a prompt: label each evidence item with an ID, require the model to cite those IDs, discard citations that do not map to provided evidence, verify claims against sources, and refuse to answer when retrieval confidence is low.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Assumptions and sizing
- About 50k users, peak ~50 QPS, average ~5 QPS.
- Corpus: ~5M text docs, ~1M PDFs (~20 pages each), ~3M standalone images. About 1% daily churn.
- Targets: p95 time to first token under 2 s, full answer under 6 s, edits searchable within ~15 minutes.
- Correctness: every factual claim is cited, and "not found" is preferred over guessing.
- Security: document-level ACLs are enforced. A user must never see evidence they cannot open. I would raise this first, because it is the most damaging failure in an internal system.
Rough sizing: ~80M text chunks plus ~13M visual entries (standalone images and PDF figures/pages). At 1024 dims in fp16 (~2 KB per vector) that is roughly 190 GB raw, or ~50 GB with PQ/int8 compression. This fits comfortably in a sharded ANN cluster.
2. Data model
- Document:
doc_id, source, url, title, acl_groups[], version, updated_at, content_hash. - Chunk:
chunk_id, doc_id, modality (text | table | image | page), text_repr, page_no, bbox, section_path, parent_chunk_id, acl_groups[], updated_at.
The key idea is text_repr, a text surrogate for every modality. It is raw text, a table rendered as markdown, or an image's caption plus OCR output. It makes retrieval, re-ranking, prompting and citation uniform. Raw blobs live in object storage, metadata in a relational or document store, and ACL and filter fields are replicated into the vector and keyword indexes.
3. Ingestion by modality
- Text: parse HTML or markdown, strip boilerplate, keep heading hierarchy. Chunk by section at ~300-500 tokens with ~15% overlap, and prepend title and section path to each chunk. Keep tickets' title, description and resolution together.
- PDFs: run a layout model to split text blocks, tables and figures with bounding boxes. Text goes down the text path. Tables become markdown or JSON chunks with their captions. Figures are cropped and treated as images, with caption and nearby paragraph as context. Also render each page as an image for page-level visual retrieval, which rescues scanned or badly parsed pages.
- Images: OCR (screenshots are mostly text), a VLM-generated dense caption, and an image embedding from a CLIP/SigLIP-style model. OCR plus caption becomes
text_repr. - Pipeline: event-driven (webhooks or change-data-capture), queue-based workers, and a
content_hashcheck to skip unchanged documents. VLM captioning is the expensive step (roughly $0.001-0.005 per image), so batch it on GPUs and cache by hash.
4. Indexing
Three indexes, queried together:
- Text dense index over
text_reprfor all chunks, including captions and OCR. - Visual index of image embeddings sharing a space with query text, giving true text-to-image retrieval when captions miss details.
- Sparse/BM25 index for error codes, ticket IDs and product names, where dense vectors are weak.
Use HNSW or IVF-PQ, sharded by doc hash. Apply ACL and metadata filters as pre-filters inside the ANN search. Post-filtering can return nothing for users with narrow access.
5. Query-time retrieval
- Query understanding: an LLM rewrites the query using conversation history, extracts filters (product, date range), and optionally splits into sub-queries. Skip for simple queries to save latency.
- Candidate generation in parallel: top ~50 dense, ~50 BM25, ~20 visual. Merge with Reciprocal Rank Fusion, which avoids calibrating scores across indexes.
- Re-ranking: a cross-encoder scores
(query, text_repr)for ~100 candidates. For visual candidates with weak surrogates, a small VLM scores(query, image). Keep the top 8-10. - Context assembly: expand small chunks to their parent section, deduplicate near-identical chunks, enforce diversity across documents, and pass the best images to a multimodal LLM alongside their captions.
- Re-check ACLs against the source of truth before generation, as defense in depth against a stale index.
Approximate latency to first token: rewrite 150 ms, retrieval 100 ms, re-rank 150 ms, LLM first token ~800 ms, for roughly 1.2 s total.
6. Grounding and citations
- Label each evidence item, for example
[S3] (wiki: "Deploy guide", section 2.1)or[S5] (image, page 4 of X.pdf). - Instruct the model to answer only from sources, cite
[S#]after each claim, say "not found in the knowledge base" when evidence is insufficient, and describe what an image shows without over-inferring. - Post-process: parse IDs, map them to URL, page and bbox, and drop any ID that was not supplied. The UI shows a snippet or a thumbnail with the region highlighted.
- Verification: an NLI model or cheap LLM checks that each cited sentence is entailed by its source. Flag or remove unsupported sentences. Run asynchronously, or only for high-stakes domains, if latency is tight.
- Confidence gate: if the top re-rank score is under a threshold, return "I couldn't find this" with the closest documents instead of generating.
7. Evaluation
Offline
- A golden set of ~1-2k questions from real logs and expert-written items, deliberately including image-only answers, table lookups, multi-hop questions and unanswerable ones.
- Retrieval metrics: recall@k, MRR, nDCG, broken down by modality.
- Generation metrics: faithfulness (claims supported by cited evidence), citation precision and recall, answer correctness via LLM-as-judge calibrated against human labels, and abstention accuracy on unanswerable questions.
- Run this as a regression suite on every change to the chunker, embedder or prompt.
Online
- Thumbs up/down, flagged citations, reformulation rate, click-through on citations, and escalation to human support.
- A/B test changes, and sample low-rated answers for review.
8. Cost and latency levers
- Cache embeddings and captions by content hash, and cache answers for frequent queries (scoped by ACL).
- Route simple queries to a smaller model and skip the rewrite step.
- Quantize vectors and limit re-rank depth.
- Most cost sits in ingestion VLM calls (one-time per image) and in generation tokens at query time.
9. Failure modes and mitigations
| Failure | Mitigation |
|---|---|
| Hallucinated claims | Strict grounding prompt, citation validation, NLI verification, abstention gate |
| Stale data | Event-driven re-indexing, version and timestamp metadata, prefer recent sources, show "last updated" |
| Permission leak | Pre-filtered ACLs plus a source-of-truth re-check, and never cache across ACL scopes |
| Modality missing or unparseable (scanned PDF, text-free diagram) | Page-render visual index, VLM captioning, and a visible "could not read this file" signal |
| Exact-token queries missed | BM25 in the hybrid mix |
| Conflicting sources | Surface both with dates and let the answer state the conflict |
| Prompt injection inside documents | Treat retrieved text as data, strip instructions, and restrict tool access |
Common mistakes
- Post-filtering by ACL instead of pre-filtering.
- Relying only on dense retrieval and losing IDs and error codes.
- Embedding images with no text surrogate, which breaks citations and re-ranking.
- Having no abstention path, so the model always answers.
- Skipping evaluation by modality, which hides weak image retrieval behind good text numbers.