---
title: Retrieval-augmented assistant over internal documents
url: https://gurkanozkan.ai/learn/design/mle-retrieval-augmented-assistant-over-internal-documents-14/
markdown: https://gurkanozkan.ai/learn/design/mle-retrieval-augmented-assistant-over-internal-documents-14.md
kind: design
role: ML engineering
json: https://gurkanozkan.ai/api/learn/design/mle-retrieval-augmented-assistant-over-internal-documents-14.json
---

# Retrieval-augmented assistant over internal documents

Build an assistant that answers analysts' questions using internal research notes and filings, with citations and access controls.

## Constraints

- 50M document chunks
- 5k daily users
- p95 answer latency under 6 s
- documents updated hourly
- strict entitlements per user

## What to cover

- **Requirements**: Build an assistant that answers analysts' questions using internal research notes and filings, with citations and access controls.
- **Estimates**: 50M document chunks; 5k daily users; p95 answer latency under 6 s; documents updated hourly; strict entitlements per user.
- **API**
- **Data model**
- **Architecture**: Ingestion with chunking and metadata; hybrid retrieval (BM25 + embeddings); permission filtering at retrieval time.; Reranker; prompt assembly with citations; LLM generation with answer-grounding checks.; Caching; feedback capture; an evaluation harness (golden Q&A set, LLM-as-judge with human calibration).; Observability (traces, token cost).
- **Deep dives**
- **Trade-offs**: chunk size vs context; retrieval recall vs latency and cost; hosted vs self-served models; abstaining vs answering; freshness of the index.
- **Evaluation**: Offline: retrieval recall@k on labelled queries, faithfulness/groundedness, citation accuracy, answer correctness on a golden set.; Online: thumbs-up rate, escalations, time saved.; Guardrails: entitlement-leak tests, hallucination rate.

## Reference design

### Requirements

**Functional**: analysts ask questions in natural language ("What did our analysts say about UK utilities' capex guidance this quarter?") and get concise answers with citations to the exact passages in internal research notes and company filings; follow-up questions; filters by company, date, document type and author; the assistant says when the documents do not answer the question.

**Non-functional**
- p95 answer latency < 6 s for a complete answer (streamed, first tokens much sooner).
- Documents updated hourly; new research notes searchable within an hour of publication.
- Strict entitlements: each user sees only documents they are entitled to (research desks, licensed content, information barriers between private and public sides). A leak is a compliance incident, not a quality issue.
- Auditability: who asked what, which documents were used.

**Assumptions to confirm**: 50M chunks; 5k daily users at ~20 questions each; English first; entitlements available from an internal service as groups and document tags; model hosting options include self-hosted open-weight models and an approved hosted provider.


### Estimates

- **Traffic**: 5k users × 20 questions = **100k questions/day**; over a ~12-hour global working day ≈ 2.3 QPS average, **~10 QPS peak** (market open, earnings days).
- **Vector index**: 50M × 1,024 dims × 1 byte (int8) ≈ 51 GB, ~80 GB with the HNSW graph — a few replicated shards. BM25 over 50M × 400 tokens = 20B tokens ≈ 150 GB.
- **Hourly updates**: if ~1% of chunks change per day → 500k/day ≈ 21k chunks/hour × 400 tokens ≈ 8.4M tokens/hour to embed — minutes on one GPU.
- **Generation**: 12 chunks × 400 + 1k system/history ≈ 6k input, ~300 output tokens. 100k × 6k = 600M input + 30M output tokens/day. Hosted at an assumed $3/M in, $15/M out: $1.8k + $0.45k ≈ **$2.3k/day ≈ 2 cents per question**. Self-hosted 70B: ~10 QPS × ~5 s ≈ 50 concurrent sequences → ~4 TP-2 replicas ≈ 8 GPUs ≈ $500/day plus operations — cheaper at scale and keeps sensitive text in-house.
- **Latency budget (p95 6 s)**: entitlement resolution 50 ms, query rewrite 250 ms, hybrid retrieval 200 ms, rerank 300 ms, prompt assembly 50 ms → ~0.9 s; LLM first token 0.8 s; 300 tokens at ~100 tokens/s ≈ 3 s; grounding check overlapped, ~0.5 s at the end → **~5.2 s**, which forces concise answers and a fast model.


### API

```
POST /v1/ask   (SSE)
  {conversation_id?, question, filters: {tickers: ["SSE LN"], doc_types: ["research_note", "10-K"],
   from: "2026-07-01"}}
  → events: token {text} · citation {n, doc_id, title, author, published_at, page, passage}
           · final {answer, citations[], grounded: true, abstained: false, trace_id}

POST /v1/feedback {trace_id, rating: "up"|"down", reason: "wrong"|"missing_source"|"outdated"|
                   "not_entitled_content", comment}
GET  /v1/documents/{doc_id}?highlight=passage_id    (entitlement re-checked on open)
Ingestion: document events {doc_id, version, entitlement_tags, content_uri} from the publishing
           system and filings feed
```
User identity comes from SSO; entitlements are resolved server-side, never passed by the client.


