Handling Large Text with LLMs: Cut Token Costs and Keep Connections Stable

    This article explains how to manage large texts like question banks and long PDFs with large language models. It covers cost estimation, token reduction strategies (RAG, context management, batch processing), and troubleshooting connection drops caused by timeouts or resource limits. Practical parameters and monitoring metrics are included for direct implementation.

    When working with large text inputs such as question banks or lengthy PDFs, developers often face two challenges: unexpectedly high costs per API call and frequent connection interruptions. Both issues usually stem from the call method and parameter settings. This article addresses these problems in order: first calculating costs, then reducing token consumption, and finally ensuring stable connections.

    Why Does a One-Time Large Text Input Cost So Much?

    1.1 How Token Costs Are Calculated

    Large models charge by tokens, with separate pricing for input and output. The cost of a single call can be estimated using this formula:

    Single-call cost ≈ Input tokens × Input price + Output tokens × Output price

    The input token count grows approximately linearly with text length. If the text length doubles, the input cost roughly doubles as well.

    Multi-turn conversations are more complex. Each turn sends the entire history to the model, so the input for turn n is approximately the sum of all previous turns. For a conversation with N turns, the cumulative input can grow roughly quadratically with the number of turns—this is why long conversations quickly become expensive.

    Consider a mixed question bank of 2,000 questions. Assuming each question with its options contains about 100 Chinese characters, the whole bank has roughly 200,000 characters. Chinese text typically maps to one or two tokens per character, so the full bank might require 200,000 to 400,000 tokens. Always use the tokenizer of your target model for exact counts rather than relying on character-based estimates.

    1.2 Two Common Sources of Waste

    • Context accumulation: In multi-turn conversations, unrelated historical messages are repeatedly sent.
    • Redundant text: Headers, page numbers, garbled characters, and repeated paragraphs extracted from PDFs all count as tokens but contribute nothing to the task.

    Cleaning up such content during preprocessing can directly reduce input size.

    How to Reduce Token Consumption?

    2.1 Use RAG to Send Only Relevant Chunks

    RAG (Retrieval-Augmented Generation) works like this: first split the question bank or document into chunks, compute embeddings, and store them in a vector database. When a user asks a question, retrieve only the most relevant chunks and send them to the model—not the entire document.

    Here is a starting set of parameters, which you should tune based on retrieval quality with real samples:

    Parameter Starting Value Tuning Basis
    Chunk size 300–800 characters Question integrity, retrieval accuracy
    Chunk overlap 10%–20% Whether questions or paragraphs spanning chunks are cut off
    top-k (number of retrieved chunks) 3–5 Answer completeness, token budget

    When splitting, try to respect question or paragraph boundaries to avoid breaking a single question across two chunks.

    2.2 Manage the Context Window

    For multi-turn conversations, you can control history length using two approaches:

    • Sliding window: Keep only the most recent N turns of full messages.
    • Summary compression: Have the model generate a brief summary of earlier conversation turns, then pass only the summary plus the recent turns.

    2.3 Asynchronous Batch Processing

    When processing large volumes of data, split the task into small batches, push them into a message queue, and let worker processes call the model batch by batch. Set a token cap per batch. If a single batch fails, only that batch needs retrying, without affecting the overall progress.

    If the model service supports prompt caching, place fixed instructions and the common parts of the question bank at the beginning of the request to improve cache hit rate.

    2.4 Use Metrics to Verify Optimization Results

    Metric Meaning How to Monitor
    Average tokens per call Input + output per invocation From the usage field in API responses
    Cost per question Total cost divided by number of processed questions Daily aggregation
    Retrieval hit rate Proportion of retrieved results that contain the answer evidence Periodic spot checks with labeled samples
    Cache hit rate Share of input that hits the cache From usage fields
    Retry rate Share of requests that need retrying From gateway logs

    After every parameter adjustment, compare these metrics to ensure cost reduction does not come at the expense of accuracy.

    How to Diagnose Connection Drops?

    3.1 Inference Timeout

    Long text inference takes noticeably longer than short text. If the client or gateway sets a short read timeout, the connection is cut off while the model is still computing.

    Many reverse proxies have default read timeouts. For example, Nginx’s proxy_read_timeout defaults to 60 seconds; if no data is returned within that time, the connection is closed. For long inference scenarios, set both the client timeout and the proxy timeout to values greater than the model’s P99 inference latency, with some headroom.

    Using streaming output (stream) allows the server to send data continuously, reducing the chance of disconnection due to prolonged silence.

    3.2 Insufficient GPU Memory or RAM

    When running models locally, a large input—or a large context history in multi-turn sessions—can exceed available memory. This often leads to process crashes or connection resets. Monitor memory usage and reduce batch sizes or context length if needed.

    For cloud APIs, if you experience frequent disconnections beyond timeouts, check the provider’s rate limits and error codes. If the service returns errors like 429 (too many requests) or 503 (service unavailable), implement exponential backoff with retries.

    3.3 Network Instability

    Network issues can also cause dropped connections. Use a reliable network environment, enable keep-alive on the connection, and consider retrying with a small backoff. If the API supports automatic retries, configure them appropriately to avoid losing progress.