Handling Ultra-Long Texts Under Compute Constraints: A Context Window Practice Guide

    When users submit massive amounts of text, large language models often only process a fraction of it due to hard context window constraints. This article explores the underlying reasons—such as quadratic attention costs, KV cache memory limits, latency, and token pricing—and provides engineering solutions for handling ultra-long texts. It covers prefix caching, chunking, retrieval-augmented generation (RAG), hierarchical summarization (Map-Reduce), and budget checking strategies. Finally, it offers guidance on avoiding silent truncation risks and selecting the appropriate approach based on specific task types.

    1. The Problem: Surface vs. Essence

    When a user submits a large volume of text at once, the server may only process a portion of it, such as the first few pages or around 10,000 tokens. The rest is excluded from inference and does not appear in the response. This is often misunderstood as the model “not reading fully” or “reading incorrectly,” but the core reason is the hard constraint of the context window.

    The context window refers to the total number of tokens a model can process simultaneously in a single request, with input and output sharing this quota. A token is the basic unit the model uses to split text. English is usually split by word or subword, while Chinese varies greatly depending on the tokenization method, where one Chinese character typically takes one to two tokens. Therefore, a 600,000-character text often translates to hundreds of thousands of tokens, far exceeding the input scale of most daily conversations.

    2. Why Long Inputs Are Restricted

    2.1 Attention Calculation Cost

    The standard self-attention mechanism requires each token to associate with all other tokens, causing the computation to grow quadratically with the sequence length. Doubling the sequence length roughly quadruples the computation. Every doubling of input rapidly amplifies the compute consumption for a single request.

    2.2 VRAM and KV Cache

    During inference, the model must save the Key-Value (KV) cache for each layer, and its memory footprint grows linearly with the sequence length. The more concurrent requests there are, the greater the VRAM pressure. On servers with limited VRAM, a single ultra-long request can squeeze out resources for other requests.

    2.3 Latency and Quality of Service

    The longer the input, the slower the first token is returned. To ensure response times for the majority of users, service providers often set an upper limit on single input lengths. For subscription-based or quota-based services, long text requests quickly consume quotas, making these restrictions even more apparent.

    2.4 Cost Structure

    Input tokens are typically billed per usage or occupy quotas. With a 600,000-character document and no cache hits, every submission requires paying for the entire content. This is why many developers consider the cache hit rate a core cost metric.

    3. Why Caching Matters

    Prefix caching refers to the server reusing previously computed results for identical prefixes. When multiple requests share the same long document as a starting point, subsequent requests can skip repeated computations as long as the prefix matches.

    When designing your workflow, follow these guidelines:

    • Place static content (system instructions, document text) at the beginning of the request and variable questions at the end.
    • Avoid inserting timestamps, random IDs, or other variable elements in the prefix, as this will break cache hits.
    • For multi-turn Q&A on the same document, prioritize reusing the established session context rather than resubmitting the full text each turn.

    4. Engineering Solutions for Ultra-Long Texts

    4.1 Chunking

    Split long text into segments based on token count, keeping a certain overlap between adjacent chunks to prevent semantics from being cut at the boundaries. Below is implementation-agnostic pseudocode, where tokenize and detokenize represent the model’s splitting and restoring functions:

    1. def split_by_tokens(text, max_tokens, overlap):
    2. # overlap must be less than max_tokens
    3. tokens = tokenize(text)
    4. chunks = []
    5. start = 0
    6. while start < len(tokens):
    7. end = min(start + max_tokens, len(tokens))
    8. chunks.append(detokenize(tokens[start:end]))
    9. if end == len(tokens):
    10. break
    11. start = end - overlap
    12. return chunks

    The overlap length is generally 10% to 20% of the chunk size, and the exact value should be adjusted based on the document structure. Splitting by chapters or paragraphs usually yields better semantic integrity than fixed-length splitting.

    4.2 Retrieval (RAG)

    First, chunk the document and generate a vector index. When the user asks a question, retrieve the most relevant segments and only pass these to the model. This method is suitable for Q&A and information locating. For tasks requiring global understanding, such as structural analysis of the entire text or cross-chapter reasoning, the effect is limited because retrieval may miss critical context.

    4.3 Hierarchical Summary (Map-Reduce)

    First, generate a local summary for each chunk (map), then merge all local results to generate a global conclusion (reduce). This method covers the full text but will lose detail. The prompt should explicitly require retaining key information such as numbers, dates, names, conclusions, and disagreements.

    1. # llm_call is a placeholder function representing a single model call
    2. partial = [llm_call("Extract key points from this section: " + c) for c in chunks]
    3. final = llm_call("Synthesize a full text conclusion based on the following points:\n" + "\n".join(partial))

    4.4 Locate Then Read Deeply

    First, let the model or program read the table of contents, titles, and keywords to determine which chapters are relevant to the task, then deeply process only those chapters. This approach is particularly effective for structured documents like reports, contracts, and technical manuals.

    4.5 Pre-send Budget Check

    Estimate the token count before sending the request and reserve space for output. Automatically switch strategies when the window is exceeded.

    1. def plan_strategy(text, window, reserve_for_output):
    2. est = estimate_tokens(text) # Estimation function, needs calibration with actual tokenizer
    3. budget = window - reserve_for_output
    4. if est <= budget:
    5. return "direct"
    6. if est <= budget * 10:
    7. return "chunked"
    8. return "retrieval"

    The specific thresholds should be determined through testing based on the task; do not directly copy the multipliers above.

    5. Hidden Risks to Watch Out For

    Truncation is the most dangerous situation because the output looks normal and readers can hardly notice the omission. It is recommended to take the following measures:

    1. Log the actual processed range in the program, such as “Processed pages 1 to 20,” and return this information to the user.
    2. Annotate source locations for key conclusions in the response for easy manual verification.
    3. Perform secondary extraction and verification of key numbers, clauses, and dates, rather than relying on a single generation result.
    4. Instruct the model in the prompt to state if information is insufficient, prohibiting it from inferring conclusions based on unread content.

    6. Choosing Strategies by Task Type

    The task type determines the appropriate processing method:

    • Information lookup (specific content of a clause): Use retrieval augmentation; lowest cost.
    • Global summary (main conclusions of an entire report): Use hierarchical summary; must accept detail loss.
    • Exact extraction (extracting all amounts and dates): Extract chunk by chunk first, then merge and deduplicate, with manual spot-checking.
    • Deep reasoning (finding contradictions across chapters): Use chunking plus retrieval, keeping the key chapters fully in the context.