Skip to main content

Token-compression toolkit for LLM payloads (Python binding over the tokenfold-core Rust crate)

Project description

tokenfold

Send less noise. Fit more context. Pay for fewer input tokens.

Local, provider-neutral compression for prompts, tool schemas, JSON, logs, and diffs.

CI Coverage GitHub Release PyPI npm Rust License

Quick start · Why tokenfold · Integrations · Benchmarks


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.

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 v0.3.1 CLI for Linux, macOS, or Windows from GitHub Releases, then verify it with the adjacent .sha256 file.

Or install the Python package:

pip install tokenfold

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 { payload, report } = await compress(input, {
  format: "json",
  mode: "balanced",
});

console.log(`saved ${report.saved_tokens} tokens`);

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
json_minify          346 → 229   saved 117
schema_compaction    229 → 213   saved  16
TOTAL                346 → 213   saved 133 (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

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.

Status

Version 0.3.1 provides SHA-256-checksummed (not signed) CLI binaries for Linux, macOS, and Windows from GitHub Releases, plus CycloneDX SBOMs. Registry packages are published to PyPI, npm, and crates.io. npm installs the matching native binary package without a post-install download or local Rust build.

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

Apache-2.0

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tokenfold-0.3.1.tar.gz (102.9 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

tokenfold-0.3.1-cp39-abi3-win_amd64.whl (2.8 MB view details)

Uploaded CPython 3.9+Windows x86-64

tokenfold-0.3.1-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (3.1 MB view details)

Uploaded CPython 3.9+manylinux: glibc 2.17+ x86-64

tokenfold-0.3.1-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (3.1 MB view details)

Uploaded CPython 3.9+manylinux: glibc 2.17+ ARM64

tokenfold-0.3.1-cp39-abi3-macosx_11_0_arm64.whl (3.0 MB view details)

Uploaded CPython 3.9+macOS 11.0+ ARM64

tokenfold-0.3.1-cp39-abi3-macosx_10_12_x86_64.whl (3.0 MB view details)

Uploaded CPython 3.9+macOS 10.12+ x86-64

File details

Details for the file tokenfold-0.3.1.tar.gz.

File metadata

  • Download URL: tokenfold-0.3.1.tar.gz
  • Upload date:
  • Size: 102.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for tokenfold-0.3.1.tar.gz
Algorithm Hash digest
SHA256 16a43637bd31058e251b6d991e8a15542bdb76d173c0e4b7f9fb5323ac785f08
MD5 93ed5678ea492dacd17d436868702225
BLAKE2b-256 738e77459cf84b594324cb87df7abbbcea6a48605f2680eeb616c759f9f48611

See more details on using hashes here.

File details

Details for the file tokenfold-0.3.1-cp39-abi3-win_amd64.whl.

File metadata

  • Download URL: tokenfold-0.3.1-cp39-abi3-win_amd64.whl
  • Upload date:
  • Size: 2.8 MB
  • Tags: CPython 3.9+, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for tokenfold-0.3.1-cp39-abi3-win_amd64.whl
Algorithm Hash digest
SHA256 7247ef477c18ab0ae983f010172b79aee3d4fd6f799b8f486b2f2533fa7a68b7
MD5 9d11777b89ada9e26518c6fc741454f9
BLAKE2b-256 2a9938ec08e87f4dad0b7ea35d49bb7975ce168cea51ba0fea418566b6a9e65a

See more details on using hashes here.

File details

Details for the file tokenfold-0.3.1-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for tokenfold-0.3.1-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 7863229d03da54173a734cc3b233784f28b1d1d0decb41768a3a5629895c1fcb
MD5 bb7318b3392003f1fe0f088d918d197a
BLAKE2b-256 f475ab4447331df64b71b192948aff82f45a1168f8fa193a2c34c5cfd91c5359

See more details on using hashes here.

File details

Details for the file tokenfold-0.3.1-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.

File metadata

File hashes

Hashes for tokenfold-0.3.1-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Algorithm Hash digest
SHA256 1f68b9205998c4270ef37b7884bba6de489e307a105030a539c89ce9bbab0761
MD5 4aa916d7a4cd2fc130bb42237b76ba14
BLAKE2b-256 e032631968b769497ceb08ca46cd04d53358e131a5e173f601081bb6dbec2e86

See more details on using hashes here.

File details

Details for the file tokenfold-0.3.1-cp39-abi3-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for tokenfold-0.3.1-cp39-abi3-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 c302c369ca1a92427c6829e5bb2e8cee608c0fd9df92889320a89b971f729384
MD5 22cce49686ae7612ded34bba41db9338
BLAKE2b-256 86d70c0ce17253dcdd38bfc7427fcf172ca28a214394f8ac1a27a4fdc36ab7d2

See more details on using hashes here.

File details

Details for the file tokenfold-0.3.1-cp39-abi3-macosx_10_12_x86_64.whl.

File metadata

File hashes

Hashes for tokenfold-0.3.1-cp39-abi3-macosx_10_12_x86_64.whl
Algorithm Hash digest
SHA256 16ca9abe73c4243742f55e65b1a8b0c2bb8a47c02829c09b6aded415cf66ea9a
MD5 2a81c1bf501dddac58ff0fd9d72565e5
BLAKE2b-256 673e6fa93f1f27f08192b3723c61c8d7102c63cb5efb4425167c81d85184ad72

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page