AiCredits
Token Budgeting

Prompt Compression Techniques: Cut Token Bills Without Losing Quality

Practical prompt compression techniques — context pruning, rolling summaries, deduplication and model routing — with runnable Python you can ship today.

Published 2026-11-19 Updated 2026-11-19 7 min

Why prompt bills grow faster than usage

Token bills rarely balloon because the model is verbose. They balloon because the request is. A support assistant that started as three sentences quietly becomes a wall of retrieved documents, a restated style guide, a forty-turn transcript and a pretty-printed JSON blob — and every one of those tokens is charged on every single call.

Compression is not about writing clipped English. It is about deleting information the model cannot act on while protecting the parts it must not lose: identifiers, numbers, negations and output contracts. The techniques below are ordered by how much they usually save relative to the risk they carry.

The shared client (used by every snippet below)

Export your key as AICREDITS_API_KEY, then copy the blocks as written. The helper logs prompt and completion tokens so you can see exactly what each change buys you.

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
)

def ask(prompt: str, system: str = "You are a precise technical assistant. Skip preamble.") -> str:
    resp = client.chat.completions.create(
        model="deepseek-v4-flash",
        messages=[
            {"role": "system", "content": system},
            {"role": "user", "content": prompt},
        ],
        temperature=0.2,
    )
    u = resp.usage
    print(f"prompt={u.prompt_tokens} completion={u.completion_tokens}")
    return resp.choices[0].message.content

Technique 1 — Strip structural noise before you touch meaning

Most wasted tokens are structural, not semantic. Log lines, indentation, markdown tables converted from spreadsheets, HTML navigation, and the same instruction repeated in both the system and user turn all cost money while adding no signal.

Run one experiment: take your three longest prompts, delete anything a careful reader could infer from what remains, and diff the answers. In most systems the output is unchanged. Where it does change, you have found a constraint worth keeping — write it down and stop deleting it.

  • Collapse JSON with json.dumps(obj, separators=(",", ":")) instead of indent=2 — indentation and newlines are billed tokens.

  • Send the exception type, message and top three stack frames rather than the full traceback.

  • Strip retrieval boilerplate: nav menus, cookie notices, "Was this helpful?", author bios, legal footers.

  • Keep exactly one copy of each rule. If both the system and user turn demand JSON, delete one — prefer the copy closest to the data.

  • Truncate tool output at the boundary you actually reason over, not at whatever the API happened to return.

Technique 2 — Compress history into a rolling summary

Resending the full transcript is the most common cause of runaway spend in chat products and agent loops. It also degrades quality: superseded instructions from turn four compete with the instruction from turn forty.

The fix is a rolling summary with an explicit preservation list. Summarize old turns once, keep the newest few verbatim, and append the new user message. Because the summary is stable across calls, it also plays well with caching. The summary prompt must name what cannot be dropped — numbers, identifiers, file paths, error strings — otherwise the model returns something fluent that quietly erases the one detail you needed.

def rolling_context(messages: list[dict], keep_last: int = 2) -> list[dict]:
    """Replace older turns with one summary; keep the newest turns verbatim."""
    if len(messages) <= keep_last + 1:
        return messages

    old, recent = messages[:-keep_last], messages[-keep_last:]
    transcript = "\n".join(f"{m['role']}: {m['content']}" for m in old)

    summary = ask(
        "Rewrite the transcript as terse bullets. Preserve every number, identifier, "
        "file path, error string and user constraint exactly. Drop greetings and any "
        "context that is restated later.\n\n" + transcript
    )
    return [{"role": "system", "content": "Earlier conversation:\n" + summary}] + recent


history = [
    {"role": "user", "content": "We use SQLAlchemy 2.0. The parser is app/parse.py."},
    {"role": "assistant", "content": "Noted. What breaks?"},
    {"role": "user", "content": "KeyError: 'span' on nested blocks."},
    {"role": "assistant", "content": "Block nodes lack the 'span' key; read it with .get('span')."},
]

messages = rolling_context(history) + [{"role": "user", "content": "Patch the parser."}]
resp = client.chat.completions.create(model="deepseek-v4-flash", messages=messages)
print(resp.choices[0].message.content)

Technique 3 — Rank and cut retrieved context

Shrinking chunk size is not compression; it relocates cost. The real win is ranking before you send. Use a flash-tier model as a ranker that returns indices only, so output tokens stay tiny and everything you discard is pure savings on the input side.

Always keep a deterministic fallback: if the ranker returns something unparseable, use the first k chunks instead of failing the request. Deduplicate first as well — retrieved sets routinely contain the same paragraph from three URLs, and no ranker will clean that up for you.

def prune_chunks(question: str, chunks: list[str], keep: int = 3) -> str:
    numbered = "\n\n".join(f"[{i}] {c}" for i, c in enumerate(chunks))
    resp = client.chat.completions.create(
        model="deepseek-v4-flash",
        messages=[
            {"role": "system", "content": "You rank passages by how much they help answer the question. Reply with indices only, comma separated, best first. No prose."},
            {"role": "user", "content": f"Question: {question}\n\nPassages:\n{numbered}"},
        ],
        temperature=0,
        max_tokens=16,
    )
    raw = (resp.choices[0].message.content or "").strip()
    picked = [
        chunks[int(t)]
        for t in raw.replace(" ", "").split(",")
        if t.isdigit() and int(t) < len(chunks)
    ]
    return "\n\n".join(picked[:keep]) if picked else "\n\n".join(chunks[:keep])


