LLM Token Consumption Optimization: From Prompt Trimming to Structured Data Compression

    This article examines how token consumption affects cost, latency, and context-window utilization in LLM applications. It presents practical optimization practices across three areas: input compression, output control, and structured data representation. Topics include trimming system prompts and injected context, replacing redundant JSON object arrays with a header-plus-rows tabular format for prompts, constraining output length and format, and establishing token-cost measurement habits. The article also discusses applicability boundaries and engineering practices for these methods.

    LLM Token Consumption Optimization: From Prompt Trimming to Structured Data Compression

    In the daily development and production use of LLM applications, token consumption directly determines call cost, response speed, and context-window utilization. Many teams encounter a common problem: model responses are long and verbose, while input data also occupies a large number of tokens, resulting in low effective information density and high bills. This article systematically outlines a set of implementable token optimization practices across three dimensions: input compression, output control, and structured data representation.

    1. Why Token Optimization Matters

    Tokens are the basic units of text processed by LLMs. Billing, context-length limits, and inference time are all directly related to token count. Token consumption mainly comes from three parts:

    1. System prompts: role settings, rule descriptions, Few-shot examples, etc., which are counted repeatedly on every request;
    2. User input and context: historical conversations, retrieved document fragments, structured business data, etc.;
    3. Model output: the answer generated by the model; the more redundant it is, the higher the cost.

    The goal of optimization is not simply to “cut words” but to improve information density without semantic loss—so that every token carries effective information.

    2. Input-Side Optimization: Making Prompts More Concise

    2.1 Trim System Prompts

    System prompts often expand continuously through iterations and become filled with repeated instructions and ineffective modifiers. It is advisable to do three things regularly:

    • Merge similar instructions: consolidate scattered rules into a bulleted list and remove duplicate wording;
    • Delete redundant modifiers: words such as “please be sure to,” “under all circumstances,” and “definitely” are emphasis terms; model instruction-following mainly depends on instruction clarity rather than tone strength;
    • Compress Few-shot examples: examples only need to cover key patterns. Usually, 2–3 high-quality examples are enough; excessive examples have diminishing marginal returns.

    2.2 Control the Amount of Injected Context

    In multi-turn conversations and RAG (retrieval-augmented generation) scenarios, context is a major token consumer:

    • Trim historical conversations: summarize and compress old conversations beyond the window instead of retaining all original text;
    • Deduplicate and rank retrieved fragments: inject only the fragments most relevant to the current question, avoiding stuffing an entire document into the prompt;
    • Use dynamic templates: select prompt templates of different lengths based on task complexity, using short templates for simple tasks.

    3. Token-Friendly Representation of Structured Data

    This is the most easily overlooked area and also the one with the most room for optimization. When JSON data needs to be passed to a model, the quotes, braces, indentation, and other formatting characters in standard JSON consume a large number of tokens, while these tokens contribute almost nothing to model understanding.

    3.1 Problem: JSON Formatting Overhead

    Take a segment of user-list data as an example. Standard JSON looks like this:

    1. {
    2. "users": [
    3. { "id": 1, "name": "Alice", "role": "admin" },
    4. { "id": 2, "name": "Bob", "role": "user" }
    5. ]
    6. }

    As can be seen, field names such as id, name, and role appear repeatedly in every object. When the array has hundreds of records, repeated field names cause significant token waste.

    3.2 Approach: Tabular Representation

    A general optimization idea is: when the data is an array of objects with consistent fields, rewrite the “array of objects” into a “header + data rows” table format. For example, the JSON above can be expressed as:

    1. users[2]{id,name,role}:
    2. 1,Alice,admin
    3. 2,Bob,user

    This representation contains three parts of information:

    • users: the key name;
    • [2]: the array length, i.e., the number of data rows;
    • {id,name,role}: the column declaration, which appears only once.

    After that, each row is a record with fields separated by commas. Field names are declared only once, and formatting characters are greatly reduced. Tests show that in large-array scenarios with consistent field structures, compared with formatted JSON, this representation usually saves 30%–60% of tokens, and because the data arrangement is regular, model understanding accuracy often does not decrease but may even increase.

    3.3 The Value of “Constraint Information” in the Representation

    The array length [2] in the header also has an additional role: it declares to the model “how many rows of data this table should have.” This is equivalent to embedding a validation guardrail—if the model loses or adds rows while processing or rewriting data, anomalies can be quickly identified based on this, reducing the risk of model hallucination or missed reads.

    3.4 Applicability Boundaries

    Note that this tabular representation is an intermediate format for prompts, not a replacement for JSON:

    • Applicable scenarios: arrays of objects with uniform field structures, tabular data, and batch record injection;
    • Inapplicable scenarios: data with deep nesting levels or large differences in field structures—forcing it flat in such cases would instead break semantics, so the structure of JSON or YAML should be retained;
    • Engineering practice: backend services should still use JSON for communication; perform format conversion only at the step of “sending data to the model,” and the conversion logic can be implemented in a few dozen lines of code.

    4. Output-Side Optimization: Keep the Model from Being Verbose

    4.1 Explicitly Constrain Output Length and Format

    Models tend to provide detailed explanations by default. You can explicitly constrain this in the prompt:

    1. Provide the conclusion and key steps directly. Keep the total length under 200 words. Do not repeat the question and do not include pleasantries.

    Common constraint methods include:

    • Limit word count or item count: for example, “list 3 key points, each no more than 30 words”;
    • Specify output format: require JSON, a list, or a table, which both compresses length and facilitates downstream parsing;
    • Use prohibitive instructions: such as “do not explain the principle” or “do not summarize the full text.”

    4.2 Guide the Model to Skip Meaningless Content

    For scenarios that only need an answer, you can add instructions such as “if you are not confident, state that directly and do not expand into speculation,” which both reduces tokens and lowers hallucination risk.

    4.3 Structured Output and Streaming Truncation

    At the engineering level, you can use the model’s structured-output capabilities (such as JSON mode and function-call parameters) to constrain the returned structure; monitor the length of streaming responses and terminate early once a threshold is exceeded to avoid runaway output.

    5. Build a Habit of Measuring Token Cost

    Optimization needs data support. It is advisable to do three things in applications:

    1. Record the input/output token count of each request and establish baselines by scenario;
    2. A/B test different prompt versions for token consumption and answer quality, avoiding “saving tokens while losing effectiveness”;
    3. Cache high-frequency call scenarios: the same prefix (such as a system prompt) can significantly reduce repeated billing in inference services that support prefix caching.

    6. Conclusion

    The essence of token optimization is the optimization of information density. The core practices can be summarized as: on the input side, streamline prompts and context; for structured data, replace redundant JSON with a “header + data rows” tabular representation; on the output side, use explicit constraints to control length, supplemented by continuous cost measurement. These methods do not depend on a specific platform, and any team calling LLMs can implement them immediately. They usually bring a cost reduction of 30% or more while making model answers more focused and higher quality.