TOKENFOLD
Send less noise. Fit more context. Pay for fewer input tokens.
46–68% fewer tokens on JSON & schemas · deterministic · reversible · every call audited
CLI · Python · TypeScript · proxy · MCP · local-first · provider-neutral
Quick start · Why tokenfold · Integrations · Benchmarks · Select model
Proven compression, not projections
| Repetitive JSON | API responses | Tool schemas |
|---|---|---|
| 67.6% fewer tokens | 61.3% fewer tokens | 45.63% fewer tokens |
| 50-record payload | 30-record payload | 1.8 MB OpenAI-style fixture |
All three results use exact o200k_base counts in balanced mode. The
JSON-data results are lossless. The schema benchmark preserves required
fields and descriptions while trimming redundant examples. Repetitive,
structured data benefits most.
What it does
- CLI —
tokenfold compress/inspectfiles or stdin, and compare payloads withtokenfold diff;tokenfold wrap -- <command>compresses a command's output in place. - Library — the same Rust engine and receipt shape from
pip install tokenfoldornpm install tokenfold, so behavior never drifts between languages. - Proxy —
tokenfold-proxysits in front of your provider, compresses requests, and streams responses through untouched. - MCP server —
tokenfold mcp serveexposes compress/inspect/retrieve/stats to any MCP-compatible agent or editor. - Receipts, not guesses — every call returns exact token counts, the transforms it applied, and any warnings, so you can audit what changed.
- Local and lightweight — one static Rust binary runs on your machine or infrastructure, with no hosted service or additional data processor.
Quick start
Install the interface that fits your stack:
pip install tokenfold # Python 3.9+
npm install tokenfold # Node.js 22+
cargo add tokenfold-core # Rust library
cargo install tokenfold-cli # Rust CLI
Or download the CLI for Linux, macOS, or Windows from
GitHub Releases,
then verify it with the adjacent .sha256 file.
Preview the savings without changing the input, then write the compressed payload when you are ready:
tokenfold inspect payload.json --format json
tokenfold compress payload.json --format json --output payload.compact.json
Compress an OpenAI-style request before sending it to your provider:
import json
from pathlib import Path
from tokenfold import CompressionMode, compress_openai_payload
result = compress_openai_payload(
Path("request.json").read_text(),
mode=CompressionMode.BALANCED,
)
compressed_request = json.loads(result.payload)
print(f"saved {result.report.saved_tokens} tokens ({result.saved_pct():.1f}%)")
# Pass compressed_request to your existing OpenAI client.
The TypeScript package calls the same local Rust engine and returns bytes plus the canonical compression receipt:
import { compress } from "tokenfold";
const input = new TextEncoder().encode(JSON.stringify({
results: [
{ id: 101, region: "us-east-1", plan: "pro" },
{ id: 102, region: "us-east-1", plan: "pro" },
{ id: 103, region: "us-east-1", plan: "pro" },
],
}, null, 2));
const { payload, report } = await compress(input, {
format: "json",
mode: "balanced",
});
console.log(`saved ${report.saved_tokens} tokens`);
console.log(new TextDecoder().decode(payload));
Want to try the CLI from source? Inspect the bundled request without changing it:
git clone https://github.com/snchimata/tokenfold.git
cd tokenfold
cargo run --release --locked -p tokenfold-cli -- \
inspect examples/openai_payload.json --format openai
Across 100 requests with the same payload shape, those savings add up to:
json_minify 34,600 → 22,900 saved 11,700
schema_compaction 22,900 → 21,300 saved 1,600
TOTAL 34,600 → 21,300 saved 13,300 (38.4% reduction, estimated)
Why tokenfold
Models do not need the same object key hundreds of times. Providers still count every token. Tokenfold removes that structural waste before the model call, so you get:
- Lower input cost — send fewer billable tokens without changing providers.
- More useful context — reclaim room for instructions, evidence, and conversation history.
- Less data movement — shrink payloads crossing queues, proxies, logs, and evaluation runs.
- Fewer blind spots — inspect counts, transforms, and warnings.
- No new data processor — run locally, in-process, or behind your own loopback proxy.
messages · schemas · JSON · logs · diffs
│
▼
tokenfold ──────▶ any LLM provider
│
└───────────▶ compressed payload + receipt
When to use tokenfold · when to look elsewhere
Good fit if you...
- want an exact, auditable receipt for every call instead of an estimate
- need lossless guarantees on structured data — JSON, schemas, tool arguments — before it reaches a billing meter
- want a portable static binary with deterministic behavior and a small operational footprint
- are shrinking logs, diffs, and repetitive tool output before they hit an LLM, a log store, or a queue
Look elsewhere if you...
- need query-aware summarization of unstructured prose — that calls for a model, and tokenfold stays deterministic on purpose
- want a hosted API to call — tokenfold runs entirely on your machine or your infrastructure; there is nothing to sign up for
What it improves
| Workload | User benefit |
|---|---|
| APIs and record sets | Store repeated keys and values once |
| Provider requests | Shrink messages and schemas without changing API shape |
| Agent logs and diffs | Keep evidence; collapse repetitive output |
| Token budgets | Meet the target or return an honest best effort |
| Sensitive workflows | Redact detected secrets before reports or storage |
Pick your integration
One Rust engine powers every surface, so policies and receipts stay consistent as your stack changes.
| Surface | Best for | Install or run |
|---|---|---|
| Python | Applications and evaluation pipelines | pip install tokenfold |
| TypeScript | Node.js applications and automation | npm install tokenfold |
| Rust | Native embedding | cargo add tokenfold-core |
| CLI | Files and command output | Download a release binary |
| HTTP proxy | Provider-shaped traffic | Build tokenfold-proxy from source |
| MCP server | MCP-compatible agents and editors | tokenfold mcp serve |
Compress generic JSON
Use format="JSON" for API responses, record dumps, and other data that is
not an LLM request:
import json
import tokenfold
result = tokenfold.compress(
json.dumps({
"results": [
{"id": 101, "region": "us-east-1", "plan": "pro"},
{"id": 102, "region": "us-east-1", "plan": "pro"},
{"id": 103, "region": "us-east-1", "plan": "pro"},
]
}),
format="JSON",
mode="BALANCED",
)
print(f"saved {result.report.saved_tokens} tokens")
Run the proxy
cargo build --release --locked -p tokenfold-proxy
target/release/tokenfold-proxy \
--upstream https://api.openai.com \
--target-tokens 12000
The proxy listens on 127.0.0.1:8787 by default, streams SSE responses, and
returns the compression receipt in X-TokenFold-* headers.
Safety you can inspect
Tokenfold recounts after every stage and stops when the target is met or the allowed transform set is exhausted.
- Never larger: a transform stays only when it reduces the token count.
- Reversible JSON: every structural rewrite must pass an exact round trip.
- Clear provenance: exact tokenizer results and estimates are labeled separately.
- Actionable receipts: every result lists savings, transforms, warnings, and final status.
- Honest limits: unreachable targets return an explicit status instead of silently deleting more content.
Lossy log and diff transforms remain policy-gated. Optional originals can be stored by SHA-256 hash; detected secret-shaped content is excluded.
Reproduce the numbers
| Fixture | Exact token reduction | Source |
|---|---|---|
| Repetitive 50-record JSON | 67.6% | Changelog |
| 30-record API response | 61.3% | Changelog |
| 1.8 MB OpenAI tool schema | 45.63% | Thresholds |
Run the regression benchmark:
cargo bench -p tokenfold-core
Or inspect the small bundled JSON sample:
cargo run --release --locked -p tokenfold-cli -- \
inspect examples/api_response.json --format json
The sample reports 382 → 206 estimated tokens, a 46.1% reduction. Ragged or compact inputs may save little; Tokenfold reports that result honestly.
Tokenfold Select
When structural compression ends, rank what matters.
Tokenfold Core removes structural waste. Tokenfold Select is its optional, query-aware companion: a LoRA-fine-tuned model that ranks text spans by relevance before you assemble a smaller context.
| Tokenfold Core | Tokenfold Select | |
|---|---|---|
| Best at | JSON, schemas, logs, and diffs | Query-conditioned span ranking |
| Runtime | Static Rust binary | Granite reranker + LoRA adapter |
| Contract | Compressed payload + auditable receipt | Ranking logits only |
Select is deliberately separate from the CLI and libraries. That separation lets each tool do one job well: Core provides deterministic transforms and auditable receipts; Select adds query-aware ranking when relevance matters. Your allocator still owns required-content retention and the hard token budget.
Python: load the model and score spans
from pathlib import Path
import torch
from huggingface_hub import snapshot_download
from peft import PeftModel
from transformers import AutoModelForSequenceClassification, AutoTokenizer
base_id = "ibm-granite/granite-embedding-reranker-english-r2"
repo_dir = Path(snapshot_download("snchimata/tokenfold-select"))
adapter_dir = repo_dir / "adapter"
tok = AutoTokenizer.from_pretrained(adapter_dir)
base = AutoModelForSequenceClassification.from_pretrained(base_id, dtype=torch.float32)
model = PeftModel.from_pretrained(base, adapter_dir).eval()
def score(query: str, spans: list[str]) -> list[float]:
if not spans:
return []
enc = tok([query] * len(spans), spans, padding=True, truncation=True,
max_length=8192, return_tensors="pt")
with torch.no_grad():
out = model(input_ids=enc["input_ids"], attention_mask=enc["attention_mask"])
return out.logits.view(-1).float().tolist()
See the Tokenfold Select model card for setup, evaluation, training data, and limitations.
Contributing
Issues and pull requests are welcome. Run the core checks before opening a PR:
cargo fmt --all --check
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace --locked
python eval/run_fidelity.py --gate --profile smoke-first-consumer
cd packages/tokenfold && npm ci && npm test
License
Reclaim your context window
Start with one representative payload. Install tokenfold, inspect the
receipt, and see how many tokens your application can stop sending today.
pip install tokenfold
If tokenfold earns a place in your stack, a ⭐ on GitHub helps the next team find it.
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distributions
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file tokenfold-0.3.4.tar.gz.
File metadata
- Download URL: tokenfold-0.3.4.tar.gz
- Upload date:
- Size: 110.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2979818d73b5cffbdb2c97b9f3c1ffd36d5443e10fd86da6cf2d2b508c2e664e
|
|
| MD5 |
d632763dce298a4265e6bb832b7e08fd
|
|
| BLAKE2b-256 |
0fc56912c879cb0ade72977a364bc2f29488d9fc7ae296f5b7a567a98b0b12f9
|
File details
Details for the file tokenfold-0.3.4-cp39-abi3-win_amd64.whl.
File metadata
- Download URL: tokenfold-0.3.4-cp39-abi3-win_amd64.whl
- Upload date:
- Size: 2.9 MB
- Tags: CPython 3.9+, Windows x86-64
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a819e3872e2b6bb097e8ddf08521117583584284e42737b066d3dda3637d6678
|
|
| MD5 |
fa4b99b2a44c838babab65858f13dee7
|
|
| BLAKE2b-256 |
8900934cd2c6834d5ee4d26439e3fcf905bf5044c5c5478b3013976392e65ca8
|
File details
Details for the file tokenfold-0.3.4-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.
File metadata
- Download URL: tokenfold-0.3.4-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
- Upload date:
- Size: 3.2 MB
- Tags: CPython 3.9+, manylinux: glibc 2.17+ x86-64
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
945c592fd6e82c4ca504b3d2721d4e1909efb94b20b1c51c8a359924d71eb016
|
|
| MD5 |
283308182c73b5e339d325ca20f2a32b
|
|
| BLAKE2b-256 |
d97c3d8d18abda6745d8f234c31bfc5776fcadbdca502bd6b0f8fa12a330908a
|
File details
Details for the file tokenfold-0.3.4-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.
File metadata
- Download URL: tokenfold-0.3.4-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
- Upload date:
- Size: 3.1 MB
- Tags: CPython 3.9+, manylinux: glibc 2.17+ ARM64
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
03902f2f5c73afd27e3193c517a4218f5a99ac31e896df48495bd0e926c6c7fa
|
|
| MD5 |
53db941d7f82dd7a182895f04258cc6e
|
|
| BLAKE2b-256 |
b413eac44aabdadb0927a0e747248a63a0ebc67891fd68b13ad1c7502104c39a
|
File details
Details for the file tokenfold-0.3.4-cp39-abi3-macosx_11_0_arm64.whl.
File metadata
- Download URL: tokenfold-0.3.4-cp39-abi3-macosx_11_0_arm64.whl
- Upload date:
- Size: 3.0 MB
- Tags: CPython 3.9+, macOS 11.0+ ARM64
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
fa328390b9abbb389247651a042777c4a83d33053c52b05b9cdae62e2c0212a9
|
|
| MD5 |
326f690eb60a02816e5c201812e37e1a
|
|
| BLAKE2b-256 |
10a9db3567d02ab842d7f939a428c683dc649ed5f93b46a0d416a2b53060426c
|
File details
Details for the file tokenfold-0.3.4-cp39-abi3-macosx_10_12_x86_64.whl.
File metadata
- Download URL: tokenfold-0.3.4-cp39-abi3-macosx_10_12_x86_64.whl
- Upload date:
- Size: 3.0 MB
- Tags: CPython 3.9+, macOS 10.12+ x86-64
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
fd495ac95b89fbd0c25e3d20f06519843459a676be59596060a7e05e559d1b31
|
|
| MD5 |
7ace606a7ed5aba856cde5fe9999bbca
|
|
| BLAKE2b-256 |
ce34e2ed590232c5ab593f522bb2a4bf613ae06444c804cd89fc0f6d54d95319
|