### Data model

- **Document**: doc_id, type (research note, filing, transcript), source, company/tickers, author/desk, published_at, version, entitlement tags, retention class.
- **Chunk**: chunk_id, doc_id, text, section path (e.g. "Risk factors > Liquidity"), page, table flag, position, embedding, entitlement tags (denormalised), published_at.
- **EntitlementMap**: user → groups → allowed tags; cached with a short TTL and versioned; information-barrier rules as deny tags.
- **Conversation / Turn**: question, rewritten query, retrieved and cited chunk ids, answer, model version.
- **Trace**: per stage latency, token counts and cost, retrieval scores, grounding verdicts; stored under the same entitlement controls as the documents it quotes.
- **Feedback** and **GoldenItem** (question, expected documents/passages, reference answer, answerable flag, entitlement profile of the test user).


### Architecture

```
Publishing system / filings feed ─► Ingestion: parse (PDF tables, sections),
   chunk with metadata (company, section, page), entitlement tags ─► embed
   ─► Hybrid index (BM25 + vectors, entitlement tags as filter fields), hourly
      incremental updates; deletions and re-tagging propagate immediately
User ─SSO─► Assistant API
   1. resolve entitlements (cached ≤ 5 min, versioned)
   2. query rewrite: standalone question, ticker/company normalisation, filters
   3. hybrid retrieval WITH entitlement filter (top 100) ─► fusion
   4. cross-encoder rerank ─► top 10–12
   5. prompt assembly with numbered passages ─► LLM generation, cite [n]
   6. grounding check: each sentence entailed by its cited passage; else
      remove sentence or abstain
   ─► stream to user · caches keyed by (query, entitlement version)
Evaluation harness (golden set, LLM judge calibrated by humans) · feedback store
Observability: traces per request, token cost, latency per stage, leak tests
```


### Deep dives

**Entitlements at retrieval time.** Filtering after generation is too late — the model has already seen restricted text. Entitlement tags live on every chunk and the index applies the user's allowed tags inside the retrieval query; very restrictive users who can see few documents fall back to exact search to preserve recall. Caches key on entitlement version, and the final cited set is re-checked before display. Re-tagging a document (for instance when it moves behind an information barrier) updates the index immediately, without re-embedding.

**Financial documents are awkward.** Filings are long, repetitive and full of tables; chunk by section with headings carried into each chunk, keep tables intact with captions, and record page numbers so citations land precisely. Normalise tickers and company names so "SSE" and "SSE plc" retrieve the same filings.

**Abstention.** If reranker scores are low or the grounding check removes most sentences, say the documents do not answer the question and show the closest sources, rather than guessing.


### Trade-offs

- **Chunk size vs context**: small chunks retrieve precisely but lose surrounding context; large chunks keep context but dilute relevance. ~300–500 tokens with section headings, plus neighbour expansion at answer time.
- **Retrieval recall vs latency and cost**: retrieving 100 and reranking to 12 costs ~300 ms; retrieving fewer is faster but misses evidence. Tune on recall@k against the latency budget.
- **Hosted vs self-served models**: hosted models are stronger and need no GPU operations but send sensitive text outside and cost per token; self-served open-weight models keep data in-house and are cheaper at steady volume but need serving expertise. With material non-public information in scope, self-hosting (or a dedicated private deployment) is likely required.
- **Abstaining vs answering**: analysts dislike "I don't know", but a confident wrong figure is worse; tune the threshold per question type and show sources either way.
- **Freshness of the index**: hourly incremental updates meet the requirement; a near-real-time path for breaking research notes costs more ingestion complexity.


### Evaluation

- **Offline retrieval**: recall@k (k = 20, 100) on labelled queries with known relevant passages, by document type and query type.
- **Offline generation**: faithfulness/groundedness (claims entailed by cited passages), citation accuracy, answer correctness on a golden set built with analysts; LLM-as-judge for scale, calibrated against human ratings (agreement checked each release).
- **Guardrails**: entitlement-leak tests — synthetic users with known entitlements probing restricted documents, through every cache — must find zero leaks before release; hallucination rate on unanswerable questions.
- **Online**: thumbs-up rate, escalations to human research support, citation clicks, time saved (survey and task studies), abstention rate.
- **Monitoring**: per-stage latency against the budget, token cost per answer, ingestion lag, grounding-check failure rate, entitlement cache staleness.


## What a strong design shows

- Enforces entitlements inside retrieval, re-checks before display and keys caches by entitlement version.
- Builds a hybrid retrieval, rerank and grounded-generation pipeline sized to a 6 s p95 budget with explicit arithmetic.
- Handles financial documents properly: section-aware chunking, tables, page-level citations, ticker normalisation.
- Evaluates retrieval and generation separately, calibrates the LLM judge with humans, and runs entitlement-leak tests as a release gate.
- Makes a reasoned hosted vs self-hosted choice given cost and data sensitivity.

---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
