aiXcompact-4B compresses context to 25.89%: how to price the token bill of a coding agent without losing money

Three numbers first: 25.89%, 78%, 0.019 yuan. On November 11, aiXcoder -- spun out of Peking University's Institute of Software Engineering -- released aiXcompact-4B, a 4B model that does exactly one job: shrink the history of a coding agent. The published figures: history compressed to 25.89% of its original length on average, 78% lower GPU inference cost per compaction than DeepSeek-V4-Pro in private deployment, and roughly 0.019 yuan per API compaction request (per the aiXcoder announcement and Jiqizhixin, 2026-11-11; Yesky reported the same day). A single A100-40GB can host it.

The interesting part is not that a small model won again. It is that compaction got pulled out of the general-purpose model entirely. Claude Code and Codex CLI both ship a /compact command, and both do roughly the same thing: when the context window is about to fill, ask the main model to write a summary. Convenient, except that writing the summary is itself a full long-context call, and the output is one unstructured blob of prose.

Context compression is not summarization: aiXcompact-4B's three structured decisions

A coding trajectory has roles: the user request, the agent's analysis, tool calls, and tool results carrying file contents or test logs. Compressing it is not about how much you delete. It is about whether the next turn can still run. aiXcompact-4B emits three kinds of decisions (per the aiXcoder technical note, 2026-11-11):

  • Keep: core requirements and hard constraints verbatim. "Stay compatible with the existing interface", "no new external dependencies", "reuse this auth component" -- paraphrase these and the next forty turns of code drift off course.
  • Trim tool results: keep the call, replace long file reads, search hits and test logs with short text. The catch is pairing must survive. In an OpenAI-style message list, every role=tool message hangs off an earlier assistant message's tool_calls via tool_call_id. Emit a summary and lose that id, and the next turn either errors out or the model hallucinates a tool result that never existed.
  • Delete: duplicate records and intermediate output with no further reference value, paired with a check that key errors and business facts already made it into the task summary.

The output is not a paragraph. It is a message sequence you can hand straight back to the agent, plus a structured task summary covering intent, key technical facts, errors and fixes, current work, and todos. That distinction is the first thing people get wrong when rolling their own /compact.

The training path is equally unromantic: teacher-model distillation, LoRA fine-tuning of a 4B student, and structured compaction decisions. Training data comes entirely from real agent trajectories in software engineering, after normalization, filtering and compaction-trigger sampling. On the private eval set it scores 0.7012 on the composite rule metric against 0.7332 for the 1.6-trillion-parameter DeepSeek-V4-Pro, with 0.9939 format validity and 0.9936 decision coverage. Average retention is 25.89% versus 18.46% for the teacher. On Terminal-Bench, plugged into OpenCode, overall task completion accuracy did not drop (164 private cases published by aiXcoder, 2026-11-11).

The bill: compacting with a frontier model hands the savings straight back

