Context-Window Budgeting Middleware for Financial RAG

Medium · ML System Design · Machine Learning Engineer · Onsite

Prompt

Architect a context-assembly middleware service for an enterprise financial-research assistant built on retrieval-augmented generation (RAG). On each turn, the service gathers candidate text from four streams:

  1. The analyst's active query
  2. A sliding window of the latest 5 conversation turns
  3. Document passages fetched from a vector index
  4. Outputs returned by external tools (such as a Python execution sandbox)

The downstream language model enforces a strict 32k-token window. Your middleware must pack and format the prompt so answers stay fast, accurate, and verifiable while honoring these operational rules:

  • Tokenization & prompt structure: Plan around an average English prose expansion factor of 1.3 tokens per word, always include both a fixed System Prompt and a per-request Analysis Prompt, and explicitly account for the differing dollar and latency costs of input versus output tokens.
  • Budgeting & conflict handling: Establish how sources are ranked or trimmed whenever total tokens exceed 32k, and specify how discrepancies between earlier conversation turns and freshly retrieved filings are reconciled.
  • Citation provenance: Maintain end-to-end lineage from every packed context segment back to its underlying filing or tool run so the client UI can render clickable citations.
  • Untrusted-content isolation: Prevent prompt-injection payloads inside user text, filings, or tool logs from overriding privileged instructions.
  • Overflow degradation: Define multi-stage fallback behavior when essential context remains over budget even after initial trimming.

Scope & Expectations

  • Token accounting & packing policy: Break down the 32k window across fixed instructions, reserved generation space, and competing dynamic sources without starving critical context.
  • Provenance & security boundaries: Show the API/data structures that preserve citation lineage and encapsulate untrusted text against injection attacks while keeping prefix caching intact.
  • Multi-turn consistency & overflow fallbacks: Explain how multi-turn memory reconciles stale claims against newer primary evidence, and walk through concrete degradation tiers for oversized queries or multi-document syntheses.
  • Evaluation & production resilience: Outline how you measure context-selection quality separately from retrieval quality and keep middleware latency predictable under component failures.

