AlgoMaster Logo

Design a Q&A Assistant over Company Documents

High Priority24 min readUpdated October 18, 2026Asked atOpenAIAtlassian
Listen to this chapter
Unlock Audio

Most companies spread their knowledge across several tools. The onboarding guide might live in Confluence, the travel policy in a Google Drive PDF, and the fix for a recurring deployment error in an old Jira ticket. Even a simple question like "Which team owns the billing service?" might have its answer buried in a Slack thread. Finding that answer often means searching several places or asking a colleague.

In this chapter, we'll design an assistant that brings this information together. We'll start with the requirements and high-level architecture, then look closely at access control, incremental updates and deletes, retrieval quality, grounded answers, citations, and evaluation.

Let's begin by clarifying what the system needs to do.

Clarifying the Requirements

"Design a Q&A assistant over company documents" leaves several questions open. Which sources should it search? How quickly should changes appear? And how do we make sure employees only see information they're allowed to access?

Here's how that discussion might unfold in an interview:

These answers give us enough scope to define the functional and non-functional requirements.

Functional Requirements

  • Employees can ask questions in natural language and receive streamed answers.
  • Every factual claim about company information includes a citation linking to an original source.
  • Employees can ask follow-up questions that depend on earlier turns.
  • When the documents don't contain an answer, the assistant says so and shows the closest relevant documents.
  • Answers use only content the employee is authorized to access.
  • Employees can rate answers with a thumbs up or down.

Non-Functional Requirements

  • Permission correctness: Restricted content must not reach unauthorized users. This takes priority over answer quality, latency, and availability.
  • Freshness: Content edits appear within 15 minutes at p95. Permission revocations and deletions take effect within 5 minutes. A stale edit can produce a wrong answer, but a stale permission can expose restricted information.
  • Latency: Time to first token stays below 2 seconds at p95, with complete answers arriving in about 10 seconds.
  • Availability: The system targets 99.9% availability during business hours. If generation is unavailable, it returns search results.
  • Auditability: The system records who asked each question and which documents contributed to the answer, following the company's retention policy.

Actions such as filing tickets, image understanding beyond text extraction, and answering external customers are out of scope.

One requirement needs an explicit distinction. A 5-minute revocation target allows a short period when local permissions may be stale. If access must stop immediately after a source-side revocation, the design needs a current authorization check against that source.

Defining Success

Uptime and latency tell us whether the assistant is available and responsive. They don't tell us whether its answers are useful or correct. We therefore measure retrieval, answer quality, security, system performance, and product outcomes.

Scroll
CategoryMetricTarget
RetrievalRecall@10: the correct document appears in the top 10 resultsAt least 90% on the evaluation set
Answer qualityFaithfulness: the share of claims supported by cited sourcesAt least 95%
Answer qualityCorrect abstention on questions the documents cannot answerAt least 90%
SecurityRestricted content exposed to an unauthorized userZero observed leaks, checked through canary tests and audits
SystemTime to first token, freshness lag, cost per queryUnder 2 seconds at p95, within freshness targets, under $0.03
ProductHelpful ratings, citation clicks, reduction in helpdesk ticketsCompared with a baseline

Abstention needs to be measured in both directions. An assistant that says "I don't know" to questions it could answer may avoid unsupported claims, but employees will soon stop relying on it. The evaluation set should include both answerable and unanswerable questions so we can balance unnecessary refusals against unsupported answers.

Estimating the Scale

A few estimates help us identify which parts of the system need the most attention. We'll start with query traffic.

Twenty-five queries per second is a modest load for the API servers. The larger concern is the amount of model capacity those requests consume, which we'll estimate after sizing the corpus.

These are estimates for the underlying data. The deployed cluster also needs space for the keyword index, vector index structures, replicas, and operational headroom. Even so, this is a manageable workload for a small search cluster.

At an illustrative embedding price of $0.02 per million tokens, processing roughly 16.5 billion tokens, including overlap, costs about $330. If 2% of documents change each day, embedding the changed content costs only a few dollars per day. Parsing, OCR, storage, and connector operations add separate costs.

The initial backfill is more likely to be limited by source APIs than by embedding cost. SaaS tools throttle requests, and each document must be downloaded, parsed, and sometimes processed with OCR. At a sustained rate of 50 documents per second across all connectors, loading 10 million documents takes about 200,000 seconds, or 2.3 days. That backfill must not delay normal updates.

Now let's estimate generation cost.

