Feeding Large Files to LLMs: How On-Demand Chunking Cuts Token Usage by Up to 90%

    This article explains why uploading an entire large file to a large language model is the most expensive way to read it, and how on-demand chunking reduces token consumption. It covers a three-layer pipeline of low-cost scanning, targeted loading, and cross-turn reuse, chunking strategies for PDFs, slides, spreadsheets, audio, and video, a practical cost model, engineering implementation tips, and common misconceptions. Developers will learn how to align token costs with actual reading behavior by structuring, indexing, and caching file content.

    1. The Starting Point: Why Loading Everything Is the Most Expensive Way to Read

    When you hand a several-hundred-page PDF, a spreadsheet with tens of thousands of rows, or a few hours of meeting audio to a large language model, the most intuitive approach is to upload it whole, parse it whole, and count the entire thing against the context window. The problem is that billing and compute consumption are measured in tokens, and token count correlates strongly with the physical size of the input material but only weakly with what the model actually needs to see.

    This creates three kinds of waste:

    1. Wasted context: In an annual report, only three tables might actually answer the question. The rest is cover pages, table of contents, disclaimers, and repeated headers and footers.
    2. Paying the same cost over and over: In multi-turn conversations, attaching the full file on every turn makes cost grow linearly with the number of turns.
    3. Attention dilution: The longer the context, the higher the chance that key information gets buried, and answer quality drops. The result is a reverse curve: spending more money for worse results.

    So the industry has gradually converged on one idea: a file should not be treated as an indivisible whole, but as a structured resource that can be addressed and loaded partially. This is exactly the problem that file chunking control solves.

    2. The Core Idea: Locate First, Load in High Resolution Second, Pay Only for What You View

    The key to on-demand chunking is turning “reading a file” from a single atomic operation into an explicit pipeline:

    • Step 1: Low-cost scan (the locating layer). Extract plain text or generate low-resolution previews to skim the whole document quickly. This layer only answers “where is it,” not “what are the details.” It is extremely token-efficient, because the character count of extracted text is far smaller than the cost of rendering every page as an image and encoding it.
    • Step 2: Targeted loading (the detail layer). Based on the scan results, enable high-precision parsing only for the page numbers, cell ranges, or time segments that were matched.
    • Step 3: Cross-turn reuse (the caching layer). Upload the file only once. Later turns reference different chunks of the same resource instead of re-uploading it.

    This structure is closely analogous to “virtual memory plus on-demand paging” in operating systems: the full dataset stays resident on the storage side, and the compute side maps in only the pages it currently needs. The engineering benefits are similar too: lower peak memory usage (the context window) and fewer I/O operations (uploads and parsing).

    A sketch of the call skeleton (pseudocode, only to express the layered idea):

    1. # 1) Upload once and get an addressable file handle
    2. doc = files.upload(path="annual_report.pdf")
    3. # 2) Low-cost scan: text only, used for locating
    4. overview = model.generate(
    5. contents=[doc.as_text_mode()], # text extraction, no image rendering
    6. prompt="List the page numbers and table IDs related to 'gross margin'"
    7. )
    8. # 3) Targeted high-resolution load: only the matched pages
    9. answer = model.generate(
    10. contents=[doc.pages(12, 13).as_high_res()],
    11. prompt="Calculate the change in gross margin from the tables on these two pages and explain why"
    12. )
    13. # 4) Multi-turn reuse: swap chunks, not files
    14. followup = model.generate(
    15. contents=[doc.pages(27).as_high_res()],
    16. prompt="Compare the cash flow on page 27 with the conclusion just now"
    17. )

    3. Chunking Dimensions: Different Modalities Need Different Addressing Schemes

    Chunking is not simply truncating by bytes. It has to fit the natural structure of each file format, or it will break the semantics.

    • PDFs / documents: Use page numbers, sections, and bookmarks as primary keys, supplemented by layout blocks (headings, paragraphs, tables, figure captions). Tables are best taken whole as “header plus data block” to avoid splitting a table across pages.
    • Presentations: Use the slide number as the granularity, optionally filtering by layer or object to take only the slide that contains the target chart.
    • Spreadsheets: Use the worksheet plus cell range (such as A1:F200) as the granularity. This is the category with the most obvious compression ratio, because more than 90% of the cells in a workbook are usually irrelevant to the question.
    • Audio: Use time segments as the granularity. Run transcription and silence detection first, then apply fine-grained processing only to the intervals that contain valid speech.
    • Video: Use time segments plus keyframes as the granularity. Extract a low-frame-rate thumbnail sequence to locate candidates, then pull frames from the candidate segments.

    One general principle: structure first, index second, load last. Chunks without structural information (page numbers, timestamps, cell coordinates) merely cut a large file into small files. They save little and easily lose context.

    4. The Cost Model: Calculating Exactly How Much You Save

    Let the parsing cost of the full file be C_full, the cost of the scan layer be C_scan, and the detail cost of the i-th matched chunk be C_i. The total cost of the on-demand approach is approximately:

    1. C_on_demand ≈ C_scan + Σ C_i (i = chunks actually viewed)

    The approach works as long as C_scan + Σ C_i < C_full. Since the scan layer is usually plain text extraction, its per-unit content cost is far lower than image-based rendering. In practice, C_scan is often only a small fraction of C_full, and Σ C_i depends on the number of matches, which is usually far smaller than the total page count.

    One caveat: publicly reported savings ratios (for example, several-fold to tens-of-fold savings for certain document types) come from measured results across different implementations and cannot be treated as a guaranteed value for your system. What really determines the benefit is three variables: how structured the file is, how sparse the required chunks are for the question, and the cache hit rate. Before integrating, run an A/B measurement on your own samples and record three metrics: average matched pages, average scan overhead, and multi-turn reuse rate. Then project your monthly bill.

    5. Engineering Implementation

    1. Build a file resource layer. Abstract uploaded files into resource objects with a unique identifier, recording the format, page count or duration, and the structural index already parsed, so multi-turn sessions can reference them.
    2. Store the index separately from the source content. The structural index (table of contents, timestamps, table list) is small and can be cached long-term; the original content lives in object storage and is read on demand.
    3. Make chunk granularity configurable. Expose parameters such as the scan budget, maximum number of chunks loaded simultaneously, and per-chunk token limit, and tune them per business scenario to avoid pulling in too much detail and blowing up the context again.
    4. Provide a fallback path. When chunk locating fails or answer confidence is low, allow progressively widening the scope (page → section → chapter) instead of blindly reverting to loading the whole file.
    5. Observability. Log the scan tokens, detail tokens, and matched chunk IDs for every request, and use logging services plus monitoring alerts for cost attribution. Only then can you keep optimizing prompts and chunking strategies.
    6. Permissions and compliance. Chunk reuse means files live longer on the server side, so lifecycle, access control, and deletion policies must be defined. Sensitive documents should have shorter cache durations.

    6. Common Misconceptions

    • Misconception 1: Chunking always saves money. If the question requires reading the whole document for a global summary, the matched chunks approach the full set, and the benefit is offset by the scan overhead.
    • Misconception 2: Text extraction is always lossless. Complex layouts, scanned documents, and chart-heavy pages lose information during text extraction. Such pages must go through the image-based path.
    • Misconception 3: The finer the chunks, the better. Overly fine chunks break contextual continuity. The model needs extra reasoning to fill in the severed semantics, which actually increases output tokens.

    7. Conclusion

    Charging by the whole file essentially shifts storage cost onto the compute side. The value of file chunking control is to turn reading into an addressable, layered, and reusable process, aligning the cost curve with real reading behavior. For developers, the implementation path is not complicated: build a structured index first, then layered loading, and finally use caching to spread a single upload across multiple turns. If you are using the relevant model services from Baidu AI Cloud, it is also advisable to run a small-scale measurement with the cost model above before deciding on chunk granularity and caching strategy, so that every token is spent on content that is actually viewed.