Step-by-step walkthrough

  1. Clarify requirements, constraints, and ML framing

    In an enterprise RAG (Retrieval-Augmented Generation, a pattern where an AI model answers questions using retrieved external documents rather than relying on memory alone) application for financial analysts, our middleware sits right between the application's agent loop and the LLM (Large Language Model). On every turn it receives four competing candidate streams—the analyst's active query, a 5-turn sliding dialogue window, vector-indexed filing passages (retrieved from a vector database, a search engine that indexes text by numeric meaning vectors called embeddings), and Python sandbox execution results—and must assemble one safe, verifiable prompt inside a strict 32k-token context window (the total number of text pieces, or tokens, the model can read and write in a single call).

    Functional requirements

    • Assemble each request with a static System Prompt, a dynamic Analysis Prompt, the current user query, Python tool outputs, retrieved document snippets, and conversation history.
    • Guarantee prompt_tokens + max_output_tokens <= 32,768 (treating 32k as 32 * 1,024 = 32,768; if a provider defines 32k as 32,000, only one registry constant changes).
    • Prioritize inputs when candidates exceed the window, and resolve conflicts when older conversation turns contradict fresh search results.
    • Preserve provenance (exact origin tracking: document ID, page, character offsets, or tool call ID) so every figure in the UI links to its source.
    • Defend against prompt injection (malicious or accidental instructions hidden inside PDFs, tool printouts, or user pastes) by isolating system instructions, user text, and external evidence.
    • Degrade gracefully in explicit stages when inputs still overflow after standard truncation.

    Non-functional requirements and assumptions

    • Financial accuracy first: Analysts make investment decisions from these numbers; an invented or uncited figure is much worse than saying "data not in context."
    • Low middleware overhead: Context assembly must take ≤ 250 ms at p95 before the LLM call begins (excluding external Python tool runtime).
    • Zero context-overflow errors at the LLM gateway.
    • Tokenizer discipline: We use the constraint's 1.3 tokens per English word ratio for capacity planning and pre-fetch estimates, but run the target model's exact local tokenizer before sending, because financial tables, stock tickers, and decimals often expand to 2–3× more tokens per word than prose.
    • ML problem framing: Context packing is a budgeted subset-selection problem: each candidate item i has an exact token cost c_i and an estimated utility u_i (its probability of being needed for a complete, accurately cited answer). Version 0 ranks items using rules plus a neural reranker; Version 1 learns u_i from logged analyst citations.
  2. Back-of-the-envelope token, cost, and latency math

    Let us convert words into tokens (at 1.3 tokens/word for prose), check input vs. output economics, and size our token budget.

    Typical item sizes (prose at 1.3 tokens/word)
      1 retrieved filing chunk       400 words x 1.3 = ~520 tokens
      20 reranked chunks             20 x 520 = 10,400 tokens
      1 conversation turn            (60 user words + 600 assistant words) x 1.3 = ~860 tokens
      5 conversation turns           5 x 860 = ~4,300 tokens
      Full SEC 10-K annual report    60,000 words x 1.3 = 78,000 tokens (~2.4 windows -> never sent whole)
      200-row Python stdout table    ~60 tokens/row (digits + pipes tokenize densely) = ~12,000 tokens
    
    Token budget inside a 32,768-token context window
      Component                        Typical    Hard Cap   Guaranteed Floor          Rule
      ----------------------------------------------------------------------------------------------------
      1. Static System Prompt            1,500      1,500    1,500 (never cut)         Byte-identical prefix
      2. Dynamic Analysis Prompt           400        800      800 (never cut)         Task metadata + rules
      3. Current User Query + Constraints  100      4,000    All (<= 4,000)            Pastes > 4k become docs
      4. Output Reserve (max_tokens)     3,000      6,000    By task: lookup 1,000,    Must reserve upfront!
                                                             analysis 3,000, report 6,000
      5. Formatting & XML tag margin       500        500      500                     Chat roles + delimiters
      6. Python Tool Outputs             2,000      8,000    Newest view (<= 2,500)    Compressed table view
      7. Retrieved Evidence             10,400     16,000    Top 6 chunks (~3,120)     Whole chunks only
      8. Conversation History            4,300      5,000    Previous turn (<= 1,500)  2 verbatim + summary
    
    Budget invariant checks
      Worst-case fixed reservation (analysis task): 1,500 + 800 + 4,000 + 3,000 + 500 = 9,800 tokens
        -> Leaves 32,768 - 9,800 = 22,968 tokens for flexible sources (19,968 if 6,000 report reserve)
      Sum of worst-case flexible floors: 2,500 + 3,120 + 1,500 = 7,120 tokens -> Always fits (< 19,968)!
      Sum of flexible caps: 8,000 + 16,000 + 5,000 = 29,000 tokens (> 22,968 intentionally so priority
        decides who trims when all three sources are simultaneously large)
    
    Input vs. output token cost & latency (illustrative enterprise API rates: $2.50/1M in, $10.00/1M out)
      Typical request: 18,700 input tokens + 800 generated output tokens
      Input cost:      18,700 x $2.50 / 1,000,000 = $0.0468 (~85% of the dollar bill!)
      Output cost:        800 x $10.00 / 1,000,000 = $0.0080 (~15% of the dollar bill)
      Daily spend (2,000 analysts x 50 turns/day = 100k turns/day, ~10.4 req/s at 3x peak):
        ~$4,680/day input + ~$800/day output = ~$5,480/day (~12M input tokens/minute at peak)
      Wall-clock time:
        Prefill (reading 18,700 input tokens in parallel on GPU):  ~1.0 s
        Decode (generating 800 output tokens one by one at 60/s): ~13.3 s (~93% of total wait!)
    

    This math reveals a crucial asymmetry between cost and latency:

    • Input tokens drive ~85% of dollar cost even though each output token is 4× pricier, because prompts are ~23× longer than answers (18,700 vs. 800). Stuffing unused room up to 32k wastes ~$2,500/day and dilutes model attention.
    • Output tokens drive ~93% of wall-clock latency, and max_output_tokens directly steals room from input evidence. Sizing max_output_tokens dynamically by task (1,000 for quick lookups vs. 3,000 for analysis) frees 2,000 extra evidence tokens on lookups, while pushing math into Python keeps outputs short and fast.
  3. API and provenance data model

    The orchestrator calls our stateless middleware before every LLM invocation to build the bounded prompt, then calls a second endpoint after generation to resolve short citation tags into clickable UI highlights.

    POST /v1/context:build
    {
      "session_id": "sess_83c",
      "turn_id": 6,
      "model": "fin-llm-32k",
      "task_type": "analysis",          // "lookup" (1k out) | "analysis" (3k out) | "report" (6k out)
      "query": { "text": "How did Helios operating margin change in FY2025 vs FY2024, and why?" },
      "tool_outputs": [ { "tool_call_id": "py_7", "artifact_id": "art_94", "status": "ok" } ],
      "retrieval": { "top_k": 50, "filters": { "tickers": ["HLIO"], "doc_types": ["10-K", "10-Q"] } },
      "deadline_ms": 250
    }
    
    -> 200 OK
    {
      "messages": [ ... ],              // [system, developer (analysis), user]
      "max_output_tokens": 3000,
      "prompt_tokens": 18712,
      "degradation_level": 0,           // 0: normal, 1: extractive compress, 2: map-reduce, 3: narrow scope
      "manifest_id": "man_9d4",
      "dropped": [ { "item_id": "E19", "reason": "source_cap", "tokens": 520 } ],
      "warnings": []
    }
    
    POST /v1/citations:resolve
    { "manifest_id": "man_9d4", "answer_text": "Operating margin rose 180 bps to 28.4% [E4], driven by ... [T1]" }
    -> 200 OK
    {
      "citations": [
        { "marker": "E4", "doc_id": "helios-10k-fy25", "page": 53, "char_start": 1200, "char_end": 1730 }
      ],
      "invalid_markers": [],
      "unsupported_numbers": []
    }
    

    Core data structures

    ContextItem (in-memory candidate during packing)
      item_id          Short session-stable marker: "E4" (evidence), "T1" (tool), "H4" (history)
      source           "system" | "analysis" | "query" | "tool" | "evidence" | "history"
      trust_tier       "system_trusted" | "user_input" | "external_untrusted"
      text, tokens     Exact token count under target model's tokenizer
      score            Relevance probability for evidence; recency weight for tool & history
      origin           Evidence: {doc_id, chunk_id, page, char_start, char_end, as_of_date}
                       Tool:     {tool_call_id, artifact_id, code_sha256, input_evidence_ids}
    
    ContextManifest (persisted 90 days for financial compliance audit, ~5 KB/turn = ~500 MB/day)
      manifest_id, session_id, turn_id, model, prompt_tokens, degradation_level,
      items: [{item_id, source, origin, tokens, kept_or_dropped, drop_reason}]
    
    SessionState (Redis with 24h TTL + durable DB audit log)
      session_id, last_5_turns, running_summary (<= 500 tokens),
      user_constraints (e.g. ["use fiscal years", "exclude discontinued Asia unit"]),
      evidence_ledger  Map chunk_id -> stable "E#" id + {first_turn, last_cited_turn}
    

    Two data-model choices eliminate whole classes of bugs:

    1. Short opaque IDs (E4, T1) instead of URLs or filenames: The LLM never sees raw URLs, so it cannot hallucinate plausible-looking broken links. Server-side resolution against ContextManifest guarantees every rendered UI badge corresponds to a real chunk actually shown in that prompt.
    2. Precomputed chunk token counts + session-stable E# IDs: Document chunks are tokenized once at index time, cutting runtime tokenization to milliseconds, and evidence_ledger ensures chunk helios-10k-p53 keeps the exact ID E4 from Turn 1 through Turn 10.
  4. End-to-end context middleware architecture

    Analyst UI  <================ Streamed tokens + resolved citation links ================+
        | Question                                                                          |
        v                                                                                   |
    [ Agent Orchestrator ] --- Python code ---> [ Network-Isolated Sandbox ]                |
        |                                              | Full stdout/tables                 |
        | POST /v1/context:build (250 ms budget)       v                                    |
        v                                       [ Object Artifact Store ]                   |
    [ Stateless Context Middleware ]                   |                                    |
      1. Load SessionState (5 ms)    <--- [ Redis ]    |                                    |
      2. Vector search top-50 (50 ms)<--- [ Vector DB + metadata filters ]                  |
      3. Neural rerank (100 ms)      <--- [ Cross-Encoder GPU Service ]                     |
      4. Build compact Tool Views    <-----------------+                                    |
      5. Exact token count + Two-pass Pack  <--- [ Model Registry: window, tokenizer, cost ]|
      6. Render random-boundary XML  ---> [ Manifest Store ]                                |
        |                                                                                   |
        v                                                                                   |
    [ LLM Gateway (Prefix Cache enabled) ] ---> [ Citation Resolver & Number Verifier ] ----+
        |
        +---> (Async post-turn worker): Update running_summary & extract user_constraints
    

    Keeping the middleware stateless, running history summarization asynchronously after each turn finishes, and running session fetch + vector retrieval in parallel keeps context assembly around ~165 ms typical (well inside our 250 ms p95 budget).

  5. Context prioritization with floors and caps

    When candidates exceed our ~23k–27k flexible token budget, we follow the domain hierarchy:

    Fixed Prompts > Active Query > Sandbox Tool Views > Filing Passages > Prior Dialogue

    Why this exact order? System and Analysis instructions define safety and citation rules; Current Query defines the user's immediate task; Tool Results were just computed in Python for this specific question and cost seconds to rerun; Retrieved Evidence contains primary SEC filing text needed for citations; and Conversation History mostly consists of the model's own past prose, whose essential constraints and cited sources are already preserved in user_constraints and evidence_ledger.

    However, pure strict priority has a fatal flaw: a single 12,000-token Python dataframe printout would starve Retrieved Evidence, or 35 relevant filing chunks would wipe out 100% of Conversation History so a follow-up like "What about the prior year?" loses its referent! We solve this with a two-pass floor-and-cap packer:

    • Before packing: Python stdout is summarized into a structured table view (column headers, first 20 rows, last 5 rows, row count, and artifact pointer); retrieved chunks are kept whole (never sliced mid-sentence, which could detach "not" from "profitable"), deduplicated by character span, and capped at 8,000 tokens per single filing on multi-document queries so one giant 10-K cannot crowd out another.
    • Pass 1 (Guaranteed Floors): Reserve the highest-scoring minimum items for each source (1 newest tool view ≤ 2,500 tokens, top 6 evidence chunks ≈ 3,120 tokens, 1 immediately preceding turn ≤ 1,500 tokens).
    • Pass 2 (Priority Fill to Caps): Fill remaining budget in priority order (tool up to 8,000, evidence up to 16,000, history up to 5,000).
    from dataclasses import dataclass
    
    PRIORITY_ORDER = ["tool", "evidence", "history"]
    
    
    @dataclass
    class CandidateItem:
        item_id: str
        source: str     # "tool", "evidence", or "history"
        tokens: int
        score: float    # higher = more important (relevance for evidence, recency for tool/history)
    
    
    def pack_context(
        candidates: list,
        flexible_budget: int,
        floor_counts: dict,
        source_caps: dict,
    ) -> tuple:
        """Two-pass greedy packer enforcing both guaranteed floors and per-source token caps."""
        # Group candidates by source and sort highest-utility items first within each group.
        grouped = {src: [] for src in PRIORITY_ORDER}
        for item in candidates:
            grouped[item.source].append(item)
        for src in PRIORITY_ORDER:
            grouped[src].sort(key=lambda x: x.score, reverse=True)
    
        chosen = []
        chosen_ids = set()
        used_by_source = {src: 0 for src in PRIORITY_ORDER}
        tokens_left = flexible_budget
    
        # Pass 1: secure minimum floor items per source so no single source starves the others.
        for src in PRIORITY_ORDER:
            for item in grouped[src][: floor_counts[src]]:
                fits_cap = used_by_source[src] + item.tokens <= source_caps[src]
                if fits_cap and item.tokens <= tokens_left:
                    chosen.append(item)
                    chosen_ids.add(item.item_id)
                    used_by_source[src] += item.tokens
                    tokens_left -= item.tokens
    
        # Pass 2: fill remaining budget in strict priority order up to each source's token cap.
        for src in PRIORITY_ORDER:
            for item in grouped[src]:
                if item.item_id in chosen_ids:
                    continue
                fits_cap = used_by_source[src] + item.tokens <= source_caps[src]
                if fits_cap and item.tokens <= tokens_left:
                    chosen.append(item)
                    chosen_ids.add(item.item_id)
                    used_by_source[src] += item.tokens
                    tokens_left -= item.tokens
    
        dropped = [item for item in candidates if item.item_id not in chosen_ids]
        return chosen, dropped
    
    
    def table_view(lines: list, head: int = 20, tail: int = 5) -> list:
        """Keep table header, first `head` rows, and last `tail` rows with an explicit omission note."""
        if not lines:
            return []
        header = lines[0]
        rows = lines[1:]
        if len(rows) <= head + tail:
            return lines
        omitted = len(rows) - head - tail
        note = f"... [{omitted} of {len(rows)} rows omitted; run Python aggregation on full artifact] ..."
        return [header] + rows[:head] + [note] + rows[-tail:]
    
  6. Resolving conflicts between history and fresh evidence

    Conversation history mixes two very different kinds of information—analyst instructions vs. prior factual claims—and treating them identically causes subtle financial errors:

    1. Analyst constraints win over defaults: Standing user rules ("use fiscal years, not calendar years", "report margins in basis points") are extracted into user_constraints after each turn and pinned right beside the current query so Turn 1 instructions survive even after Turn 1 rolls off the 5-turn window.
    2. Fresh primary evidence always beats old assistant answers: An earlier assistant turn is a derived summary, never a primary source. If Turn 6 retrieves an amended 10-K/A or Q4 restatement that contradicts a figure stated in Turn 2, we keep the fresh chunk and pull Turn 2's cited chunk from evidence_ledger so the model sees both primary filings with their as_of dates. Our Analysis Prompt instructs the model to prefer the newest as_of filing and explicitly note the restatement rather than silently changing its story.
    3. Topic switches shrink history: When the new query introduces a company ticker or fiscal period absent from recent turns, we drop older history down to the 1-turn floor so fresh evidence gets maximum room.

    Structured async condensation vs. dropping older turns

    Strategy                 Added Cost & Latency         Strength                     Financial Risk
    ----------------------------------------------------------------------------------------------------------
    Simple truncation        Zero cost, zero latency      100% verbatim accuracy       Loses Turn 1–3 context
    Semantic summarization   Small-LLM call (~300 tokens  Preserves multi-turn goals   Can paraphrase or
                             async *after* each turn)     in <= 500 tokens             hallucinate numbers!
    

    We combine the best of both: the last 2 turns stay verbatim, while turns 3–5 are condensed into a ≤ 500-token structured summary computed asynchronously after each turn completes (zero added latency on the next turn!). To eliminate the risk of altered financial figures, the summarizer records entities, decisions, and [E#] IDs, and a deterministic validator checks that every number in the summary appeared verbatim in the source turns—falling back to simple truncation if validation fails:

    import re
    
    CITATION_MARKER = re.compile(r"\[[ET]\d+\]")
    NUMERIC_TOKEN = re.compile(r"\d[\d,]*(?:\.\d+)?")
    
    
    def extract_numbers(text: str) -> set:
        """Extract normalized numbers after stripping [E4]/[T1] citation markers."""
        cleaned = CITATION_MARKER.sub("", text)
        return {match.replace(",", "") for match in NUMERIC_TOKEN.findall(cleaned)}
    
    
    def summary_is_faithful(summary: str, source_turns: list) -> bool:
        """Verify the summary never invents or alters numeric figures from the turns it condenses."""
        allowed_numbers = set()
        for turn_text in source_turns:
            allowed_numbers |= extract_numbers(turn_text)
        return extract_numbers(summary).issubset(allowed_numbers)
    
  7. Prompt layout, provenance citations, and injection defense

    How we order and wrap the selected items affects latency, model accuracy, and security.

    Message 1 [role: system]     STATIC SYSTEM PROMPT (100% byte-identical across all requests)
                                 -> Enables LLM prefix caching; defines citation & untrusted-data rules.
    
    Message 2 [role: developer]  DYNAMIC ANALYSIS PROMPT (built strictly from server-side enums/IDs)
                                 -> Task type, today's date, valid item IDs [E1..E18, T1], conflict rules.
                                 -> Contains ZERO raw user text or document text!
    
    Message 3 [role: user]       ENCAPSULATED DATA + USER INPUT (random per-request hex boundary `7c4e91a2`)
                                 <history_7c4e91a2> ... summary + last 2 turns ... </history_7c4e91a2>
                                 <evidence_7c4e91a2 id="E4" doc="Helios 10-K FY25" page="53" as_of="2026-02-18">
                                 Operating margin increased to 28.4% in FY2025 from 26.6% in FY2024...
                                 </evidence_7c4e91a2>
                                 <tool_output_7c4e91a2 id="T1" call="py_7" rows="25 of 412">
                                 ... compact table view ...
                                 </tool_output_7c4e91a2>
                                 <user_constraints_7c4e91a2>Use fiscal years.</user_constraints_7c4e91a2>
                                 <user_query_7c4e91a2>
                                 How did Helios operating margin change in FY2025 vs FY2024, and why?
                                 </user_query_7c4e91a2>
    

    Why this exact layout works:

    • Prefix caching saves money and prefill latency: Modern LLM gateways reuse the GPU KV cache (precomputed attention tensors) for any byte-identical prompt prefix. Keeping timestamps and dynamic IDs out of Message 1 guarantees the 1,500-token System Prompt is cached on every call.
    • Defeating "lost in the middle": LLMs attend strongest to tokens at the very start and very end of long contexts. Putting system rules first, grouping evidence chunks cleanly by document and page order in the middle, and placing <user_query> at the very end maximizes recall right as generation begins.

    Five-layer defense in depth against prompt injection

    1. Strict role separation: Only system and developer messages hold authoritative instructions, and developer is formatted exclusively from server-controlled enums and dates—never interpolated with user prompts or document titles.
    2. Randomized XML delimiters: Static tags like <evidence> fail the moment a malicious PDF includes </evidence><system>Ignore prior rules. Appending a fresh 64-bit random hex token (<evidence_7c4e91a2>) per request and stripping that token from untrusted content makes tag-closing forgery impossible, while keeping <user_query_...> and <evidence_...> cleanly separated from each other.
    3. Index-time sanitization: Document ingestion strips invisible PDF text (0-pt font, white-on-white text, zero-width Unicode tag characters) and flags instruction-like phrases ("ignore previous instructions") so suspicious chunks get down-ranked and labeled untrusted_flag="true".
    4. Least-privilege tool & UI execution: Even if a clever injection tricks the LLM, the Python sandbox has zero outbound internet access and no write/email tools, and the UI renders zero external Markdown links or images—only server-verified [E#] / [T#] badges. Data exfiltration via hidden image URLs is impossible.
    5. Post-generation number & citation verification: Every [E#] marker is checked against ContextManifest, and numbers absent from cited evidence or tool outputs are flagged as unsupported_numbers in the UI.
    import secrets
    
    
    def make_boundary() -> str:
        """Generate an unguessable 16-hex-character (64-bit) per-request delimiter suffix."""
        return secrets.token_hex(8)
    
    
    def sanitize_attr(value: object) -> str:
        """Strip characters that could break out of an XML attribute string."""
        text = str(value)
        for ch in ('"', "<", ">", "\n", "\r"):
            text = text.replace(ch, " ")
        return text
    
    
    def wrap_block(kind: str, boundary: str, attrs: dict, content: str) -> str:
        """Encapsulate user or external text inside an unforgeable per-request XML tag."""
        tag = f"{kind}_{boundary}"
        # Loop removal so crafted substrings cannot reassemble the secret boundary after one pass.
        while boundary in content:
            content = content.replace(boundary, "")
        attr_str = " ".join(f'{k}="{sanitize_attr(v)}"' for k, v in attrs.items())
        open_tag = f"<{tag} {attr_str}>" if attr_str else f"<{tag}>"
        return f"{open_tag}\n{content}\n</{tag}>"
    
  8. Multi-stage graceful degradation when truncation is not enough

    Sometimes standard truncation is still not enough—for instance, an analyst pastes a 45,000-token earnings call directly into the chat box, or asks "Compare liquidity risks across all 8 semiconductor 10-Ks" (~50,000 tokens of high-relevance chunks). Rather than failing or silently dropping half the companies, we step through four explicit degradation levels:

    • Pre-step for giant user pastes (> 4,000 tokens): Split the short question line from the pasted body, ingest the paste as an ephemeral session document (~1 s to chunk and embed), and retrieve from it with normal [E#] citations.
    • Level 0 (Normal single-pass): Everything high-scoring fits inside our 32k budget.
    • Level 1 (Extractive sentence compression): Triggered when dropped evidence chunks with high relevance (score >= 0.5) exceed 2,000 tokens. Instead of using an LLM to rewrite chunks (which adds latency and risks rounding or altering financial numbers!), we run extractive compression: keeping only sentences inside each chunk that contain numbers, query entities, or high query cosine similarity, shrinking chunks ~40–50% while preserving exact verbatim wording and character offsets. History simultaneously drops to summary-only.
    • Level 2 (Parallel Map-Reduce across evidence batches): Triggered on broad multi-filing syntheses where relevant compressed evidence still overflows. We split chunks in document order into ≤ 12,000-token Map batches, run a fast/cheap model in parallel on each batch to extract ≤ 800 tokens of verbatim-cited facts ([E#]), and pass the combined notes (~3,200 tokens) plus the top 10 raw chunks (~5,200 tokens) to the primary Reduce model. Map-reduce costs ~3.5× normal input tokens and adds ~12–18 s (streamed with progress updates like "Analyzing filing batch 3 of 4..."), while keeping every [E#] citation verifiable against the union manifest.
    • Level 3 (Transparent scope narrowing): If Map-Reduce would exceed safety caps (> 8 batches / > 120k tokens), the system states exactly which filings it covered and asks the analyst whether to narrow scope or launch an asynchronous background report—never pretending a partial sample covered everything.
    def make_map_batches(chunks: list, batch_token_limit: int = 12000) -> list:
        """Group ordered evidence chunks into bounded token batches for parallel Map calls."""
        batches = []
        current_batch = []
        current_tokens = 0
    
        for chunk in chunks:
            if current_batch and current_tokens + chunk.tokens > batch_token_limit:
                batches.append(current_batch)
                current_batch = []
                current_tokens = 0
            current_batch.append(chunk)
            current_tokens += chunk.tokens
    
        if current_batch:
            batches.append(current_batch)
        return batches
    
  9. Learning context selection: labels, features, and offline metrics

    Once Version 0 (rules + cross-encoder reranker) is live, we improve item scoring u_i as a supervised ML task:

    • Labels: (1) An offline golden benchmark of ~500 analyst-authored multi-turn financial questions with human-marked gold chunks and verified numeric answers; (2) logged online citations, treating chunks cited in thumbs-up/exported answers as positives. Because uncited dropped chunks are never observed by the LLM, we add 2% exploration (injecting 2 randomly chosen dropped chunks inside the cap) and apply IPW (Inverse Propensity Weighting) so our learned selector discovers helpful chunk types that Version 0 ranked too low.
    • Candidate features & selector model: Gradient-boosted decision trees (GBDT, sub-millisecond CPU inference for 50 chunks) scoring u_i / tokens_i (utility per token!) from cross-encoder score, vector similarity, exact ticker and fiscal-period match, table/numeric density, evidence_ledger prior-citation count, same-document redundancy count, and injection-risk score.
    • Diagnostic offline metrics: Separating Retrieval Recall@50 (did search find the gold chunk?) from Context Recall (did our packer keep the gold chunk?) isolates middleware losses from vector-DB losses. On the output side, we measure exact-tolerance numeric accuracy, citation precision & coverage, unsupported-number rate, red-team prompt-injection attack success rate, and cost / TTFT curves across budget sweeps (8k, 16k, 24k, 29k).
  10. Serving resilience, monitoring, and online A/B testing

    Graceful component failures

    Component Failure Impact Fallback Behavior
    Vector DB timeout (> 150 ms) Fresh search unavailable Pack from evidence_ledger, tool outputs, and history; show UI banner "Document search degraded"
    Cross-encoder GPU slow Rerank scores late Fall back to raw vector-search similarity order at the 150 ms deadline
    Async summary not ready yet Turns 3–5 uncondensed Include last 2 verbatim turns + prior turn's summary
    LLM unexpected length error Tokenizer drift bug Retry once immediately with flexible budget cut by 10% and page on-call
    Primary 32k LLM outage Generation fails Route to backup model in registry; re-run pack_context with backup model's tokenizer and window

    Production monitoring & A/B test. Dashboards track degradation-level shares (L0–L3), high-score dropped evidence tokens (score >= 0.5), invalid_markers and unsupported_numbers rates, TTFT (Time to First Token) at p50/p95, and cost per accepted answer. When testing a new context-packing model online, we randomize by analyst ID (1,000 treatment vs. 1,000 control analysts for ≥ 2 weeks, stratified by financial desk so multi-turn sessions never mix policies), using accepted-answer rate (thumbs-up, copy, or spreadsheet export without a follow-up correction turn) as the primary metric and p95 TTFT, cost per query, and unsupported-number rate as strict guardrails.

Intuition & how it works

Think of managing a 32k-token context window (the fixed text buffer an AI model can read and write in one call) like packing a single carry-on suitcase for a high-stakes financial briefing. First, you must leave empty space at the top of the suitcase for the briefing memo you plan to write (max_output_tokens), because input and output share the exact same 32,768-token limit. Next, your passport and assignment sheet—the static System Prompt, dynamic Analysis Prompt, and Current User Query—go in unconditionally. For the three bulky piles competing for the remaining room (Python tool results, retrieved SEC filing snippets, and conversation history), you first pack a small survival kit (floors) from each pile so you never show up with zero evidence or zero memory of the previous sentence, then fill the remaining room in priority order up to per-source caps. Finally, every filing snippet gets a short numbered sticky note ([E4]) for citations, and untrusted text is sealed inside tamper-proof folders (<evidence_7c4e91a2>) so a deceptive footnote cannot impersonate instructions from your boss.

A naive middleware that simply concatenates every input and chops off whatever overflows 32,000 tokens fails in four ways. First, forgetting to reserve max_output_tokens upfront leaves the model unable to finish its answer, and estimating length via words * 1.3 crashes on financial tables where digits and punctuation consume 2–3× more tokens per word than prose. Second, pure priority without floors/caps lets one 12,000-token Python printout crowd out all citable SEC filings. Third, mixing past assistant answers with fresh search snippets lets an old hallucination or superseded quarter override an amended filing, while plain <evidence> tags let an attacker write </evidence> inside a PDF to hijack the prompt.

Let us trace a single analyst turn asking "How did Helios's operating margin change in FY2025 vs. FY2024?":

  1. Reserve fixed slots: Static System Prompt (1,500 tokens) + dynamic Analysis Prompt (400) + Query & standing user constraints (150) + analysis max_output_tokens (3,000) + XML tag margin (500) = 5,550 tokens reserved, leaving 32,768 - 5,550 = 27,218 flexible tokens.
  2. Prepare candidates: A 300-row Python operating-margin script output is condensed into a 25-row table_view (T1, 1,800 tokens); vector search + neural reranking return 35 SEC 10-K chunks (520 tokens each = 18,200 tokens); history offers the last 2 verbatim turns (860 each) plus an async ≤ 500-token summary of turns 1–3 (420 tokens).
  3. Two-pass pack: Pass 1 locks in the floors (T1 = 1,800, top 6 chunks = 3,120, previous turn = 860). Pass 2 adds 24 more chunks until evidence hits its 16,000-token cap (30 chunks = 15,600 tokens, dropping the 5 lowest-relevance chunks rather than paying for noisy filler) and adds the remaining history (1,280). Total prompt = 24,230 tokens—well under 32,768.
  4. Wrap, generate, and verify: Each block is wrapped in a random per-request XML tag (<evidence_7c4e91a2 id="E4">), the LLM streams "Operating margin rose 180 bps to 28.4% [E4], matching segment math [T1]", and the server-side resolver maps [E4] to Helios 10-K FY2025, p. 53 while confirming 28.4 and 180 exist in the cited blocks.

Key trade-offs

  • Strict priority vs. two-pass floors and caps. Pure strict priority (System > Query > Tool > Evidence > History) is simple, but lets one oversized Python table wipe out every citable filing snippet or lets abundant evidence erase the previous turn needed to understand "What about last year?". Adding small guaranteed floors (1 tool view, 6 chunks, 1 prior turn) and per-source caps (8k / 16k / 5k) requires tuning three cap numbers, but prevents source starvation and stops low-relevance chunks from inflating prefill cost by 50%.
  • Hybrid async summarization vs. pure truncation of history. Dropping turns older than 2 is free and never alters numbers, but forgets Turn 1 goals; summarizing everything inline adds LLM latency and risks paraphrasing $14.2M into $14M. Keeping the last 2 turns verbatim, extracting user_constraints separately, generating a ≤ 500-token summary asynchronously after each turn, and validating numbers deterministically gets multi-turn memory with zero added latency and zero invented figures.
  • Task-sized output reserves vs. a single fixed max_tokens. Although output tokens cost ~4× more per token than input tokens, typical prompts (~18.7k tokens) are ~23× longer than typical answers (~800 tokens), so input drives ~85% of dollar cost while sequential output generation drives ~93% of wait time. Sizing max_output_tokens by task (1,000 lookup / 3,000 analysis / 6,000 report) reclaims up to 2,000 tokens for evidence on quick lookups, while pushing arithmetic into the Python sandbox keeps generated text brief and fast.
  • Extractive compression vs. LLM rewriting at Degradation Level 1. Asking a small LLM to rewrite retrieved chunks achieves higher compression ratios, but adds hundreds of milliseconds and risks corrupting subtle financial qualifiers or numbers. Selecting verbatim high-salience sentences preserves exact numbers and character-offset citations at zero LLM cost, trading away some compression ratio for 100% factual fidelity.
  • Parallel Map-Reduce vs. larger-window routing at Degradation Level 2. When a cross-filing comparison needs ~50,000 tokens of evidence, Map-Reduce (extracting cited notes from 12k-token batches in parallel on a cheap model, then synthesizing on the main 32k model) stays within the 32k limit and avoids mid-context attention drop-off, at the price of ~3.5× input tokens and ~12–18 seconds of extra latency.
  • Randomized XML delimiters vs. capability sandboxing for prompt injection. Per-request random tags (<evidence_7c4e91a2>) and role separation make boundary breakouts far harder than static <context> tags, yet no prompt format makes an LLM 100% immune to social engineering inside text. Combining delimiters with least-privilege sandboxing (no network in Python, no write tools, and no unverified UI links/images) guarantees an injection cannot exfiltrate confidential financial data.

Common mistakes

  • Forgetting that max_output_tokens comes out of the 32k limit, sending a 31,500-token prompt that cuts off the LLM mid-sentence after 1,268 tokens or fails validation at the API gateway.
  • Using word_count * 1.3 as the final guardrail instead of the model's actual tokenizer, causing sudden context-overflow crashes on financial balance sheets packed with decimals, currency symbols, and ticker codes.
  • Slicing retrieved chunks mid-sentence or tables mid-row to squeeze in exact token counts, accidentally turning "operating income was not positive" into "operating income was..." or hiding that 380 table rows were truncated.
  • Interpolating user instructions or document titles into the System Prompt, both handing untrusted strings system-level authority and breaking prefix caching (GPU KV-cache reuse, which requires an identical byte prefix across requests) on every single call.
  • Relying on static <document> tags or letting the LLM output raw citation URLs, allowing malicious PDFs to close </document> early and letting the LLM hallucinate broken links instead of resolving short [E4] IDs against a server-side manifest.
  • Allowing older assistant turns to outrank fresh retrieved filings, causing the system to repeat stale or restated numbers instead of citing the primary as_of filing.
  • Evaluating only end-to-end answer quality, which makes it impossible to tell whether a bad answer happened because vector search missed the filing chunk or because the context packer threw the right chunk away.

Follow-up questions

  • How can you isolate and quantify the effect of your context-packing policy on end-to-end RAG answer accuracy? Build an offline benchmark of ~500 real multi-turn analyst questions with human-labeled gold filing chunks and verified numeric answers, then measure the drop from Retrieval Recall@50 (share of gold chunks found by search) to Context Recall (share of gold chunks kept by your packer)—that gap isolates the context selector's exact loss. Run ablation studies (comparing strict priority alone, floors + caps, and the learned utility-per-token GBDT selector, plus an "oracle" ceiling containing only gold chunks) across a token-budget sweep (8k, 16k, 24k, 29k), tracking numeric accuracy, citation precision, and unsupported-number rate. Online, run an analyst-randomized A/B test measuring accepted-answer rate (exports/thumbs-up without correction turns) and inspect logged dropped manifests whenever an analyst flags a wrong answer.
  • Suppose a follow-up question references a filing retrieved on Turn 1 that no longer appears in the current search results—how does your middleware retain access to it? Every chunk included or cited during a session is recorded in SessionState.evidence_ledger with a permanent session ID (E4), document metadata, and the turns where it was cited—persisting across the entire session even after Turn 1 rolls past the 5-turn verbatim window. When Turn 7 asks an indirect follow-up like "Compare this quarter's margin to the filing from the start of our chat", a lightweight query-rewriter expands the reference using the running summary in parallel with raw search, while the middleware also injects previously cited evidence_ledger chunks directly into the candidate pool by key lookup (no vector search needed) with a recency/citation boost so E4 is re-scored and re-packed cleanly.
  • How would you pipeline and stream context assembly so Time to First Token (TTFT) stays as low as possible? First, move all non-blocking work off the request path: chunk token counts are precomputed at index time, history summaries run asynchronously after the previous turn completes, and the 1,500-token static System Prompt sits untouched in Message 1 so the LLM server's prefix cache skips prefilling it. Second, execute independent I/O in parallel at t = 0 ms—fetching Redis session state (~5 ms), evidence_ledger chunks (~5 ms), and top-50 vector search (~50 ms) concurrently—and enforce a strict 150 ms deadline on GPU cross-encoder reranking (~100 ms typical), falling back immediately to vector-similarity scores if reranking lags. Third, stream real-time Server-Sent Events ("Searching SEC filings...", "Packing 28 passages...") to the analyst UI during those ~165 ms, cap low-value filler chunks so the LLM prefills ~18.7k tokens (~1.0 s) instead of 30k, and pipe generated tokens through a streaming citation state machine that resolves [E4] markers on the fly without buffering the whole response.

Follow-up questions

Similar questions

More Rogo interview questions

All 2 Rogo questions →