Two points stand out. First, generation dominates the estimated cost, so avoiding unnecessary calls to the large model can produce meaningful savings. Second, the provider must support about 8.3 million input tokens per minute at peak, along with the output throughput and roughly 200 concurrent generations. We need to confirm that capacity before launch.

High-Level Design

The system has three main paths:

  • Ingestion collects documents and permissions, then keeps the search index current.
  • Query processing retrieves authorized content and generates an answer.
  • Feedback and evaluation capture traces and ratings so we can measure quality and investigate failures.

Ingestion runs continuously in the background. Query processing runs whenever an employee asks a question. The two paths share the search index and authorization data, so keeping those stores consistent is central to the design.

The Ingestion Path

Each source has a connector that can list documents, fetch content, read permissions, and detect changes. Connectors publish change events to a queue rather than processing documents directly. This lets change detection continue even when parsing slows down or the embedding service is unavailable.

Workers consume those events and process each document:

  1. Fetch and parse: Download the latest version and extract text, preserving useful structure such as headings, tables, and ticket fields.
  2. Resolve permissions: Translate the source's access rules into an effective authorization policy and store it in the ACL store.
  3. Chunk: Split the content into passages of a few hundred tokens, following the document's structure where possible.
  4. Embed: Generate a vector for each chunk.
  5. Index: Write the chunks, vectors, and metadata to the hybrid index. Metadata includes the document ID, source, URL, title, modification time, version, and permission information.

A separate identity service synchronizes users and groups from the company's identity provider, such as Okta or Microsoft Entra ID. It also tracks source-specific groups and memberships, including Confluence groups and Slack channels.

The Query Path

When an employee asks a question, the request follows these steps:

  1. The API gateway authenticates the employee through SSO and passes their identity to the orchestrator.
  2. The orchestrator gets the employee's principals from the identity service: their user ID, group memberships, nested groups, and organization-wide principals.
  3. For a follow-up question, a small model uses the conversation history to rewrite it as a standalone query.
  4. Keyword and vector search run in parallel, both filtered by the employee's permissions. Their results are then merged.
  5. A reranker scores the strongest candidates and selects up to eight passages.
  6. The orchestrator re-checks those passages against current authorization and document state.
  7. If the evidence is too weak, the assistant abstains. Otherwise, the model generates an answer grounded in the selected passages.
  8. The system checks citations, streams the response, and records the trace.

A planning budget for time to first token might look like this:

StepLatency budget
Authentication and cached principal lookup20 ms
Query rewrite for follow-ups300 ms
Hybrid retrieval with permission filtering100 ms
Rerank 50 candidates150 ms
Permission re-check on final candidates10 ms
LLM time to first token with about 5,500 input tokens800 ms
Total planned budgetAbout 1.4 seconds

This leaves some room under the 2-second target. These are planning estimates, and the actual p95 must be measured across complete requests rather than inferred by adding component percentiles.

Model generation takes the largest share of the budget, so the earlier stages need to remain fast. First-turn questions usually don't need rewriting, which saves about 300 ms on those requests. Any checks that hold generated text before display also need to fit within the user-visible latency budget.

We'll now examine the parts of this design that need the most care, starting with permissions.

Deep Dive 1: Access Control at Retrieval Time

Suppose an employee asks, "What's the plan for the reorganization next quarter?" A draft plan exists in a restricted HR folder. If that document enters the model's context, the model may summarize it for someone who should never have seen it.

A prompt instruction such as "Don't reveal restricted content" cannot enforce authorization. The system must prevent unauthorized content from entering the model's context in the first place.

There are three common approaches.

Approach 1: Filter After Retrieval

Retrieve the highest-ranked results without permission filters, then check each result against the source system and remove anything the employee cannot access.

This can use the source's current authorization decision, but it has two drawbacks. First, each query triggers several live API calls, adding latency and consuming source API quotas. Second, employees with limited access may lose most or all of the retrieved candidates. The top 50 results could all be restricted, even when useful documents exist farther down the ranking.

Approach 2: Use a Separate Index per User or Group

Build a dedicated index for each user or group, containing only the documents they can access.

This can provide strong isolation, but overlapping permissions make it difficult to maintain. A user may belong to many groups, and a shared document may need to appear in many indexes. Every content update then touches multiple copies, while permission changes require careful coordination across indexes.

Store permission metadata with each chunk during ingestion. At query time, resolve the employee's principals and apply an authorization filter to both keyword and vector search.

