RAG Service for Cited Q&A Over Long Regulatory Filings
Machine LearningModel answerLast updated
Design a retrieval-augmented assistant that answers multi-document questions over long regulatory filings with paragraph-level citations, streaming, and hallucination guards.
Answer questions across a large corpus of long regulatory filings, with every claim cited
A product team wants a chat assistant for analysts working with dense, highly structured corporate disclosures (annual reports, quarterly reports, registration statements, material-event filings). A user types a natural-language question and gets back a written answer where every factual claim is linked to the exact passage it came from — the specific filing, section, page, and character range — so the analyst can click through and verify in seconds.
Functional requirements
- Cross-document synthesis. Questions like "How did the risk disclosures of Company A and Company B change between FY2022 and FY2023?" must be answered by combining evidence from several filings.
- Citation fidelity. Each sentence of the output must be traceable to a specific passage (page/paragraph). Claims with no supporting passage must be dropped or explicitly marked as unsupported.
- Agentic routing. The system must decide per query whether a single retrieval pass suffices or whether it needs a multi-step, iterative search plan before answering.
- Refusal behavior. When the evidence isn't in the corpus, the system says so rather than inventing an answer.
Non-functional requirements
- Scale. Index on the order of millions of pages, growing by thousands of new filings per day, with the index catching up within roughly an hour.
- Latency. Simple lookups should start streaming tokens within ~2 seconds; long analytical jobs may run for minutes but must show progress and partial results.
- Reliability. Enforce a strict "answer only from retrieved context" constraint and validate citations before release.
Deliverables
- High-level architecture: ingestion pipeline, retrieval mechanism, and agent orchestration flow.
- A data model for parsed documents, section structure, chunks, and citation metadata/embeddings.
- A latency strategy for long-running analysis that doesn't tie up or time out the user-facing request.
- Discussion of the precision-vs-recall trade-off when domain jargon and abbreviations are common, and how you'd tune retrieval for it.
Hints
Hint 1
Pin down the citation contract (filing id, section code, page, character offsets) first and design every stage backward from it — if a chunk can't be cited, it can't be used as evidence.
Hint 2
Structure is your biggest precision lever: filings are organized into labeled sections (risk factors, MD&A, financial statements), so resolve tickers/years/section codes into hard metadata filters before touching the vector index.
Hint 3
Decouple the job from the HTTP request: return a job id immediately, run retrieval/generation on a durable queue, and stream plan → per-document progress → tokens → citations over a reconnecting event stream.
Hint 4
Combine dense embeddings with a sparse keyword index (BM25/SPLADE) because exact tokens like accounting-standard codes and segment names must match literally; then re-rank with a cross-encoder.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing: it's a citation system first, a chatbot second
The interviewers care most about the citation contract. If the product claims "every sentence is backed by a passage," then the failure that destroys trust is a confident sentence citing a passage that doesn't actually support it. So I design backward from: given the final answer, can I prove each claim maps to exact spans of source text? Everything else — chunking, retrieval, orchestration — serves that.
Clarify first (state assumptions explicitly):
- Corpus: ~10k public companies, 20 years of annual/quarterly/event filings ≈ 10M pages. At ~4 chunks/page (~300–500 tokens each) ≈ 40M chunks. With 1024-dim int8 vectors that's ~40 GB of vectors + ~200 GB text/metadata — trivially shardable.
- Ingest: a few thousand filings/day, spiky around earnings season; <1h freshness is fine (batch, not real-time).
- Latency: quick Q&A first token <2s, full answer <10s; multi-document analysis can take minutes but must stream progress.
- Accuracy: ≥98% of citations must actually entail their claim; when evidence is absent, say "not found in the filings."
1. API and job model
POST /v1/queries {query, filters?: {tickers, form_types, fiscal_years}, mode?: auto|quick|deep}
-> {query_id}
GET /v1/queries/{id}/stream (SSE) events: plan | progress | token | citation | done | error
GET /v1/citations/{chunk_id} -> {filing_url, page, bbox, text_span}
Returning a query_id and streaming over SSE (with Last-Event-ID reconnect) decouples long work from the HTTP connection — this is the core of the latency deliverable.
2. Data model
A hierarchy Filing → Section → Chunk, with citation metadata carried on the chunk:
Filing: filing_id (accession no.), cik, ticker, company_name, form_type,
fiscal_year, fiscal_period, filed_date, source_url, sic_code
Section: section_id, filing_id, item_code ("1A","7","7A"), title,
page_start, page_end, summary_text, summary_embedding
Chunk: chunk_id, section_id, filing_id, text, page_number, paragraph_idx,
char_start, char_end, bbox (PDF highlight), is_table, table_json?,
embedding, sparse_terms, denormalized: ticker, form_type, fiscal_year, item_code
Storage: object store for raw/parsed documents; Postgres for filings and sections; a sharded vector index that holds embeddings plus the denormalized filter fields so metadata filtering happens inside ANN search; a separate BM25 index for lexical matching. Tables are stored both as linearized text (for embedding) and structured JSON (so numeric questions can be answered by computation, not by the LLM reading digits).
3. Ingestion pipeline (offline, queue-driven)
- Poll the filing source, dedupe on accession number.
- Parse HTML/XBRL into a layout-aware tree; detect section boundaries with rules + a small classifier (Item 1A, Item 7, etc.).
- Chunk within section boundaries along paragraphs with modest overlap; keep tables as single chunks. Record page, paragraph index, character offsets.
- Enrich: prepend contextual headers before embedding ("AAPL 10-K FY2023, Item 1A Risk Factors: …") so chunks aren't context-free; generate section summaries.
- Embed with a finance-tuned model, build sparse terms, upsert.
4. Retrieval (hierarchical)
- Metadata resolution — an LLM/NER step parses tickers, years, form types, section codes into hard filters. Biggest single precision win.
- Section level — search section-summary embeddings within filters, keep top sections.
- Chunk level — hybrid dense + BM25, merged via reciprocal rank fusion, restricted to chosen sections.
- Re-rank — cross-encoder narrows ~100 candidates to ~15; add diversity (MMR, ≥k chunks per company) so comparisons are balanced.
5. Agent orchestration
A router chooses a path:
- Direct: one fact, one pass, cited answer.
- Multi-hop: iterative search (e.g., "did guidance change after the CFO left?") where each step's output seeds the next query.
- Map-reduce/analytical: planner splits into per-filing subtasks ("extract FY2023 risk factors for A"); workers run in parallel returning structured findings + chunk IDs; a reducer synthesizes only from cited extracts.
The generator sees a numbered context [c_8812]. The prompt requires each sentence to end with chunk-ID citations and to emit an exact refusal string when evidence is missing. A verifier runs before each paragraph streams: every cited ID must be in context; an NLI/entailment check of claim-vs-chunk; exact-match checks on numbers. Unsupported sentences are rewritten or dropped.
6. Latency mitigation
- Async jobs on a durable workflow engine (retries, resumable) with SSE streaming.
- Progressive streaming: emit the plan, then per-document progress, then each map result as it finishes (so the user sees Company A's table while B runs), then the reduce answer token by token.
- Parallelism + caching: bounded concurrency per provider; cache per-(filing, extraction-template) results reused across users; precompute section summaries at ingest.
- Model tiering: small models for routing, metadata extraction, map extraction; large model reserved for synthesis. Cap documents per job and per-worker timeouts; on partial failure return partial results naming what's missing.
7. Precision vs. recall under jargon
Dense-only retrieval struggles: synonyms ("net interest margin" ≈ "spread income"), false friendliness ("goodwill impairment" vs. "goodwill"), and exact tokens (accounting-standard codes, CET1, segment names). Approach: recall-first then precision — hybrid retrieval for recall, metadata filters + cross-encoder re-rank for precision; maintain a synonym/abbreviation lexicon built from filings themselves; evaluate with a labeled set tracking citation-entailment rate and recall@k separately.
Common mistakes: answering from model memory instead of context; treating citation as a post-hoc URL lookup rather than chunk provenance captured at parse time; running long jobs synchronously; and optimizing answer fluency while ignoring entailment checks, which is exactly where trust breaks.