Metadata-Version: 2.4
Name: tokenslim-py
Version: 0.1.0
Summary: Reduce LLM agent token usage: compress prompts, truncate tool output, compact history, cache responses, and budget the context window.
Author: kamal
License: MIT
Project-URL: Homepage, https://github.com/kamalmosadegh/tokenslim
Project-URL: Repository, https://github.com/kamalmosadegh/tokenslim
Project-URL: Changelog, https://github.com/kamalmosadegh/tokenslim/blob/main/CHANGELOG.md
Project-URL: Issues, https://github.com/kamalmosadegh/tokenslim/issues
Keywords: llm,agents,tokens,context-window,prompt-compression,ai-cost
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: exact
Requires-Dist: tiktoken>=0.5; extra == "exact"
Dynamic: license-file

# tokenslim

[![CI](https://github.com/kamalmosadegh/tokenslim/actions/workflows/ci.yml/badge.svg)](https://github.com/kamalmosadegh/tokenslim/actions/workflows/ci.yml)
![Python](https://img.shields.io/badge/python-3.9%20%7C%203.10%20%7C%203.11%20%7C%203.12-blue)
![License](https://img.shields.io/badge/license-MIT-green)
![Dependencies](https://img.shields.io/badge/dependencies-0-brightgreen)

**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](https://github.com/microsoft/llmlingua) (EMNLP'23) |
| History compaction (elide old tool results, summarize old turns) | `compactor.compact_history()` | [letta-ai/letta](https://github.com/letta-ai/letta) (MemGPT) |
| Tool-output trimming (head+tail text, JSON arrays/strings, logs) | `truncator.*` | token-optimization repos ([topic](https://github.com/topics/token-optimization)) |
| Response caching (exact + fuzzy Jaccard, no embeddings) | `cache.TokenCache` | [GPTCache](https://github.com/zilliztech/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](https://github.blog/ai-and-ml/github-copilot/improving-token-efficiency-in-github-agentic-workflows/) |

## Install

```bash
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

```python
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

```python
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

```python
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

```bash
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](https://github.com/microsoft/llmlingua) 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

```bash
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](CONTRIBUTING.md). PRs welcome.

## License

MIT — see [LICENSE](LICENSE).