For documents governed by simple allow lists, a chunk is eligible when its allowed principals overlap with the employee's principals. More complex source rules may require additional policy checks.

Scroll
ApproachLatencyRecall for users with limited accessPermission freshnessOperational cost
Filter after retrievalHigh with live API checksCan be poorCurrent at the source checkHigh API usage
Index per user or groupLow for simple access patternsGood within covered indexesDepends on index updatesHigh duplication and update cost
Filter during searchLow with suitable index supportGood with filter-aware retrievalDepends on synchronizationModerate

Filtering during search is the best default for this system. Making it reliable requires several additional decisions.

Store group IDs instead of expanding them into user IDs

If a document is shared with group:eng-platform, store that group on its chunks rather than listing all 400 members. When an employee joins or leaves, the identity service updates their membership. The document's chunks don't need to change.

Resolve the employee's principals at query time

The identity service maintains a precomputed mapping from users to their principals, including nested groups, and caches it briefly. An employee in 300 groups produces a filter containing roughly 300 IDs. We should benchmark this with the chosen search engine, especially for users with unusually large group memberships.

Preserve the source's permission rules

Permissions may depend on a combination of space access, parent-page restrictions, project roles, and issue-level rules. A flat allow list works only when it preserves those semantics. Where access requires multiple conditions, the connector must retain those conditions or use an equivalent policy representation. This translation deserves dedicated tests because an overly broad rule can expose entire collections.

A file shared with "anyone in the company with the link" may be accessible to every employee, but its owner may expect it to be found only by people who receive the link. Making it searchable changes that expectation. A conservative default is to index it only for explicitly authorized users and groups unless the company approves broader discovery.

Test highly selective permission filters

Approximate nearest neighbor indexes such as HNSW search only part of a graph. If permission filters exclude nearly everything, some implementations may struggle to return enough relevant results efficiently. Search engines can address this with filter-aware traversal or exact search over a small allowed subset. Test the behavior for the most restricted users, not just typical employees.

Handling Permission Changes Between Index Updates

Permission metadata in the index can become stale. If Bob loses access at 10:00 but the index updates at 10:04, a query at 10:02 could still retrieve the document.

To reduce this window, permission changes use a priority path that updates the ACL store before the search index. After reranking, the orchestrator checks the final candidates against that store before including them in the prompt. Batched key-value lookups make this check inexpensive.

This protects against stale index metadata once the ACL store has received the change. It does not eliminate the delay between a source-side revocation and its detection. For sensitive sources that require immediate enforcement, verify the final candidates against the source API and accept the additional latency.

The system must also fail closed. If the identity service is unavailable and cached memberships have expired, it should reject the request rather than search without permission filters. The same principle applies when required authorization data is unavailable or too stale.

Preventing Leaks Outside Retrieval

Retrieval is only one place where restricted content can escape.

A shared response cache might return an answer built from documents another employee cannot access. Debugging traces may contain full prompts and retrieved passages. A "share this answer" link may expose content to a new viewer. Even conversation history can contain information whose permissions have since changed.

These paths need the same controls as retrieval: access-aware caching, permission checks when reusing history or sharing answers, and restricted trace access with appropriate redaction and retention.

Permissions and content both change over time. Next, we'll look at how the system keeps up with those changes.

Deep Dive 2: Incremental Sync and Deletes

A nightly full crawl is not enough for this workload. With 10 million documents and rate-limited source APIs, a complete crawl could take days. It also cannot meet a 15-minute content freshness target.

Instead, the system processes changes incrementally and uses periodic reconciliation to catch anything it missed.

Detecting Changes

Sources expose different change-detection mechanisms. A reliable connector combines the available mechanisms because each covers gaps in the others.

Scroll
MethodTypical latencyLimitationRole
WebhooksSecondsEvents may be duplicated or missedFast notification path
Incremental polling with a cursorMinutesSupport varies by API and resource typeRecover changes reliably
Full reconciliationDaily or weekly, often spread across partitionsExpensiveFind missed changes, especially deletes

A change cursor lets the connector resume from where it last stopped. For example, Google Drive exposes page tokens for its changes API, while Microsoft Graph supports delta queries for supported resources. Polling every few minutes helps recover changes that webhook processing missed.

Reconciliation compares the source's document inventory with the indexed inventory. If a document is confirmed to be gone or no longer accessible to the connector, it should be removed from retrieval. The process must distinguish that case from an incomplete listing or temporary API failure, which should not trigger mass deletion.

