On-Demand File Slicing: Token Optimization for LLM Long Document Processing

    This article explores how on-demand file slicing optimizes token usage, latency, and accuracy when processing long documents with large language models (LLMs). It covers the structural waste of full-file injection, the advantages of server-side native slicing, common slicing dimensions across different file types, and practical architectural recommendations for implementing slicing routers, caching, and cost observability.

    1. The Root Cause: Structural Waste from Full-File Injection

    When multimodal large language models (LLMs) enter production environments, long document processing becomes one of the most common scenarios: contract review, research report summarization, financial statement reconciliation, meeting video retrieval, and training video Q&A. Developers’ intuitive approach is to upload the entire file and let the model “find” the answer. This path is engineering-simple but has clear flaws in its cost structure.

    The basic unit of token billing is the actual content volume inspected by the model. When a 300-page document is sent entirely into the context, the model must “view” all page images or extracted text to locate the relevant two or three pages. This means:

    • Cost is tied to file size, not queried content. Asking a question about page 1 or page 300 incurs almost the same overhead.
    • Context is diluted by noise. Irrelevant pages occupy the window, reducing effective information density and increasing the probability of model attention dispersal and irrelevant answers.
    • Latency increases linearly with input size. The prefill phase for large files is time-consuming, making interactive product experiences unacceptable.
    • Cache benefits are unstable. The entire file acts as a giant prefix; any change in the slicing method invalidates the prefix.

    In other words, full-file injection does not just cost “a bit more”; it simultaneously puts cost, latency, and accuracy in an unfavorable position.

    2. Native File Slicing: Handing Control to the Caller

    Native file slicing control refers to the model service supporting the caller’s declaration of “which parts to load” when parsing files on the server side, rather than having the client download, parse, trim, and re-upload. The difference is critical:

    Dimension Client-side Preprocessing Server-side Native Slicing
    Parsing Logic Implemented individually by each team, poor format compatibility Maintained centrally by the platform, covers mainstream office and media formats
    Layout Fidelity Prone to losing layout, charts, formulas Can preserve original layout rendering
    Transfer Overhead Requires fetching the full file first Only transfers file ID and slice description
    Billing Basis Depends on uploaded content Billed by actually inspected parts

    The core value of native slicing is that the heavy lifting of parsing is handled by the platform, while the decision of “what to see” is left to the caller who understands the business context best. The file itself typically obtains an ID through an initial upload, and subsequent calls reuse this ID, varying only the slicing parameters.

    3. Common Slicing Dimensions

    Structural differences across file types dictate different slicing dimensions. The industry’s common divisions are as follows.

    Documents and Presentations (PDFs, Word processors, Slides)

    • Page numbers or page ranges: The most basic slicing unit.
    • Rendering resolution: Low, medium, high. Low resolution suits layout and structure judgment; high resolution suits small fonts, stamps, and handwriting recognition.
    • Content layers: Page text layer and page image layer. The text layer is the cheapest; the image layer preserves visual information but is more expensive.

    Spreadsheets

    • Worksheet tabs: Load only the target sheet.
    • Cell ranges: Slice by range rather than the entire table.
    • Content layers: Calculated values, formulas, visualization elements (charts). Use values for number checking and formulas for auditing logic—two distinct needs.

    Video

    • Time range cropping.
    • Frame rate and resolution adjustment.
    • Content layers: Transcribed text, visual frames, audio tracks.

    Audio

    • Time range cropping, optionally paired with transcribed text to reduce overhead.

    The common logic across these dimensions is: orthogonal slicing along the three axes of “spatial range + expression precision + content layer.” Understanding this is more valuable than remembering a specific parameter name, as naming conventions vary across platforms but the abstract structure is highly consistent.

    4. Read the Semantics of Default Behavior

    When slicing options are omitted, the platform applies a default strategy, which is often not the most cost-effective. Common defaults are: documents and slides return as page images preserving layout; spreadsheets return calculated values, formulas, and worksheet names for all sheets.

    There are two easily overlooked traps here. First, “preserving layout” means going through the image path; if your task is only text extraction, the default behavior will cost you image-level prices. Second, spreadsheet defaults include formulas, and formula strings are usually “heavier” in token statistics than numerical values. A workbook with extensive cross-sheet references may find its formula section far exceeding the data itself.

    Therefore, the first rule in engineering is: Always explicitly declare slicing intent; do not rely on defaults.

    5. Illustrative Code

    The following pseudocode only expresses the calling pattern and does not represent any specific platform’s real API:

    1. # 1. Upload once to get the file ID
    2. file_id = upload("/data/quarterly_report.pdf")
    3. # 2. Get text by page, lowest precision path
    4. resp = model.generate(
    5. file=file_id,
    6. slice={
    7. "type": "document",
    8. "pages": "12-15",
    9. "resolution": "low",
    10. "layer": "text",
    11. },
    12. prompt="Extract the YoY revenue data from these four pages",
    13. )
    14. # 3. Same file, reuse the ID with a different slice
    15. resp2 = model.generate(
    16. file=file_id,
    17. slice={
    18. "type": "spreadsheet",
    19. "sheets": ["Summary"],
    20. "range": "B2:F20",
    21. "layer": ["values"],
    22. },
    23. prompt="Compare the gross margin across regions",
    24. )

    6. Architecture Recommendations

    1. Build a slicing router. Add a layer between the business logic and model calls to map task types (extraction, comparison, summarization, Q&A) to slicing templates, preventing each call site from writing its own parameters.
    2. Two-stage retrieval. First, use the low-resolution text layer for coarse localization; after identifying candidate pages/ranges, use the high-resolution image layer for fine reading. This is the key technique for reducing costs from “file-level” to “fragment-level.”
    3. Layered caching for file IDs and slice results. File IDs can be reused long-term; slice results are cached using “file + slice parameters” as the key. Parameter changes naturally invalidate the cache without manual cleanup.
    4. Cost observability. Log the slice description and token consumption for each call in the logging service, and set single-file cost thresholds with monitoring alerts. Without slice-level billing attribution, optimization is impossible.
    5. Establish your own benchmark set. Layout density and chart proportions vary greatly across documents, so ROI multiples cannot be copied from others’ conclusions. Use 20 to 50 real business files to form a benchmark set, comparing token usage, latency, and accuracy between full-file injection and sliced injection.
    6. Keep a fallback path. Revert to full loading when slicing fails or file structures are abnormal, ensuring availability first.

    In environments like Baidu AI Cloud, the above architecture can directly reuse general category capabilities: files are hosted via object storage to generate IDs, the slicing call chain is carried by the container platform, and logging services with monitoring alerts handle cost attribution, without introducing extra proprietary components.

    7. Common Pitfalls

    • Treating slicing as retrieval. Slicing solves “reading less,” not “finding accurately.” Localization logic still needs to be provided by the business side, such as directories, page hints, or front-end small model recall.
    • Always choosing the lowest resolution. Low resolution directly causes recognition failure in scenarios involving stamps, handwriting, or extremely small fonts. You save on costs but accuracy collapses.
    • Ignoring formula layer overhead. In financial auditing scenarios where only values are needed, explicitly exclude the formula layer.
    • Repeatedly uploading in loops. File IDs should be reused; repeated uploads are a major hidden cost.

    Conclusion

    On-demand file slicing is essentially a shift in the cost model: from “paying by file size” to “paying by actual inspected content.” It returns optimization decisions from the platform side to the business side, making token overhead in long document scenarios controllable, predictable, and attributable for the first time. For developers, what truly needs to be established is not the memory of a specific parameter, but the orthogonal slicing mindset of “spatial range × expression precision × content layer,” and the routing, caching, and observability systems built around it.