tokenslim
Cut LLM agent token usage by ~72% in real scenarios — without changing your model and without a compressor model.
tokenslim composes the strongest open-source techniques for token reduction into one small, zero-dependency Python library + CLI: measure the waste, trim bulky tool outputs, compact old history, compress prompts, cache repeats, and budget a tight context window.
Goal
Verifiable savings, not claimed savings. Every number in this README comes from a runnable script in tests/ with a fact-recall check attached: compression only counts if the ERROR line, the trace ID, the amount, and the answer still survive. That is the whole point of the project — transparency you can re-run.
Real benchmark (exact tiktoken counting)
A realistic coding-agent transcript — 17 messages: system prompt, 3 tool schemas, varied tool outputs (grep, source file, pytest log, API JSON), one realistic re-read of the same file, 3 RAG chunks:
| Step | Tokens | Cumulative reduction |
|---|---|---|
| 0. raw transcript | 2,150 | — |
| 1. + cache repeated tool calls | 1,687 | −21.5% |
| 2. + truncate tool outputs (400 tok) | 1,622 | −24.6% |
| 3. + compress RAG chunks (rate 0.75) | 1,576 | −26.7% |
| 4. + compact history (budget 2,500) | 592 | −72.5% |
On pathological inputs (the same 5k-token log pasted 10×) the pipeline reaches ~98%, but 72.5% is the honest number for realistic work — your mileage depends on how much of your context is tool output. Run it yourself: python tests/benchmark_real.py.
Test suite: 42 unit tests (incl. 18 fact-recall tests that prove compressed output keeps load-bearing facts) + 12 stress tests (massive histories, 600 KB single-line dumps, deep JSON, Unicode, cache precision under 2000 lookups, adversarial compression) + 112 adversarial cases (106 PASS / 0 FAIL / 6 by-design OBSERVE — contradictory values and no-signal rows are kept on purpose) — all passing in CI.
Head-to-head vs Headroom (measured 2026-11-28, same inputs, same tiktoken counter)
Headroom is the strongest tool in this space (~81k stars) and deserves a fair comparison. Run it yourself: python tests/benchmark_headroom.py (needs pip install headroom-ai).
| Scenario | TokenSlim | Headroom |
|---|---|---|
| Coding session, 40 turns, buried ERROR line (179,631 tok) | 2,965 (−98.3%), 5/5 facts | 57,111 (−68.2%), 5/5 facts |
| RAG, 12 chunks, 2 answer it (3,125 tok) | 1,128 (−63.9%), 2/2 facts | 3,125 (−0.0%), 2/2 facts |
Honest reading: on English logs Headroom keeps the facts too — including the buried ERROR line. TokenSlim's edge is depth of savings on the same input (98% vs 68%), and one place where Headroom's routers do nothing at all: small messages under its 250-token floor. TokenSlim's 98% figures still include history compaction (old turns deleted) — the 5/5 fact checks are what make the number meaningful. Headroom's ML text compressor (261 MB ONNX model) did not run in this environment, so this compares its heuristic routers only.
On a larger 55-fact table (same method, tests/benchmark_headroom_own_extended.py): TokenSlim kept 55/55 facts at −97.9% (353,523 → 7,522 tokens); Headroom kept 52/55 at −41.7%. All three Headroom misses are the same systematic drop (an fs-search path fact).
On a 24-question accuracy eval (single run per model, two models — small eval, stated plainly): raw context, TokenSlim and Headroom all scored 23/24 — TokenSlim matches them, it does not beat them — while using −73.9% average context tokens vs raw (386 vs 1,476). Reproduce with python tests/accuracy_eval.py --rescore.
Techniques and their origins
| Technique | Module | Inspired by |
|---|---|---|
| Prompt compression (filler/stopword/redundancy cuts, protects code & terms) | compressor.compress() |
microsoft/LLMLingua (EMNLP'23) |
| History compaction (elide old tool results, summarize old turns) | compactor.compact_history() |
letta-ai/letta (MemGPT) |
| Tool-output trimming (head+tail text, JSON arrays/strings, logs) | truncator.* |
token-optimization repos (topic) |
| Response caching (exact + fuzzy Jaccard, no embeddings) | cache.TokenCache |
GPTCache |
| Context budgeting (score-per-token greedy selection) | budget.select() |
LangChain-style memory budgets |
| Token auditing (where do the tokens go? + suggestions) | audit.audit() |
GitHub Agentic Workflows guide |
Install
pip install . # zero required dependencies
pip install ".[exact]" # optional: exact tiktoken counting (downloads encoding on first use)
Offline or air-gapped? Export TOKENSLIM_NO_TIKTOKEN=1 to force the chars/4 estimator — everything works, ratios stay identical.
Quickstart
from tokenslim import audit, suggestions, truncate_text, compact_history, compress
# 1. Measure first — where do the tokens go?
report = audit(messages) # OpenAI-style message list
for tip in suggestions(report):
print(tip)
# 2. Trim bulky tool outputs
for m in messages:
if m["role"] == "tool":
m["content"] = truncate_text(m["content"], max_tokens=400)
# 3. Compact old history, keep the recent tail verbatim
messages, saved = compact_history(messages, max_tokens=8000, keep_recent=6)
# 4. Compress prompts (LLMLingua-style, no model needed)
short = compress(prompt, rate=0.7, protected={"OAuth", "my_api_key"})
Cache repeated calls
from tokenslim import TokenCache
cache = TokenCache(threshold=0.75)
hit = cache.get(prompt)
if hit is None:
hit = call_llm(prompt)
cache.put(prompt, hit)
cache.stats() # {"hits": 3, "misses": 1, "saved_tokens": 412, "entries": 4}
Budget a tight context window
from tokenslim import allocate, select
budget = allocate(128000) # system 10%, tools 15%, history 50%, retrieval 25%
kept, dropped = select(rag_chunks, budget["retrieval"]) # keeps best score-per-token
CLI
tokenslim stats big_prompt.txt
tokenslim compress prompt.txt --rate 0.6
tokenslim trim server.log --max-tokens 400 # or --lines 100
tokenslim audit messages.json # waste report + suggestions
Design notes
- Zero required dependencies — falls back to a chars/4 token estimator when tiktoken is absent.
- Deterministic — compression and compaction are reproducible; easy to test and diff.
- Measure → cut —
audit()exists because the biggest waste is usually one or two repeated tool dumps, not the prompt. - Model-free, upgradeable — wrap LLMLingua-2 for stronger compression and plug an LLM summarizer into
compact_history(summarizer=...)without changing call sites. - Budget guarantees — compaction always terminates and always fits the requested budget (fuzz-tested with 12 adversarial stress cases).
Test
pip install -e .
TOKENSLIM_NO_TIKTOKEN=1 python -m unittest discover -s tests -v # fast, offline
python tests/stress_test.py # 12 stress cases
python tests/benchmark_real.py # realistic benchmark
Roadmap
- Optional LLMLingua-2 backend for model-grade compression
- LiteLLM / OpenAI SDK middleware (drop-in request rewriting)
- MCP server exposing tokenslim as a tool
- Semantic cache with optional embedding backend
Contributing
See CONTRIBUTING.md. PRs welcome.
License
MIT — see LICENSE.
Metadata
Release files for tokenslim-py 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| tokenslim_py-0.1.0.tar.gz | 77.0 kB | With provenance | Details for tokenslim_py-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| tokenslim_py-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for tokenslim_py-0.1.0-py3-none-any.whl |
Total release size: 124.4 kB
Release files / tokenslim_py-0.1.0.tar.gz
| Download URL | tokenslim_py-0.1.0.tar.gz |
|---|---|
| Size | 77.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d1d12a748ada6973aa3ace3c7508d625d3c81925831ef7b5a90f6f27d44e5cdb
|
|
BLAKE2b-256 checksum How to use checksums |
46f1da67790bc8ce793745a922980b2bbd573af82e2b7977ae4ac56eb8a8aac5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.
Transparency logRelease files / tokenslim_py-0.1.0-py3-none-any.whl
| Download URL | tokenslim_py-0.1.0-py3-none-any.whl |
|---|---|
| Size | 47.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
984e2171af0075769df0a2483dac6329d80885c0604943abcd13fa4cbaaa7211
|
|
BLAKE2b-256 checksum How to use checksums |
1a22a9b73c791da3bde092b44c467c9e4fd2ec62ac7258dee61fe93c2c139ecb
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.
Transparency logSecurity for tokenslim-py 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for tokenslim_py-0.1.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.