Say one trajectory is 4,000 input tokens and compression leaves 1,000. Looks like 3,000 saved. But the compaction call itself has to send all 4,000 tokens to the main model. Fable 5.2 lists at 8 USD per million input tokens (per mindpattern's roundup of SemiAnalysis and Latent Space, 2026-11-10), so that single pass costs about 0.032 USD in input alone. The dedicated small model's request is quoted at 0.019 yuan. Not the same order of magnitude.

MetricDeepSeek-V4-ProaiXcompact-4B
GPU cost per compactionabout 0.9518 yuanabout 0.2076 yuan
API cost per compaction (proxy estimate)0.702 yuan0.019 yuan
Composite rule score0.73320.7012
Average retention18.46%25.89%

Pause on those last two rows. The small model's rule score is actually slightly lower, and it retains more (compresses less aggressively). Yet task completion on Terminal-Bench held. Compaction quality and final task outcome are not monotonic: 18% is not automatically better than 26%, and dropping a stack trace gets paid back with interest a few turns later as repeated debugging. REMORY, a 1.9B memory module from the Shanghai Innovation Institute reported by Tencent News on 2026-11-11, is a useful counterpoint: instead of fighting /compact, it appends residual soft memory to the summary. On Qwen3.8-27B running Terminal-Bench 2.1, tool errors fell from 933 to 568, repeated output from 459 to 377, and per-task generation cost from 4.29 to 2.86 USD.

The same day, three other teams answered the same question at different layers

On GitHub Trending for 2026-11-11, shadcn/improve has a one-line README: use your most capable model to audit your codebase and write plans for cheaper models to execute. The skill writes no code itself. /improve execute sends a cheaper model into an isolated git worktree, then reviews the resulting diff against the plan (per GitHub Trending, 2026-11-11, +333 stars that day). Aiera relayed Anthropic's own cost guide on 11-10 with the same split: Opus 5.5 for the main line, Haiku for the chores; on 11-11 it reported Muse Ember finishing hundreds of browser steps for three cents. Meta prices Ember at 0.10 USD per million input tokens and 0.50 per million output, with the line "Muse Wonder plans, Muse Ember handles the volume".

Then there is a very concrete trap. On 2026-11-10 an r/ClaudeAI user posted that a five-hour usage window vanished in minutes: they expected subagents on Opus, but a resumed session had not set the subagent model variable, so the children inherited Fable (per mindpattern, 2026-11-10; single unconfirmed report). The same roundup carries a colder number: Fable 5.2 cut per-token price 20% versus 5.1, yet SemiAnalysis measured per-task cost rising from 67.16 to 88.15 USD, up 31%, because the new model writes more tests and spawns subagents to check itself. So tiered routing saves money only if the children really run on the cheap model. Pin that in config. Do not leave it in a prompt.

Hands-on: a compressor and bill calculator you can run right now

The script below is stdlib only; python compact_budget.py runs it. It does three things: compress a simulated trajectory with structured decisions, verify tool_call pairing survived, and price the input tokens before and after using published rates -- plus the extra cost of doing one compaction pass on a frontier model.

# compact_budget.py - stdlib only. Run: python compact_budget.py
TOOL_HEAD = 400
TOOL_TAIL = 200
CHEAP_IN = 0.10       # USD per 1M input tokens, executor tier
FRONTIER_IN = 8.0     # USD per 1M input tokens, Fable 5.2 (Nov 2026)

def approx_tokens(s):
    return max(1, len(s) // 4)

def compress(messages):
    out, seen = [], set()
    for m in messages:
        role, text = m["role"], m["content"]
        if role in ("system", "user"):
            out.append(m)                          # KEEP: hard constraints
            continue
        if role == "tool":
            if len(text) > TOOL_HEAD + TOOL_TAIL:
                text = (text[:TOOL_HEAD] + " ...[trimmed]... "
                        + text[-TOOL_TAIL:])
            out.append({"role": role,
                        "tool_call_id": m["tool_call_id"],
                        "content": text})          # REPLACE, keep the id
            continue
        if m.get("tool_calls"):
            out.append(m)                          # KEEP: tool_call definitions
            continue
        key = (role, text[:80])
        if key in seen:
            continue                               # DROP: duplicate chatter
        seen.add(key)
        out.append(m)
    return out

def check_pairing(messages):
    calls = set()
    for m in messages:
        for c in m.get("tool_calls", []):
            calls.add(c["id"])
    results = {m["tool_call_id"] for m in messages if m["role"] == "tool"}
    orphan = results - calls
    if orphan:
        raise SystemExit("orphan tool results: " + repr(sorted(orphan)))
    return len(calls), len(results)

def make_trace():
    msgs = [
        {"role": "system", "content": "Keep the existing auth middleware. "
                                      "No new dependencies."},
        {"role": "user", "content": "Add user registration to this service."},
    ]
    for i in range(6):
        cid = "call_" + str(i)
        msgs.append({"role": "assistant", "content": "",
                     "tool_calls": [{"id": cid, "name": "read_file"}]})
        body = ("line " + str(i) + " of src/auth.py ") * 120
        if i == 5:
            body = body + "FAILED: assertion in test_registration"
        msgs.append({"role": "tool", "tool_call_id": cid, "content": body})
    chatter = "line 0 of src/auth.py " * 3
    msgs.append({"role": "assistant", "content": chatter})
    msgs.append({"role": "assistant", "content": chatter})
    return msgs

def bill(messages, label):
    n = sum(approx_tokens(m["content"]) for m in messages)
    print(label, "msgs=", len(messages), "tokens~", n,
          "input_usd~", round(n * CHEAP_IN / 1000000, 6))
    return n

raw = make_trace()
comp = compress(raw)
n_raw = bill(raw, "before")
n_comp = bill(comp, "after ")
print("retained:", round(100 * n_comp / n_raw, 2), "%")
print("paired tool_calls / tool results:", check_pairing(comp))
print("one frontier compaction pass costs ~USD",
      round(n_raw * FRONTIER_IN / 1000000, 4), "of input tokens alone")

Expect roughly 4,000 tokens before, about 1,000 after, retained around 24%, paired tool_calls / tool results: (6, 6), and about 0.032 USD on the last line. Do not drop the if m.get("tool_calls") branch in compress(): assistant messages carrying tool_calls often have empty content, so text-based dedup would delete them as duplicate chatter and leave the tool results orphaned -- the exact trap when rolling your own /compact. That last 0.032 USD is the point: the compactor's own token spend has to be an order of magnitude below what it saves, or the whole scheme runs at a loss.

Pin the model split in config, not in a prompt. Claude Code subagent definitions accept a model in frontmatter:

---
name: code-executor
description: Runs well-scoped edits from an approved plan.
model: haiku
---
You receive one self-contained plan. Edit only the listed files.

Add one hard pre-deploy check too: log every actual call, group tokens and cost by model, and confirm the cheap tier's share. Without that telemetry, "I assumed the subagents were on the cheap model" only shows up on the invoice at month end.

What makes aiXcompact-4B worth reading is not the 4B size. It is the move of pulling a high-frequency, well-bounded, structurally fixed side job out of the main model. REMORY and shadcn/improve are working the same problem: expensive tokens belong on judgment. As for the compression ratio, do not chase 18% -- first make sure the stack trace is still there and the tool_call ids still pair up.

Further reading

Commentaires

Ce site est uniquement frontal : pas de backend ni de compte. Les commentaires vont sur GitHub Issues, Discussions ou par e-mail.

Collez ceci dans l'issue ou l'e-mail pour m'aider à localiser le problème ; cela n'inclut rien de ce que vous avez saisi

Aussi :Voir les commentaires existants · Commentaires par e-mail (sans compte GitHub) :278975598@qq.com