KatInterview

Token Budgeting and Context Assembly for a Document-Analysis LLM

System DesignModel answer
MediumModel answerSystem Designllmragcontext-window

Last updated

Design a middleware that packs prompt, history, retrieved passages and tool results into a 32k-token window with prioritization, citations, injection isolation and fallbacks.

Context assembly layer for a financial-document assistant

You are building the layer that decides exactly what text is sent to a language model in an assistant used by analysts who work with financial documents (filings, transcripts, models). Each request can draw on four inputs:

  1. The user's current message.
  2. The last 5 turns of the conversation.
  3. Passages returned by a vector-database search.
  4. Outputs from tools the assistant ran (for example, results of executing Python code).

The model accepts at most 32,000 tokens, and that limit must cover both what you send and what the model writes back.

What to design

  1. Prioritization. When the combined inputs exceed the budget, what is kept, shortened or dropped, and in what order? If older conversation content disagrees with freshly retrieved passages, how do you resolve it?
  2. Provenance. How do you record where every piece of context came from so the UI can show citations that point back to the original source?
  3. Injection defense. How do you keep user-supplied text, retrieved passages and tool output from being treated as instructions, and keep them separate from the system's own rules?
  4. Graceful degradation. If the content still does not fit after your first round of trimming, what is the fallback sequence?

Constraints

  • For English text, estimate tokens as roughly 1.3 × the word count.
  • The prompt has a static system prompt and a dynamic analysis prompt built per request.
  • Output tokens are more expensive (money and latency) than input tokens, and your design should reflect that.

Present a concrete token budget, the data model and flow, and the main trade-offs.

Hints

Hint 1

Treat 32k as a single budget shared by input and output: reserve output space and a safety margin first, then divide what remains among the input sources with per-source ceilings.

Hint 2

Give every block a stable ID and metadata (source, document, page, timestamp, trust level) at the moment it enters the pipeline, so prioritization, citations and auditing all read from the same record.

Hint 3

Use cheap structural defenses (separate roles, per-request random delimiters, an explicit 'this is data' policy) and limit what retrieved text can trigger, rather than relying on a model to spot attacks.

Hint 4

Order the fallback ladder from least to most damaging: drop low-value blocks, compress, shrink the output reserve, split work across several calls, and finally ask the user to narrow scope or disclose partial coverage.