Processing a Change

All detection methods produce normalized jobs keyed by document ID. Processing a duplicate event should be harmless, and an older job must never overwrite a newer result.

Coalescing prevents repeated edits from creating unnecessary work. If a page is edited 20 times in ten minutes, the connector can combine nearby events into fewer jobs that fetch the latest version, while still meeting the freshness target.

Jobs are divided into three lanes:

  • Priority lane: Permission changes and deletes. These usually require authorization or metadata updates, not re-embedding.
  • Content lane: New documents and edits to existing content.
  • Backfill lane: The initial import of a newly connected source.

Without separate lanes, importing a SharePoint site with two million documents could push permission revocations to the back of the queue. Workers should reserve capacity and source API quota for priority work. Per-source rate limits and backoff prevent retries or backfills from overwhelming a connector's quota.

For content updates, the pipeline compares the extracted text's hash with the stored hash. If the text is unchanged, it skips embedding. If it has changed, the pipeline re-chunks the document and compares chunk hashes to reuse existing embeddings where possible. An edit may affect several chunk boundaries, but it should not automatically require re-embedding the entire document.

Ordering and Versioning

Events can arrive out of order, and workers may finish out of order too. A slow job for an older version must not replace a newer version already in the index.

Each update therefore carries a source version or another reliable revision identifier. The writer uses a conditional update to reject stale work. Partitioning the queue by document ID helps preserve order, but version checks are still needed for retries and concurrent processing.

For a content update, the writer first adds chunks tagged with the new version. Once those chunks are searchable, it marks that version as active in the document store. Old chunks are removed afterward.

During the transition, both versions may exist physically. Retrieval must validate candidates against the active document version, using an index filter or a document-state check, so old and new passages are not mixed in one answer.

Handling Deletes

A deleted document must stop contributing to answers promptly, even if physical cleanup takes longer.

  1. Tombstone immediately after detection: Mark the document as deleted in the document store. Retrieval and final candidate checks exclude tombstoned documents.
  2. Purge asynchronously: Remove its chunks from the keyword and vector indexes. Some indexes reclaim physical space later during compaction, and the tombstone prevents retrieval in the meantime.
  3. Clean up derived data: Invalidate cached answers that depend on the document. Apply the company's deletion and retention rules to traces, conversation logs, and other stored copies.

This gives us a current, permission-aware corpus. The next challenge is finding the passages that actually answer each question.

Deep Dive 3: Retrieval Quality

Many incorrect answers begin with a retrieval failure. If the right passage never reaches the model, the model may abstain or answer using information that sounds relevant but addresses a different question.

Company documents present two common retrieval challenges.

Internal vocabulary needs exact matching

Questions may contain ticket IDs such as PLAT-4521, error codes, product codenames, and team acronyms. Embeddings may not distinguish these identifiers reliably. Keyword search can match them directly.

Natural questions often use different wording from the documents

"Can I expense a home office chair?" should match a section titled "Remote Work Equipment Reimbursement." Vector search can recognize that relationship even when the wording differs.

This is why we use hybrid search. Keyword and vector searches run in parallel with the same permission constraints. Their results are combined using Reciprocal Rank Fusion (RRF), which assigns each chunk a score based on its position in each result list:

Here, L represents a result list, and k is a smoothing constant commonly set to 60. Because RRF uses ranks, the keyword and vector scores do not need to share a scale.

The cross-encoder reranker reads the question and each candidate passage together, then scores their relevance. Unlike a vector retriever that compares independently generated embeddings, it can evaluate detailed interactions between the question and passage. This is too expensive to run across the whole corpus, but practical for a small candidate set.

Reranking 50 candidates might add roughly 50 to 200 ms, depending on the model, hardware, and passage lengths. We validate that cost against the improvement in retrieval and answer quality.

Chunking determines what the reranker receives. A fixed token boundary can split a table or separate a heading from the paragraph it explains. Structure-aware chunking follows sections in wiki pages, meaningful fields in tickets, and conversational boundaries in Slack threads. Large sections or threads still need to be split to fit the chunk budget.

Each chunk should also include its title and section path. A prefix such as "Travel Policy > International Travel > Per Diem" gives the embedding model, reranker, and answer model context that an isolated paragraph may lack.

Finally, relevance alone does not establish which source to trust. "Travel Policy 2023" and "Travel Policy 2025" may both closely match a question about per diem rates. Ranking should consider whether a document is current, approved, archived, or deprecated, and whether it comes from an authoritative policy space or a personal note. Modification time helps, but it should not override an explicit effective date or approval status.