passages = [
    "Invoices are stored in the billing schema and expire after 7 years.",
    "Refunds over 500 units require a second approver.",
    "Our office moved to Lisbon in 2023.",
]
print(prune_chunks("Who has to approve a large refund?", passages, keep=2))

Technique 4 — Order prompts so cache hits do the work

Cached input tokens are billed at a lower rate than fresh ones, which makes prompt ordering a pricing decision, not just a style one. The rule is stable-to-volatile: system prompt and tool definitions first, fixed reference material next, retrieved documents after that, and the user's actual message last. Anything that changes between calls must live after the cached region.

A timestamp on the first line of your system prompt, a shuffled tool list, or a random session ID invalidates the prefix on every request. That single line can cost more than the entire rest of the prompt.

  • Freeze the system prompt byte-for-byte; version it in code instead of templating values into it.

  • Put retrieved context after the instructions but before the question.

  • If you must include a timestamp or request ID, append it to the user turn.

  • Sort tool definitions deterministically — dictionary iteration order is not a caching strategy.

Technique 5 — Route by difficulty, escalate only on failure

Not every call needs the stronger model. Classification, extraction, reformatting and ranking are handled well by deepseek-v4-flash. Reserve deepseek-v4-pro for steps where a wrong answer is expensive: multi-step reasoning, ambiguous policy decisions, final review of generated code.

The cheap pattern is try-then-escalate: run flash, validate the output against a schema, and re-run on pro only if validation fails. Validation is deterministic and nearly free; always paying for the stronger model is a habit, not a decision. Pro is genuinely the stronger option and it costs more per token — that trade is worth it on a fraction of your traffic, not all of it.

import json

def extract(text: str, keys: list[str]) -> dict:
    prompt = (
        "Return only a JSON object with these keys: " + ", ".join(keys) + "."
        " Use null when a value is absent. Text:\n" + text
    )
    for model in ("deepseek-v4-flash", "deepseek-v4-pro"):
        resp = client.chat.completions.create(
            model=model,
            messages=[{"role": "user", "content": prompt}],
            temperature=0,
        )
        try:
            data = json.loads(resp.choices[0].message.content)
        except (json.JSONDecodeError, TypeError):
            continue
        if isinstance(data, dict) and all(k in data for k in keys):
            print(f"resolved by {model}")
            return data
    raise RuntimeError("no model produced valid JSON")


print(extract(
    "Order 4471 shipped on 2026-03-02 to Lisbon; total 1290 units.",
    ["order_id", "ship_date", "total"],
))

What you must never compress

  • Negations. "Do not invent citations" becomes "Invent citations" if you trim the wrong three words.

  • Identifiers: function names, column names, error codes, SKUs, enum values.

  • Numbers, units and dates — including the ones embedded in examples.

  • Output contracts: schema keys, delimiters, the instruction to return JSON only. Keep them in the last few lines, where they are likeliest to be honoured.

  • Anything a downstream parser depends on. Compression that breaks json.loads is not a saving.

Compare the levers

TechniqueWhat it removesRisk to watchBest for
Noise strippingWhitespace, boilerplate, duplicate rulesAccidentally deleting a constraintEvery prompt
Rolling summaryOld conversational turnsSummary silently drops a detailChat and agent loops
Context pruningIrrelevant retrieved passagesRanker misjudges relevanceRAG pipelines
Cache-friendly orderingNothing — it prevents prefix invalidationOne volatile field near the topHigh-volume, stable system prompts
Model routingStronger-model spend on easy callsExtra validation step and latencyExtraction, classification, reformatting

Measure, then ship

Log usage.prompt_tokens and usage.completion_tokens for every call, tagged by route. Then freeze a set of thirty to fifty real prompts with known-good answers and run it before and after each compression change. A technique that lowers tokens but drops accuracy on that set is a regression, not an optimisation — and you will only find out if the set exists before you deploy.

Total cost also depends on when batch work runs and how much of your prompt is being served from cache: off-peak traffic costs less and cache hits cost less than fresh input. Current rates live at aicreditsapi.com/deepseek-prices — check them before deciding a rewrite is worth the engineering time.

FAQ

Does prompt compression actually reduce cost without hurting quality?

It reduces cost reliably; whether quality holds depends entirely on what you cut. Structural noise, duplicated rules and stale history are safe. Negations, identifiers and output schemas are not. Verify on a frozen eval set rather than a vibe check.

Which model should do the compressing work?

Use deepseek-v4-flash for summarization, ranking and validation — it is the fast default and this work is mechanical. Escalate to deepseek-v4-pro for the final answer when validation fails or the task is genuinely multi-step.

How do I know a cached prefix is actually working?

Send two identical requests with the same stable prefix and compare the usage figures the API returns. If caching is effective, the second call should report fewer fresh input tokens. If the numbers are identical, something in your prefix is changing — a timestamp, a shuffled tool list, a templated ID.

Is a rolling summary better than simply truncating history?

Usually yes, but it costs an extra call. Truncation is free and fine for casual chat. Use the summary when earlier turns contain constraints the model still has to honour.

Do I need a Chinese phone number or bank account to use the DeepSeek API?

Not through AiCredits. Credits are sold to international developers and payable by card or PayPal, and the endpoint is a drop-in OpenAI-compatible base URL you point the SDK at.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

💻Code Explainer

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×