Token Compression and Optimization for Large Language Models: A Practical Guide
This article explains why token usage has become a core cost factor in LLM applications and presents a practical approach to reducing it by changing how structured data is formatted before it reaches the model. It covers a table-style compact notation, the reasons models handle it well, a five-step implementation workflow with sample code, evaluation metrics and common pitfalls, and how the conversion pipeline can fit into a cloud-based system. Readers will learn how to cut token consumption on uniform record arrays while keeping accuracy and latency in check.
1. Background: Why Tokens Became the Main Cost Driver
Large language models bill and compute in tokens, so every redundant segment on the input side turns into both cost and latency. In enterprise scenarios, structured data such as orders, logs, user profiles, and monitoring metrics often makes up the bulk of a prompt. When this data is serialized, it naturally carries a large amount of repeated structural information. Take an array of objects as an example: every record repeats the same keys, quotes, brackets, and commas, and the waste grows with the number of records. The first step in optimizing tokens, therefore, is not to change the model but to change the shape of the data you feed it.
2. Core Idea: Express Arrays as Tables
A common compression approach in the industry is a token-oriented structured markup. It does not aim to replace general-purpose data formats used for exchange between programs; it exists as an intermediate format at the prompt layer. The backend keeps handling business logic with the general format and performs a single conversion right before the payload is submitted to the model.
Side-by-side comparison of the same data:
# General object array (highly redundant){"users":[{"id":1,"name":"Alice","role":"admin"},{"id":2,"name":"Bob","role":"user"}]}# Table-style compact form (column names appear once)users[2]{id,name,role}:1,Alice,admin2,Bob,user
The key is three conventions: key names are declared once, [N] states the row count explicitly, and {column names} defines the field order, after which each row contains values only. For large arrays with a consistent structure, this notation typically saves 30% to 60% of tokens, and models understand the “header plus rows” pattern very naturally, so accuracy often stays flat or even improves.
3. Why Models Prefer This Format
First, information density is higher. The same context window holds more valid records, which reduces the risk of truncation. Second, the pattern is more regular. With column names separated from row values, the alignment cost for extraction, aggregation, and comparison is lower. Third, it comes with built-in validation anchors. The row count declaration and column definition act as guardrails, letting the model check whether its output is complete and whether all fields are present, which lowers the chance of fabrication and omissions. Fourth, the hierarchy is shallower. Compared with deeply nested bracket structures, a flat table reduces the model’s bracket-matching burden.
4. Implementation in Five Steps
- Data tiering: separate the fields the model must see from the fields only the backend uses, and drop the latter outright.
- Structure detection: identify arrays of objects that share a uniform structure as the main compression target; leave heterogeneous data as is or normalize it first.
- Format conversion: perform the table-style encoding during prompt assembly, keeping column order fixed and separators consistent.
- Constrained prompting: state the row count and the meaning of each column in the instructions, and require the model to answer with table semantics rather than improvising.
- Result backfill: parse the model output back into structured objects in code, closing the loop.
Sample code (pseudo-implementation):
def to_compact(rows, key):cols = list(rows[0].keys())head = f"{key}[{len(rows)}]{{{','.join(cols)}}}:"body = "\n".join(",".join(str(r[c]) for c in cols) for r in rows)return head + "\n" + body
5. Measuring Results and Common Pitfalls
Evaluation should focus on three metrics: token usage, task accuracy, and end-to-end latency. In practice, tabular data yields the largest gains, while long-form text benefits only marginally. Common pitfalls include forcing sparse fields into a table and producing many empty values, failing to escape separators that collide with the content itself, and compressing too many rows at once, which scatters the model’s attention. The recommendation is to batch by business case, trim by field, and roll out gradually by scenario.
6. Combining with General Cloud Capabilities
In a real system, you can archive raw data in object storage, use a message queue to smooth out traffic spikes, run the conversion service on a container platform, and watch the token curve through log and monitoring services with alerting. General-purpose capabilities from cloud providers such as Baidu AI Cloud can help teams turn “format conversion + cost accounting + quality monitoring” into a standardized pipeline, keeping quality intact while continuously lowering LLM invocation costs.