Good retrieval gives the model useful evidence. We still need to control how it uses that evidence.

Deep Dive 4: Grounded Answers, Citations, and "I Don't Know"

The model has a specific job: answer the employee's question using the supplied passages and cite the evidence for its claims. The prompt should state that clearly.

Each source includes a title, date, and useful status metadata. The application maintains the mapping from source IDs to URLs so citation links point to the actual retrieved documents.

Keeping the instruction prefix stable may also make it eligible for provider prompt caching, subject to the provider's minimum prefix length and cache behavior.

Abstaining Before Generation

Some questions can be rejected before calling the large model. If the strongest retrieved passages score below a calibrated relevance threshold, the assistant can respond with "I couldn't find this in the documents you have access to." It can then show up to three related documents, provided they are useful enough to display.

This avoids spending generation tokens when retrieval has found little evidence. We tune the threshold on the evaluation set, balancing correct abstentions against answerable questions that the gate wrongly rejects.

A relevance score is not proof that a passage contains the answer, however. A question about the 2026 bonus structure may retrieve a highly relevant 2025 bonus document. The model must still recognize when the supplied evidence is incomplete or out of date and abstain during generation.

Verifying Citations

A citation can point to a real source and still fail to support the claim. Verification therefore has two parts.

The structural check confirms that cited IDs appeared in the prompt and that factual statements include citations. Source-ID validation is deterministic. Detecting every factual statement is less exact, but sentence-level rules or a lightweight classifier can identify likely omissions.

The support check asks whether the cited passage actually supports the claim. A natural language inference model or an LLM judge compares the statement with its evidence. This can catch cases where the model cites an on-topic passage that does not justify what it says.

Checking every claim synchronously adds latency and cost. For high-risk content, such as HR or legal policies, the system can buffer completed sentences and check them before releasing them. Generation may continue while a sentence is checked, but unchecked claims should remain hidden if the goal is to prevent unsupported text from reaching the user.

For lower-risk answers, the system can run support checks asynchronously on a sample of responses. Those checks help measure quality and investigate failures, but they cannot prevent an unsupported claim that has already been displayed.

These controls evaluate individual answers. To understand whether the system improves over time, we also need a repeatable evaluation process.

Deep Dive 5: Evaluating Faithfulness

A change can reduce answer quality without causing an exception or increasing latency. A new chunking strategy might separate useful context. A prompt edit might encourage overconfident answers. A model upgrade might change citation behavior.

Evaluation helps us detect these regressions before they reach employees.

Building the Evaluation Set

Start with questions employees actually ask. Helpdesk tickets and channels such as #ask-it and #ask-hr often contain realistic questions and useful answers. Subject-matter experts can label the expected answer and the documents that support it.

A few hundred carefully labeled questions are enough for an initial evaluation set. Each case should record the relevant user permissions and source versions so the expected result is clear.

The set should deliberately include:

  • Unanswerable questions: Around 15% is a reasonable starting point for measuring abstention.
  • Follow-up questions: Cases that require earlier conversation turns to make sense.
  • Conflicting or outdated documents: For example, two versions of a policy with different effective dates.
  • Permission cases: The same question asked by users with different access, where the correct response may differ.

Evaluating Each Stage Separately

An end-to-end score tells us that quality changed. Stage-level metrics help explain why.

Scroll
SymptomStageMetricTypical fix
The correct document is never retrievedRetrievalRecall@k against labeled sourcesImprove chunking, hybrid retrieval, or query rewriting
The correct passage is retrieved but ranked too lowRerankingRecall@8 after rerankingImprove the reranker or ranking signals
The answer contradicts or goes beyond the sourcesGenerationFaithfulnessAdjust the prompt or use a stronger model
A cited passage does not support the claimGeneration and verificationCitation precisionImprove citation instructions or support checks
The assistant answers when it should abstain, or abstains unnecessarilyRelevance gate and generationAbstention and answerability metricsTune thresholds and generation instructions

To measure faithfulness, an LLM judge splits an answer into individual claims and checks each against the cited evidence. The score is the fraction of claims supported by those sources.

The judge also needs evaluation. Have humans label a few hundred claims, compare their judgments with the model's, and inspect disagreements. Automated scores are useful only when we understand where the judge is reliable and where it makes mistakes.

Testing for Permission Leaks

Authorization has a clear expected outcome for each test user and document. We can use that to build automated checks.

