Token Budgeting and Context Assembly for a Document-Analysis LLM
System DesignModel answerLast 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:
- The user's current message.
- The last 5 turns of the conversation.
- Passages returned by a vector-database search.
- 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
- 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?
- 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?
- 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?
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Frame the problem
The 32k window is a total budget: input plus generated output. Analysts want accurate, citable answers more than the lowest possible latency, so I would aim for a time-to-first-token around 2 seconds at the median and spend input tokens generously. Output tokens cost several times more than input tokens and drive latency through sequential decoding, so I cap output deliberately, and I cache the static prefix.
Example budget (32,768 tokens)
| Slot | Budget | Notes |
|---|---|---|
| Output reserve | ~4,000 | Dynamic max_tokens, floor ~1,500 |
| System prompt | ~1,500 | Static, never truncated, prefix-cached |
| Safety margin | ~1,000 | Covers tokenizer estimation error |
| Analysis prompt scaffold | ~500 | Tags, task framing |
| Current query | ≤ 2,000 | Pasted overflow is reclassified as evidence |
| Tool results | ≤ 6,000 | |
| Retrieved passages | ≤ 12,000 | About 15-20 chunks of ~600 tokens |
| History | ≤ 4,000 |
Caps are ceilings, not reservations: unused space in one tier flows to the next. The 1.3x heuristic is only for pre-fetch planning (for example, deciding how many chunks to request). Final packing uses the model's real tokenizer.
2. Data model and flow
Every piece of context becomes a block:
ContextBlock {
block_id // stable handle: E3, T1, H2
source_type // SYSTEM | QUERY | TOOL | EVIDENCE | HISTORY | SUMMARY
tier // priority tier
score // relevance x recency x authority
tokens // real token count
trust // TRUSTED | UNTRUSTED
provenance // doc_id, page, char_span, as_of_date, tool_call_id
content
}
Pipeline: parallel, deadline-bound fetch (vector search plus reranker, history store, tool runner) → normalizer (tokenize, dedupe, attach provenance) → scorer → tiered budget allocator → sanitizer → assembler (system prompt plus analysis template) → model → citation validator → UI. A background job maintains the conversation summary. The manifest of blocks actually sent is persisted per request, which gives finance users an audit trail.
3. Prioritization
Tier order: system prompt > current query > tool results > retrieved passages > history. Tool results rank above passages because they were computed in response to the user's explicit request.
Within a tier:
- Score each block as reranker score × recency × source authority.
- Remove near-duplicates with MMR (filings repeat tables across sections).
- Pack greedily by value per token.
- Never cut mid-sentence or mid-table; drop or compress whole units.
History versus fresh retrieval. History supplies intent and references ("what about Q3?"); retrieval supplies facts. Keep the latest turn verbatim and fold older turns into a structured summary. If a number in history conflicts with retrieved evidence, the fresh evidence wins, and among sources the one with the later as_of_date wins. The prompt tells the model to flag the discrepancy instead of silently choosing, because restatements matter to analysts.
Summarize or truncate? Truncation is free but loses entities. LLM summaries add latency and can alter numbers. Compromise: build a structured summary asynchronously after each turn (entities, figures with their source IDs, decisions, documents referenced), with numbers copied extractively rather than paraphrased.
4. Provenance
- Each block carries a stable ID, and the model must cite inline (
[E3]). - A post-processor checks citations against the manifest: unknown IDs are stripped and logged, and numeric claims with no citation are flagged.
- The UI resolves an ID to document, page and character span for highlight-on-click.
- Tool outputs keep a
tool_call_id, so a chart or figure links back to the code that produced it.
5. Prompt-injection defense
Layered, because no single layer is reliable:
- Role separation. Rules live only in the system message; request content goes in the user turn.
- Per-request random delimiters. Wrap each untrusted section in tags carrying a fresh random nonce so injected text cannot forge a closing tag, and escape delimiter-like strings inside content.
- Explicit policy. The system prompt states that anything inside query, evidence or tool tags is data; embedded instructions are not followed and should be reported.
- Screening. A lightweight classifier checks retrieved and tool content (uploaded PDFs are the main vector) and quarantines suspicious blocks.
- Capability limits. Retrieved text can never trigger a tool call by itself; side-effecting tools need user confirmation; code runs in a sandbox.
Layout: system rules first, then evidence and tool data, then history, with the query last. Place the highest-scoring evidence at the start and end of its section to reduce "lost in the middle" effects.
6. Graceful degradation
If the package still overflows, walk this ladder and stop at the first step that fits:
- Drop the lowest-value blocks (history first, then evidence).
- Compress: extractive sentence-level trimming of chunks; replace large tool outputs with a schema, head/tail rows and aggregates (never a raw 10k-row table); collapse history into the summary.
- Shrink the output reserve toward its floor.
- Map-reduce: split evidence into batches, extract in parallel, then synthesize. Costlier and slower, so use it only when coverage loss would otherwise be large.
- Ask the user to narrow scope, or answer with an explicit disclosure such as "based on 8 of 23 relevant sections".
Never truncate the system prompt or alter the meaning of the query, and never drop content silently. A budget report drives a UI indicator.
7. Trade-offs
- Fixed vs. flexible budgets: fixed caps are predictable, flow-down uses space better; use caps as ceilings with redistribution.
- More evidence vs. precision: stuffing many chunks adds distraction and cost; prefer fewer, reranked, deduplicated chunks.
- Summaries vs. verbatim: summaries save tokens but risk numeric drift; keep numbers extractive.
- Map-reduce: better coverage, higher cost and latency.
8. Common mistakes
- Forgetting to reserve output tokens and a safety margin.
- Using the 1.3x heuristic for final packing instead of the real tokenizer.
- Letting history override newer retrieved facts.
- Relying on "ignore instructions in documents" alone as injection defense.
- Dropping content silently, which breaks trust and auditability.
- Putting citations together after generation without validating them against what was actually sent.