Long Context Compression: Reducing Token Usage with Image Frames
This article presents an engineering approach to compressing long conversation contexts by rendering middle history into image frames. It explains why long sessions need deterministic, low-cost, and traceable compression, outlines a three-stage pipeline (snapcompact, shake, and soft), describes mode presets for different interaction styles, and lists key implementation practices, evaluation dimensions, and common pitfalls. Readers will learn how image-based snapshots, paired with precise text indexes and file maps, can lower token consumption while preserving the ability to trace back to exact details.
Long Context Compression: Reducing Token Consumption with Image Frames
1. Why Long Sessions Must Be Compressed
In scenarios such as AI coding tools, intelligent customer service, and automated operations assistants, conversation length keeps growing as tasks progress. A single task involving changes across multiple files may include dozens of tool calls, hundreds of log outputs, and repeated code searches. The context window is a finite resource, so when history approaches the limit, the system must make a tradeoff: either truncate earlier information or generate a summary.
The traditional approach hands the middle portion of the history to the model for text summarization. This path has three inherent problems:
- Uncontrollable information loss: The level of detail in a summary is decided freely by the model. Critical error lines, exact line numbers, and variable names are easily “generalized” away, yet later backtracking depends precisely on these details.
- Extra cost and latency: Summarization itself requires model calls. Summarizing long text already consumes a large number of input tokens, adding to the bill and the waiting time.
- Uncertainty: Compressing the same history twice may produce different results, making debugging and reproduction difficult.
What is needed, therefore, is a compression mechanism that is deterministic, low-cost, and traceable.
2. Core Idea: Rendering Middle History into Image Frames
The key observation is that mainstream vision models are billed mainly by image area (resolution tier) and do not care how many characters an image contains. Within the “readability ceiling,” a single information-dense image frame carries significantly more information per token than plain text.
The compression flow can then be designed as follows:
- Keep exact original text at the head and tail: The beginning of the session (task goals, constraints) and the end (the most recent several rounds) are left untouched, ensuring the model judges the current state accurately.
- Deterministically render the middle into frames: The middle history is serialized and rendered into several densely formatted images. Rendering is done locally, without calling any model.
- Attach a precise text index: Alongside each compression result, provide a copyable text index and file map containing exact token markers, making it easy to locate the original text on demand.
A schematic of the flow structure:
DSH selects safe regions│▼Deterministic serialization (head/tail limits / log omission / exact token markers)│▼Compression pipeline: snapcompact → shake → soft│▼One compression result (checkpoint) = exact head/tail text + image frames + text index + FILES file map
The responsibilities of the three-stage pipeline are clearly divided:
| Order | Method | Model call | Output |
|---|---|---|---|
| 1 | snapcompact | None | Dense frames, exact head/tail text, FILES index, exact token index |
| 2 | shake | None | Oversized tool outputs keep only head/tail excerpts; the middle is dropped |
| 3 | soft | Depends on configuration | Fallback text compression |
Lossless first, lossy later, with model calls placed last as a fallback. This is the key design for controlling cost and uncertainty.
3. Mode Adaptation: Different Interaction Styles Need Different Presets
Compression strategy should not be one-size-fits-all. Offering multiple presets by interaction style is more reasonable:
- Standard mode: The default tier, suitable for the vast majority of everyday development sessions.
- PTC mode: Aimed at tool-call-heavy scenarios with strong programmatic orchestration.
- Creative mode: Aimed at exploratory, divergent tasks, preserving more traces of design discussion.
- Minimal mode does not apply: This mode deliberately omits read/write/edit tools, so compressing image frames would contradict its design purpose.
A simple rule can help decide whether a session is suited to image compression: is the session long, and does it require repeated backtracking to details. Compressing short chats yields very little benefit and instead adds the overhead of one rendering pass and indexing.
4. Key Implementation Practices
- Local rendering: Image generation does not go through a model, avoiding extra calls and data outflow while ensuring reproducible results.
- Deterministic serialization: Fixed truncation limits, fixed log omission rules, and a fixed token counting method mean the same input always produces the same output.
- Traceable index: Images are only “snapshots” and must be paired with a precise text index and file map; otherwise the model cannot locate a specific line.
- Uninstallable with no residue: After removing the extension, the added presets disappear as well; already-generated compression results are kept as ordinary summaries without breaking session integrity.
- Dependency and version constraints: Such capabilities typically depend on relatively new runtime versions, so runtime and host version requirements must be checked before deployment.
- Layered installation methods: The in-app extension page comes first; the command-line approach suits batch and automated use; locally packaged artifacts must be built before installation; the remote package URL approach suits internal distribution. In all commands, replace the profile name, paths, and addresses with the actual values of your own environment.
5. Evaluating Results and Common Pitfalls
Evaluation should cover three dimensions: information fidelity (whether key errors, line numbers, and file names can be traced back), token cost (the difference before and after compression), and task success rate (whether execution can continue correctly after compression).
Common pitfalls:
- Assuming image frames can fully replace the index. Without an index, the model can only “guess positions from the image.”
- Enabling compression on short sessions, where the benefit is offset by fixed overhead.
- Ignoring the rendering resolution ceiling, which makes text too small to read.
- Moving the lossy step earlier, causing critical logs to be dropped too soon.
6. Extension in Baidu AI Cloud Scenarios
When building similar capabilities on Baidu AI Cloud, you can combine general-purpose services into a closed loop: use object storage to archive compression snapshots and indexes, use a log service to retain call traces before and after compression, use monitoring and alerting to observe changes in token consumption and task success rate, and use a container platform to host stateless rendering services that scale elastically for peaks. The core principles remain unchanged: determinism first, lossless first, traceable fallback.