Create canary documents in each source, each containing a unique random string and accessible only to a dedicated test group. Then issue queries as users outside that group, both in CI and on a production schedule.

If a canary appears in unauthorized retrieved content, model context, or answers, treat it as a high-severity incident. Tests should also cover restricted titles and snippets, inherited permissions, group membership changes, revocations, cached responses, and shared conversations.

Canaries help detect real failures, but passing them does not prove that every permission rule is correct. They complement connector tests, authorization audits, and monitoring.

Using Online Signals

After deployment, ratings and user behavior help identify problems that the offline set missed.

A thumbs-down rating or an immediate rephrasing of the same question may indicate a poor answer. Citation clicks can show whether employees inspect the evidence, though a lack of clicks does not necessarily mean an answer was unhelpful.

A daily sample of traces goes through automated judging and targeted human review. Confirmed failures are added to the evaluation set so future releases are tested against them.

Embedding-model changes need particular care. Vectors from different models generally do not share a compatible space, so changing models requires re-embedding the corpus. Build the new index alongside the old one, compare them using offline evaluations and shadow traffic, and switch only after the new index meets the quality, latency, and security requirements.

Scale, Cost, and Failure Handling

With the main design decisions covered, we can return to the estimates and consider how the system behaves in production.

Scaling

The API servers and orchestrator are stateless, so they can scale horizontally. The search cluster holds roughly 33 million chunks, distributed across enough shards to fit its memory and storage requirements. Replicas provide availability and additional query capacity.

At the estimated query volume, index memory, permission-filter behavior, and failover capacity may matter more than raw QPS. Load tests should include users with restrictive permissions and queries with large candidate sets.

Ingestion workers scale separately based on queue depth and freshness lag. A large backfill can add processing capacity without changing the query path, although worker scaling remains limited by source API and embedding quotas.

Reducing Cost

At roughly $150,000 per month in the illustrative estimate, generation is the largest expense. The main opportunities are:

  • Abstain early: Skip the large model when retrieval does not provide useful evidence.
  • Route by difficulty: Send straightforward lookups, such as an enrollment deadline, to a smaller model. Use a stronger model for questions that require combining several sources. Validate routing decisions on the evaluation set.
  • Reuse eligible prompt prefixes: Keep stable instructions at the beginning of the prompt and measure the savings from provider caching.
  • Use focused context: Eight well-selected chunks may answer a question as well as twenty loosely relevant ones. Confirm that reducing context preserves answer quality.
  • Cache answers with authorization checks: A simple starting policy is to cache only answers derived from company-wide documents, tracking their versions and current permissions. Restricted answers can also be cached, but every reuse must validate access to all contributing sources and account for relevant conversation context.

Caching needs invalidation for content updates, deletions, and permission changes. A correct answer can become unsafe to reuse even when its wording has not changed.

Handling Failures

FailureResponse
LLM provider outage or rate limitingFail over to a previously evaluated secondary model. If none is available, return authorized search results.
Vector index unavailableFall back to keyword-only retrieval, retaining all permission checks.
Identity service unavailableUse cached principals only while they remain valid under the authorization policy, then fail closed.
ACL store unavailable or authorization data too staleReject affected requests or exclude affected content rather than bypassing checks.
Connector blocked or failingAlert operators and track source freshness. Label stale content where safe, and exclude it when permission freshness exceeds the allowed window.
Embedding service unavailableQueue content updates while continuing permission and deletion processing, which does not require embeddings.

Summary

A company docs Q&A assistant uses RAG, but most of the design work happens around the model. Here is how the design handles each of the main requirements:

RequirementHow the design addresses it
Prevent permission leaksFilter by the user's permissions during the search itself, recheck current ACLs, and apply the same rules to caches and chat history
Keep answers freshPick up changes through webhooks and cursor-based polling, reconcile periodically, and process revocations and deletes first
Retrieve relevant evidenceChunk documents along their structure, combine keyword and vector search, and rerank the results with a cross-encoder
Answer only from evidenceSkip generation when the retrieved passages are not relevant enough, and check that each citation supports the claim it is attached to
Measure qualityEvaluate retrieval, generation, and permission handling separately, using calibrated automated judges, human review, and production feedback

Cost follows from the same choices. Abstaining early, routing simpler questions to cheaper models, and caching answers only where permissions allow it keep the cost per question down.

Quiz

Design a Q&A Assistant over Company Documents Quiz

20 quizzes