tokenslim-py 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tokenslim_py-0.1.0/LICENSE +21 -0
- tokenslim_py-0.1.0/PKG-INFO +168 -0
- tokenslim_py-0.1.0/README.md +150 -0
- tokenslim_py-0.1.0/pyproject.toml +32 -0
- tokenslim_py-0.1.0/setup.cfg +4 -0
- tokenslim_py-0.1.0/src/tokenslim/__init__.py +47 -0
- tokenslim_py-0.1.0/src/tokenslim/audit.py +87 -0
- tokenslim_py-0.1.0/src/tokenslim/budget.py +49 -0
- tokenslim_py-0.1.0/src/tokenslim/cache.py +75 -0
- tokenslim_py-0.1.0/src/tokenslim/cli.py +73 -0
- tokenslim_py-0.1.0/src/tokenslim/compactor.py +267 -0
- tokenslim_py-0.1.0/src/tokenslim/compressor.py +128 -0
- tokenslim_py-0.1.0/src/tokenslim/counter.py +56 -0
- tokenslim_py-0.1.0/src/tokenslim/py.typed +0 -0
- tokenslim_py-0.1.0/src/tokenslim/smart.py +1783 -0
- tokenslim_py-0.1.0/src/tokenslim/truncator.py +61 -0
- tokenslim_py-0.1.0/src/tokenslim_py.egg-info/PKG-INFO +168 -0
- tokenslim_py-0.1.0/src/tokenslim_py.egg-info/SOURCES.txt +25 -0
- tokenslim_py-0.1.0/src/tokenslim_py.egg-info/dependency_links.txt +1 -0
- tokenslim_py-0.1.0/src/tokenslim_py.egg-info/entry_points.txt +2 -0
- tokenslim_py-0.1.0/src/tokenslim_py.egg-info/requires.txt +3 -0
- tokenslim_py-0.1.0/src/tokenslim_py.egg-info/top_level.txt +1 -0
- tokenslim_py-0.1.0/tests/test_adversarial.py +1224 -0
- tokenslim_py-0.1.0/tests/test_fact_recall.py +488 -0
- tokenslim_py-0.1.0/tests/test_json_trim.py +117 -0
- tokenslim_py-0.1.0/tests/test_strong.py +251 -0
- tokenslim_py-0.1.0/tests/test_tokenslim.py +160 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 tokenslim contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tokenslim-py
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Reduce LLM agent token usage: compress prompts, truncate tool output, compact history, cache responses, and budget the context window.
|
|
5
|
+
Author: kamal
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/kamalmosadegh/tokenslim
|
|
8
|
+
Project-URL: Repository, https://github.com/kamalmosadegh/tokenslim
|
|
9
|
+
Project-URL: Changelog, https://github.com/kamalmosadegh/tokenslim/blob/main/CHANGELOG.md
|
|
10
|
+
Project-URL: Issues, https://github.com/kamalmosadegh/tokenslim/issues
|
|
11
|
+
Keywords: llm,agents,tokens,context-window,prompt-compression,ai-cost
|
|
12
|
+
Requires-Python: >=3.9
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Provides-Extra: exact
|
|
16
|
+
Requires-Dist: tiktoken>=0.5; extra == "exact"
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# tokenslim
|
|
20
|
+
|
|
21
|
+
[](https://github.com/kamalmosadegh/tokenslim/actions/workflows/ci.yml)
|
|
22
|
+

|
|
23
|
+

|
|
24
|
+

|
|
25
|
+
|
|
26
|
+
**Cut LLM agent token usage by ~72% in real scenarios — without changing your model and without a compressor model.**
|
|
27
|
+
|
|
28
|
+
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.
|
|
29
|
+
|
|
30
|
+
## Goal
|
|
31
|
+
|
|
32
|
+
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.
|
|
33
|
+
|
|
34
|
+
## Real benchmark (exact tiktoken counting)
|
|
35
|
+
|
|
36
|
+
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:
|
|
37
|
+
|
|
38
|
+
| Step | Tokens | Cumulative reduction |
|
|
39
|
+
|---|---:|---:|
|
|
40
|
+
| 0. raw transcript | 2,150 | — |
|
|
41
|
+
| 1. + cache repeated tool calls | 1,687 | −21.5% |
|
|
42
|
+
| 2. + truncate tool outputs (400 tok) | 1,622 | −24.6% |
|
|
43
|
+
| 3. + compress RAG chunks (rate 0.75) | 1,576 | −26.7% |
|
|
44
|
+
| 4. + compact history (budget 2,500) | **592** | **−72.5%** |
|
|
45
|
+
|
|
46
|
+
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`.
|
|
47
|
+
|
|
48
|
+
**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.
|
|
49
|
+
|
|
50
|
+
### Head-to-head vs Headroom (measured 2026-11-28, same inputs, same tiktoken counter)
|
|
51
|
+
|
|
52
|
+
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`).
|
|
53
|
+
|
|
54
|
+
| Scenario | TokenSlim | Headroom |
|
|
55
|
+
|---|---|---|
|
|
56
|
+
| Coding session, 40 turns, buried ERROR line (179,631 tok) | 2,965 (−98.3%), 5/5 facts | 57,111 (−68.2%), 5/5 facts |
|
|
57
|
+
| RAG, 12 chunks, 2 answer it (3,125 tok) | 1,128 (−63.9%), 2/2 facts | 3,125 (−0.0%), 2/2 facts |
|
|
58
|
+
|
|
59
|
+
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.
|
|
60
|
+
|
|
61
|
+
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).
|
|
62
|
+
|
|
63
|
+
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`.
|
|
64
|
+
|
|
65
|
+
## Techniques and their origins
|
|
66
|
+
|
|
67
|
+
| Technique | Module | Inspired by |
|
|
68
|
+
|---|---|---|
|
|
69
|
+
| Prompt compression (filler/stopword/redundancy cuts, protects code & terms) | `compressor.compress()` | [microsoft/LLMLingua](https://github.com/microsoft/llmlingua) (EMNLP'23) |
|
|
70
|
+
| History compaction (elide old tool results, summarize old turns) | `compactor.compact_history()` | [letta-ai/letta](https://github.com/letta-ai/letta) (MemGPT) |
|
|
71
|
+
| Tool-output trimming (head+tail text, JSON arrays/strings, logs) | `truncator.*` | token-optimization repos ([topic](https://github.com/topics/token-optimization)) |
|
|
72
|
+
| Response caching (exact + fuzzy Jaccard, no embeddings) | `cache.TokenCache` | [GPTCache](https://github.com/zilliztech/GPTCache) |
|
|
73
|
+
| Context budgeting (score-per-token greedy selection) | `budget.select()` | LangChain-style memory budgets |
|
|
74
|
+
| 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/) |
|
|
75
|
+
|
|
76
|
+
## Install
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
pip install . # zero required dependencies
|
|
80
|
+
pip install ".[exact]" # optional: exact tiktoken counting (downloads encoding on first use)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Offline or air-gapped? Export `TOKENSLIM_NO_TIKTOKEN=1` to force the chars/4 estimator — everything works, ratios stay identical.
|
|
84
|
+
|
|
85
|
+
## Quickstart
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
from tokenslim import audit, suggestions, truncate_text, compact_history, compress
|
|
89
|
+
|
|
90
|
+
# 1. Measure first — where do the tokens go?
|
|
91
|
+
report = audit(messages) # OpenAI-style message list
|
|
92
|
+
for tip in suggestions(report):
|
|
93
|
+
print(tip)
|
|
94
|
+
|
|
95
|
+
# 2. Trim bulky tool outputs
|
|
96
|
+
for m in messages:
|
|
97
|
+
if m["role"] == "tool":
|
|
98
|
+
m["content"] = truncate_text(m["content"], max_tokens=400)
|
|
99
|
+
|
|
100
|
+
# 3. Compact old history, keep the recent tail verbatim
|
|
101
|
+
messages, saved = compact_history(messages, max_tokens=8000, keep_recent=6)
|
|
102
|
+
|
|
103
|
+
# 4. Compress prompts (LLMLingua-style, no model needed)
|
|
104
|
+
short = compress(prompt, rate=0.7, protected={"OAuth", "my_api_key"})
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### Cache repeated calls
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
from tokenslim import TokenCache
|
|
111
|
+
|
|
112
|
+
cache = TokenCache(threshold=0.75)
|
|
113
|
+
hit = cache.get(prompt)
|
|
114
|
+
if hit is None:
|
|
115
|
+
hit = call_llm(prompt)
|
|
116
|
+
cache.put(prompt, hit)
|
|
117
|
+
cache.stats() # {"hits": 3, "misses": 1, "saved_tokens": 412, "entries": 4}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### Budget a tight context window
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
from tokenslim import allocate, select
|
|
124
|
+
|
|
125
|
+
budget = allocate(128000) # system 10%, tools 15%, history 50%, retrieval 25%
|
|
126
|
+
kept, dropped = select(rag_chunks, budget["retrieval"]) # keeps best score-per-token
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
## CLI
|
|
130
|
+
|
|
131
|
+
```bash
|
|
132
|
+
tokenslim stats big_prompt.txt
|
|
133
|
+
tokenslim compress prompt.txt --rate 0.6
|
|
134
|
+
tokenslim trim server.log --max-tokens 400 # or --lines 100
|
|
135
|
+
tokenslim audit messages.json # waste report + suggestions
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
## Design notes
|
|
139
|
+
|
|
140
|
+
- **Zero required dependencies** — falls back to a chars/4 token estimator when tiktoken is absent.
|
|
141
|
+
- **Deterministic** — compression and compaction are reproducible; easy to test and diff.
|
|
142
|
+
- **Measure → cut** — `audit()` exists because the biggest waste is usually one or two repeated tool dumps, not the prompt.
|
|
143
|
+
- **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.
|
|
144
|
+
- **Budget guarantees** — compaction always terminates and always fits the requested budget (fuzz-tested with 12 adversarial stress cases).
|
|
145
|
+
|
|
146
|
+
## Test
|
|
147
|
+
|
|
148
|
+
```bash
|
|
149
|
+
pip install -e .
|
|
150
|
+
TOKENSLIM_NO_TIKTOKEN=1 python -m unittest discover -s tests -v # fast, offline
|
|
151
|
+
python tests/stress_test.py # 12 stress cases
|
|
152
|
+
python tests/benchmark_real.py # realistic benchmark
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
## Roadmap
|
|
156
|
+
|
|
157
|
+
- [ ] Optional LLMLingua-2 backend for model-grade compression
|
|
158
|
+
- [ ] LiteLLM / OpenAI SDK middleware (drop-in request rewriting)
|
|
159
|
+
- [ ] MCP server exposing tokenslim as a tool
|
|
160
|
+
- [ ] Semantic cache with optional embedding backend
|
|
161
|
+
|
|
162
|
+
## Contributing
|
|
163
|
+
|
|
164
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md). PRs welcome.
|
|
165
|
+
|
|
166
|
+
## License
|
|
167
|
+
|
|
168
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
# tokenslim
|
|
2
|
+
|
|
3
|
+
[](https://github.com/kamalmosadegh/tokenslim/actions/workflows/ci.yml)
|
|
4
|
+

|
|
5
|
+

|
|
6
|
+

|
|
7
|
+
|
|
8
|
+
**Cut LLM agent token usage by ~72% in real scenarios — without changing your model and without a compressor model.**
|
|
9
|
+
|
|
10
|
+
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.
|
|
11
|
+
|
|
12
|
+
## Goal
|
|
13
|
+
|
|
14
|
+
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.
|
|
15
|
+
|
|
16
|
+
## Real benchmark (exact tiktoken counting)
|
|
17
|
+
|
|
18
|
+
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:
|
|
19
|
+
|
|
20
|
+
| Step | Tokens | Cumulative reduction |
|
|
21
|
+
|---|---:|---:|
|
|
22
|
+
| 0. raw transcript | 2,150 | — |
|
|
23
|
+
| 1. + cache repeated tool calls | 1,687 | −21.5% |
|
|
24
|
+
| 2. + truncate tool outputs (400 tok) | 1,622 | −24.6% |
|
|
25
|
+
| 3. + compress RAG chunks (rate 0.75) | 1,576 | −26.7% |
|
|
26
|
+
| 4. + compact history (budget 2,500) | **592** | **−72.5%** |
|
|
27
|
+
|
|
28
|
+
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`.
|
|
29
|
+
|
|
30
|
+
**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.
|
|
31
|
+
|
|
32
|
+
### Head-to-head vs Headroom (measured 2026-11-28, same inputs, same tiktoken counter)
|
|
33
|
+
|
|
34
|
+
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`).
|
|
35
|
+
|
|
36
|
+
| Scenario | TokenSlim | Headroom |
|
|
37
|
+
|---|---|---|
|
|
38
|
+
| Coding session, 40 turns, buried ERROR line (179,631 tok) | 2,965 (−98.3%), 5/5 facts | 57,111 (−68.2%), 5/5 facts |
|
|
39
|
+
| RAG, 12 chunks, 2 answer it (3,125 tok) | 1,128 (−63.9%), 2/2 facts | 3,125 (−0.0%), 2/2 facts |
|
|
40
|
+
|
|
41
|
+
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.
|
|
42
|
+
|
|
43
|
+
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).
|
|
44
|
+
|
|
45
|
+
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`.
|
|
46
|
+
|
|
47
|
+
## Techniques and their origins
|
|
48
|
+
|
|
49
|
+
| Technique | Module | Inspired by |
|
|
50
|
+
|---|---|---|
|
|
51
|
+
| Prompt compression (filler/stopword/redundancy cuts, protects code & terms) | `compressor.compress()` | [microsoft/LLMLingua](https://github.com/microsoft/llmlingua) (EMNLP'23) |
|
|
52
|
+
| History compaction (elide old tool results, summarize old turns) | `compactor.compact_history()` | [letta-ai/letta](https://github.com/letta-ai/letta) (MemGPT) |
|
|
53
|
+
| Tool-output trimming (head+tail text, JSON arrays/strings, logs) | `truncator.*` | token-optimization repos ([topic](https://github.com/topics/token-optimization)) |
|
|
54
|
+
| Response caching (exact + fuzzy Jaccard, no embeddings) | `cache.TokenCache` | [GPTCache](https://github.com/zilliztech/GPTCache) |
|
|
55
|
+
| Context budgeting (score-per-token greedy selection) | `budget.select()` | LangChain-style memory budgets |
|
|
56
|
+
| 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/) |
|
|
57
|
+
|
|
58
|
+
## Install
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
pip install . # zero required dependencies
|
|
62
|
+
pip install ".[exact]" # optional: exact tiktoken counting (downloads encoding on first use)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Offline or air-gapped? Export `TOKENSLIM_NO_TIKTOKEN=1` to force the chars/4 estimator — everything works, ratios stay identical.
|
|
66
|
+
|
|
67
|
+
## Quickstart
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from tokenslim import audit, suggestions, truncate_text, compact_history, compress
|
|
71
|
+
|
|
72
|
+
# 1. Measure first — where do the tokens go?
|
|
73
|
+
report = audit(messages) # OpenAI-style message list
|
|
74
|
+
for tip in suggestions(report):
|
|
75
|
+
print(tip)
|
|
76
|
+
|
|
77
|
+
# 2. Trim bulky tool outputs
|
|
78
|
+
for m in messages:
|
|
79
|
+
if m["role"] == "tool":
|
|
80
|
+
m["content"] = truncate_text(m["content"], max_tokens=400)
|
|
81
|
+
|
|
82
|
+
# 3. Compact old history, keep the recent tail verbatim
|
|
83
|
+
messages, saved = compact_history(messages, max_tokens=8000, keep_recent=6)
|
|
84
|
+
|
|
85
|
+
# 4. Compress prompts (LLMLingua-style, no model needed)
|
|
86
|
+
short = compress(prompt, rate=0.7, protected={"OAuth", "my_api_key"})
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### Cache repeated calls
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
from tokenslim import TokenCache
|
|
93
|
+
|
|
94
|
+
cache = TokenCache(threshold=0.75)
|
|
95
|
+
hit = cache.get(prompt)
|
|
96
|
+
if hit is None:
|
|
97
|
+
hit = call_llm(prompt)
|
|
98
|
+
cache.put(prompt, hit)
|
|
99
|
+
cache.stats() # {"hits": 3, "misses": 1, "saved_tokens": 412, "entries": 4}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Budget a tight context window
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
from tokenslim import allocate, select
|
|
106
|
+
|
|
107
|
+
budget = allocate(128000) # system 10%, tools 15%, history 50%, retrieval 25%
|
|
108
|
+
kept, dropped = select(rag_chunks, budget["retrieval"]) # keeps best score-per-token
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## CLI
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
tokenslim stats big_prompt.txt
|
|
115
|
+
tokenslim compress prompt.txt --rate 0.6
|
|
116
|
+
tokenslim trim server.log --max-tokens 400 # or --lines 100
|
|
117
|
+
tokenslim audit messages.json # waste report + suggestions
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## Design notes
|
|
121
|
+
|
|
122
|
+
- **Zero required dependencies** — falls back to a chars/4 token estimator when tiktoken is absent.
|
|
123
|
+
- **Deterministic** — compression and compaction are reproducible; easy to test and diff.
|
|
124
|
+
- **Measure → cut** — `audit()` exists because the biggest waste is usually one or two repeated tool dumps, not the prompt.
|
|
125
|
+
- **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.
|
|
126
|
+
- **Budget guarantees** — compaction always terminates and always fits the requested budget (fuzz-tested with 12 adversarial stress cases).
|
|
127
|
+
|
|
128
|
+
## Test
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
pip install -e .
|
|
132
|
+
TOKENSLIM_NO_TIKTOKEN=1 python -m unittest discover -s tests -v # fast, offline
|
|
133
|
+
python tests/stress_test.py # 12 stress cases
|
|
134
|
+
python tests/benchmark_real.py # realistic benchmark
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
## Roadmap
|
|
138
|
+
|
|
139
|
+
- [ ] Optional LLMLingua-2 backend for model-grade compression
|
|
140
|
+
- [ ] LiteLLM / OpenAI SDK middleware (drop-in request rewriting)
|
|
141
|
+
- [ ] MCP server exposing tokenslim as a tool
|
|
142
|
+
- [ ] Semantic cache with optional embedding backend
|
|
143
|
+
|
|
144
|
+
## Contributing
|
|
145
|
+
|
|
146
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md). PRs welcome.
|
|
147
|
+
|
|
148
|
+
## License
|
|
149
|
+
|
|
150
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "tokenslim-py"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Reduce LLM agent token usage: compress prompts, truncate tool output, compact history, cache responses, and budget the context window."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "kamal" }]
|
|
13
|
+
keywords = ["llm", "agents", "tokens", "context-window", "prompt-compression", "ai-cost"]
|
|
14
|
+
dependencies = [] # tiktoken is optional; falls back to a chars/4 estimator
|
|
15
|
+
|
|
16
|
+
[project.optional-dependencies]
|
|
17
|
+
exact = ["tiktoken>=0.5"]
|
|
18
|
+
|
|
19
|
+
[project.urls]
|
|
20
|
+
Homepage = "https://github.com/kamalmosadegh/tokenslim"
|
|
21
|
+
Repository = "https://github.com/kamalmosadegh/tokenslim"
|
|
22
|
+
Changelog = "https://github.com/kamalmosadegh/tokenslim/blob/main/CHANGELOG.md"
|
|
23
|
+
Issues = "https://github.com/kamalmosadegh/tokenslim/issues"
|
|
24
|
+
|
|
25
|
+
[project.scripts]
|
|
26
|
+
tokenslim = "tokenslim.cli:main"
|
|
27
|
+
|
|
28
|
+
[tool.setuptools.packages.find]
|
|
29
|
+
where = ["src"]
|
|
30
|
+
|
|
31
|
+
[tool.setuptools.package-data]
|
|
32
|
+
tokenslim = ["py.typed"]
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""tokenslim — cut agent token usage without an extra model.
|
|
2
|
+
|
|
3
|
+
Composes the best techniques from LLMLingua (prompt compression),
|
|
4
|
+
Letta/MemGPT (history compaction), GPTCache (response caching) and the
|
|
5
|
+
token-optimization repos (tool-output trimming), plus budgeting and audit.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from .audit import audit, suggestions
|
|
9
|
+
from .budget import allocate, fit_text, select
|
|
10
|
+
from .cache import TokenCache
|
|
11
|
+
from .compactor import compact_history, elide_old_tool_results, summarize_text
|
|
12
|
+
from .compressor import compress
|
|
13
|
+
from .counter import count_messages, count_tokens
|
|
14
|
+
from .smart import (
|
|
15
|
+
collapse_whitespace,
|
|
16
|
+
fact_aware_summary,
|
|
17
|
+
rank_chunks,
|
|
18
|
+
smart_pipeline,
|
|
19
|
+
smart_truncate,
|
|
20
|
+
)
|
|
21
|
+
from .truncator import dump_compact, truncate_json, truncate_lines, truncate_text
|
|
22
|
+
|
|
23
|
+
__version__ = "0.1.0"
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"audit",
|
|
27
|
+
"suggestions",
|
|
28
|
+
"allocate",
|
|
29
|
+
"fit_text",
|
|
30
|
+
"select",
|
|
31
|
+
"TokenCache",
|
|
32
|
+
"compact_history",
|
|
33
|
+
"elide_old_tool_results",
|
|
34
|
+
"summarize_text",
|
|
35
|
+
"compress",
|
|
36
|
+
"count_tokens",
|
|
37
|
+
"count_messages",
|
|
38
|
+
"collapse_whitespace",
|
|
39
|
+
"fact_aware_summary",
|
|
40
|
+
"rank_chunks",
|
|
41
|
+
"smart_pipeline",
|
|
42
|
+
"smart_truncate",
|
|
43
|
+
"dump_compact",
|
|
44
|
+
"truncate_json",
|
|
45
|
+
"truncate_lines",
|
|
46
|
+
"truncate_text",
|
|
47
|
+
]
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Token auditing: find where the tokens actually go before cutting anything.
|
|
2
|
+
|
|
3
|
+
Inspired by GitHub's "Daily Token Usage Auditor" pattern from the Agentic
|
|
4
|
+
Workflows blog post — measure first, then optimize what's actually big.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from collections import Counter
|
|
11
|
+
|
|
12
|
+
from .counter import count_messages, count_tokens
|
|
13
|
+
|
|
14
|
+
_WS_RUNS = re.compile(r"[ \t]{2,}")
|
|
15
|
+
_NL_RUNS = re.compile(r"\n{2,}")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def audit(messages: list, tools: list = None) -> dict:
|
|
19
|
+
"""Profile an OpenAI-style message list and surface waste.
|
|
20
|
+
|
|
21
|
+
tools: optional list of tool schemas (dicts) sent with every request.
|
|
22
|
+
"""
|
|
23
|
+
by_role = Counter()
|
|
24
|
+
largest = []
|
|
25
|
+
tool_tokens = 0
|
|
26
|
+
whitespace_waste = 0
|
|
27
|
+
contents = []
|
|
28
|
+
|
|
29
|
+
for i, m in enumerate(messages):
|
|
30
|
+
content = str(m.get("content", ""))
|
|
31
|
+
n = count_tokens(content) + 4
|
|
32
|
+
by_role[m.get("role", "?")] += n
|
|
33
|
+
largest.append((n, i, m.get("role", "?")))
|
|
34
|
+
if m.get("role") == "tool":
|
|
35
|
+
tool_tokens += n
|
|
36
|
+
stripped = _NL_RUNS.sub("\n", _WS_RUNS.sub(" ", content))
|
|
37
|
+
whitespace_waste += count_tokens(content) - count_tokens(stripped)
|
|
38
|
+
contents.append(content)
|
|
39
|
+
|
|
40
|
+
duplicate_tool_outputs = 0
|
|
41
|
+
seen = set()
|
|
42
|
+
for c in contents:
|
|
43
|
+
key = c.strip()
|
|
44
|
+
if len(key) > 80: # only bulky outputs matter
|
|
45
|
+
if key in seen:
|
|
46
|
+
duplicate_tool_outputs += 1
|
|
47
|
+
seen.add(key)
|
|
48
|
+
|
|
49
|
+
tool_schema_tokens = sum(count_tokens(str(t)) for t in (tools or []))
|
|
50
|
+
largest.sort(reverse=True)
|
|
51
|
+
|
|
52
|
+
report = {
|
|
53
|
+
"total_tokens": count_messages(messages) + tool_schema_tokens,
|
|
54
|
+
"by_role": dict(by_role),
|
|
55
|
+
"tool_result_tokens": tool_tokens,
|
|
56
|
+
"tool_schema_tokens": tool_schema_tokens,
|
|
57
|
+
"largest_messages": largest[:5],
|
|
58
|
+
"whitespace_waste_tokens": whitespace_waste,
|
|
59
|
+
"duplicate_tool_outputs": duplicate_tool_outputs,
|
|
60
|
+
"message_count": len(messages),
|
|
61
|
+
}
|
|
62
|
+
return report
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def suggestions(report: dict) -> list:
|
|
66
|
+
"""Actionable cuts, biggest win first."""
|
|
67
|
+
tips, total = [], report["total_tokens"]
|
|
68
|
+
if report["tool_result_tokens"] > total * 0.3:
|
|
69
|
+
tips.append(
|
|
70
|
+
"tool results are {:.0f}% of context — run truncator.truncate_text / "
|
|
71
|
+
"elide_old_tool_results".format(100 * report["tool_result_tokens"] / total)
|
|
72
|
+
)
|
|
73
|
+
if report["tool_schema_tokens"] > total * 0.15:
|
|
74
|
+
tips.append(
|
|
75
|
+
"tool schemas are {:.0f}% — send only the tools the current step needs".format(
|
|
76
|
+
100 * report["tool_schema_tokens"] / total
|
|
77
|
+
)
|
|
78
|
+
)
|
|
79
|
+
if report["whitespace_waste_tokens"] > total * 0.05:
|
|
80
|
+
tips.append("repeated whitespace/newlines waste ~{} tokens — collapse them".format(report["whitespace_waste_tokens"]))
|
|
81
|
+
if report["duplicate_tool_outputs"]:
|
|
82
|
+
tips.append("{} duplicate tool outputs detected — cache them with TokenCache".format(report["duplicate_tool_outputs"]))
|
|
83
|
+
if report["message_count"] > 40:
|
|
84
|
+
tips.append("{} messages — compact_history will summarize the old tail".format(report["message_count"]))
|
|
85
|
+
if not tips:
|
|
86
|
+
tips.append("context looks lean — nothing obvious to cut")
|
|
87
|
+
return tips
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Context budgeting: decide what survives when the window is tight."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .counter import count_tokens
|
|
6
|
+
|
|
7
|
+
DEFAULT_WEIGHTS = {"system": 0.10, "tools": 0.15, "history": 0.50, "retrieval": 0.25}
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def allocate(total_tokens: int, weights: dict = None) -> dict:
|
|
11
|
+
"""Split a context budget across sections (fractions are renormalized)."""
|
|
12
|
+
weights = weights or DEFAULT_WEIGHTS
|
|
13
|
+
total = sum(weights.values())
|
|
14
|
+
return {k: int(total_tokens * v / total) for k, v in weights.items()}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def select(items: list, budget: int, score_fn=None):
|
|
18
|
+
"""Greedily keep the best items that fit ``budget`` tokens.
|
|
19
|
+
|
|
20
|
+
items: dicts with ``tokens`` and ``score`` keys (plus whatever you like).
|
|
21
|
+
score_fn: optional callable(item) -> float overriding item["score"].
|
|
22
|
+
Returns ``(kept, dropped)``.
|
|
23
|
+
|
|
24
|
+
Rank is score-per-token, so short high-value items (a schema, a key fact)
|
|
25
|
+
beat long medium-value dumps. Scores are usually relevance 0..1 from
|
|
26
|
+
your retriever; count_tokens is used when ``tokens`` is missing.
|
|
27
|
+
"""
|
|
28
|
+
rank = sorted(
|
|
29
|
+
items,
|
|
30
|
+
key=lambda it: (score_fn(it) if score_fn else it.get("score", 0.0))
|
|
31
|
+
/ max(it.get("tokens", count_tokens(str(it.get("payload", "")))), 1),
|
|
32
|
+
reverse=True,
|
|
33
|
+
)
|
|
34
|
+
kept, used = [], 0
|
|
35
|
+
for it in rank:
|
|
36
|
+
t = it.get("tokens", count_tokens(str(it.get("payload", ""))))
|
|
37
|
+
if used + t <= budget:
|
|
38
|
+
kept.append(it)
|
|
39
|
+
used += t
|
|
40
|
+
kept_ids = {id(it) for it in kept}
|
|
41
|
+
dropped = [it for it in rank if id(it) not in kept_ids]
|
|
42
|
+
return kept, dropped
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def fit_text(text: str, max_tokens: int) -> str:
|
|
46
|
+
"""Return text unchanged if it fits; truncate via head+tail if not."""
|
|
47
|
+
from .truncator import truncate_text
|
|
48
|
+
|
|
49
|
+
return text if count_tokens(text) <= max_tokens else truncate_text(text, max_tokens)
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Prompt/response caching, inspired by GPTCache.
|
|
2
|
+
|
|
3
|
+
Repeated (or near-repeated) prompts don't need another paid inference.
|
|
4
|
+
Exact match plus Jaccard similarity over word 3-grams gives a fuzzy layer
|
|
5
|
+
without any embedding model.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
|
|
12
|
+
from .counter import count_tokens
|
|
13
|
+
|
|
14
|
+
_MISS = object()
|
|
15
|
+
_PUNCT = re.compile(r"[^\w\s]")
|
|
16
|
+
_WS = re.compile(r"\s+")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _normalize(text: str) -> str:
|
|
20
|
+
return _WS.sub(" ", _PUNCT.sub("", text.lower())).strip()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _shingles(text: str, n: int = 3) -> set:
|
|
24
|
+
words = text.split()
|
|
25
|
+
if len(words) < n:
|
|
26
|
+
return {tuple(words)} if words else set()
|
|
27
|
+
return {tuple(words[i:i + n]) for i in range(len(words) - n + 1)}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class TokenCache:
|
|
31
|
+
"""Exact + fuzzy response cache that tracks how many tokens it saved."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, threshold: float = 0.75, maxsize: int = 1024):
|
|
34
|
+
self.threshold = threshold
|
|
35
|
+
self.maxsize = maxsize
|
|
36
|
+
self._exact = {}
|
|
37
|
+
self._fuzzy = [] # (normalized, shingles, value)
|
|
38
|
+
self.hits = 0
|
|
39
|
+
self.misses = 0
|
|
40
|
+
self.saved_tokens = 0
|
|
41
|
+
|
|
42
|
+
def get(self, prompt: str):
|
|
43
|
+
"""Return the cached value, or ``None`` on a miss."""
|
|
44
|
+
norm = _normalize(prompt)
|
|
45
|
+
if norm in self._exact:
|
|
46
|
+
return self._hit(prompt, self._exact[norm])
|
|
47
|
+
sh = _shingles(norm)
|
|
48
|
+
if sh:
|
|
49
|
+
for n, other, value in self._fuzzy:
|
|
50
|
+
union = len(sh | other)
|
|
51
|
+
if union and len(sh & other) / union >= self.threshold:
|
|
52
|
+
return self._hit(prompt, value)
|
|
53
|
+
self.misses += 1
|
|
54
|
+
return None
|
|
55
|
+
|
|
56
|
+
def _hit(self, prompt: str, value):
|
|
57
|
+
self.hits += 1
|
|
58
|
+
self.saved_tokens += count_tokens(prompt)
|
|
59
|
+
return value
|
|
60
|
+
|
|
61
|
+
def put(self, prompt: str, value):
|
|
62
|
+
norm = _normalize(prompt)
|
|
63
|
+
self._exact[norm] = value
|
|
64
|
+
self._fuzzy.append((norm, _shingles(norm), value))
|
|
65
|
+
if len(self._fuzzy) > self.maxsize: # FIFO eviction
|
|
66
|
+
old_norm, _, _ = self._fuzzy.pop(0)
|
|
67
|
+
self._exact.pop(old_norm, None)
|
|
68
|
+
|
|
69
|
+
def stats(self) -> dict:
|
|
70
|
+
return {
|
|
71
|
+
"hits": self.hits,
|
|
72
|
+
"misses": self.misses,
|
|
73
|
+
"saved_tokens": self.saved_tokens,
|
|
74
|
+
"entries": len(self._fuzzy),
|
|
75
|
+
}
|