Skip to main content

🗜️ llm-zip

Version PyPI License Python FastAPI Docker

LLMLingua-2 MarkItDown LiteLLM Ruff

Context compression sidecar for LLM applications.
Reduce token costs 3–5× before calling any AI API.

Why · How it works · Quickstart · CLI · API response · File support · Benchmarks · Limitations · Contributing


Why llm-zip exists

AI inference is getting expensive. As context windows grow and agentic workflows multiply, the tokens you send to GPT, Claude, or Gemini compound fast — and the "free ride" subsidy era is ending.

llm-zip was built out of a simple need: compress context before it reaches the model, without changing anything else in the stack. No proxy. No middleware. No API keys. Just a sidecar you call over HTTP, that hands back a smaller text and tells you exactly how much you saved.

It started as an internal tool. It's open source because the problem is universal.

Curious about how this started? Read STORY.md.


How it works

Your app  ──→  POST /v1/estimate  ──→  llm-zip
                                           │
                              counts tokens, estimates savings
                              (no compression — CPU-free)
                                           │
              token counts + savings     ◄─┘

Your app  ──→  POST /v1/compress  ──→  llm-zip
                                           │
                              compresses with LLMLingua-2
                              scores semantic preservation
                              calculates USD savings
                                           │
              compressed text + metrics  ◄─┘

Your app  ──→  calls OpenAI / Anthropic / Gemini
               with the smaller context

llm-zip never touches your API keys or your model calls. It only compresses.


Quickstart

Requires Docker. First-time model download is ~700MB and takes 2–5 min.

Step 1 — Configure

Windows (CMD / PowerShell):

copy .llmzip.config.example .llmzip.config
notepad .llmzip.config

Linux / macOS:

cp .llmzip.config.example .llmzip.config
nano .llmzip.config

Step 2 — Download models (only on first run)

docker-compose run llmzip download-models

Step 3 — Start

docker-compose up -d

→ API: http://localhost:8000 · Docs: http://localhost:8000/docs

Running in split mode? See v0.2.0 release notes for docker-compose.split.yml and separate Dockerfile.api / Dockerfile.models — lets you scale the API layer without duplicating the ~700MB model weights.


The CLI Experience

llm-zip isn't just an API — it comes with a UNIX-friendly CLI powered by Typer and Rich. It supports stdin pipes, outputs clean JSON, and tracks live model prices.

# Check current prices (fetches live from LiteLLM)
$ llmzip prices -p anthropic

Rates from LiteLLM as of 2026-06-05
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━┓
┃ Model                                     ┃ Input $/M ┃ Output $/M ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━━┩
│ anthropic.claude-3-5-sonnet-20241022-v2:0 │    3.0000 │    15.0000 │
│ anthropic.claude-3-haiku-20240307-v1:0    │    0.2500 │     1.2500 │
└───────────────────────────────────────────┴───────────┴────────────┘

Model names come directly from LiteLLM and may use provider-specific naming (e.g. Bedrock-style). The exact list depends on live data at execution time.

# Compress directly from the terminal via pipes
$ cat huge_context.txt | llmzip compress --ratio 0.4 --model gpt-4o-mini > compressed.txt
✓ 24000 → 9600 tokens (2.5×) | score: 0.92 | saved: ~$0.0021 (gpt-4o-mini)

What you get back

{
  "compressed": "...",
  "original_tokens": 8400,
  "compressed_tokens": 1680,
  "compression_ratio": 5.0,
  "preservation_score": 0.91,
  "estimated_savings": {
    "gpt-4o-mini":           "$0.0010",
    "claude-haiku-4-5":      "$0.0013",
    "gemini-2.5-flash-lite": "$0.0006"
  },
  "skipped": false,
  "warning": null
}

Prices are fetched live from LiteLLM with local caching — no manual database updates needed.


MarkItDown Integration

One of the practical problems that motivated llm-zip was RAG over internal documents. In private systems — invoices, reports, manuals, internal specs — the source content lives in PDFs, Word files, and spreadsheets.

llm-zip integrates MarkItDown as an optional preprocessing layer. When FILE_CONVERSION=true, you can send a file directly to /v1/compress/file and get back compressed text ready for your RAG pipeline.

curl -X POST http://localhost:8000/v1/compress/file \
  -F "file=@invoice.pdf" \
  -F "ratio=0.5"

Supported formats: PDF, Word (.docx), Excel (.xlsx), PowerPoint (.pptx), and more.


Key Features

Feature Detail
📄 Text and files Compress plain text or upload PDFs, Word, Excel, and PowerPoint directly
🪓 Smart Chunking Handle documents of any length by splitting text into chunks by paragraphs
🔑 Optional auth Protect your instance with API_KEY in config (Authorization: Bearer)
📊 Dry-run estimate /v1/estimate calculates savings without compressing
🔀 Split mode Run API and inference engine as separate containers (DEPLOY_MODE=split)
🖥️ CPU-Friendly Default model requires only ~700MB of RAM — no GPU needed
🌐 Global i18n CLI in English, Spanish, Portuguese, Chinese, and Japanese
⚙️ Configurable thresholds Define when llm-zip should and shouldn't intervene (MIN_TOKENS_TO_COMPRESS)
🚫 Ignore rules Exclude texts or system prompts via .llmzipignore and .llmzipignore.local
🔒 Self-hosted Your data never leaves your infrastructure

Environment Variables

For CI or Docker deployments, you can override defaults with environment variables:

Variable Description
LLMZIP_LANG Forces CLI language (en, es, pt, zh, ja). Overrides system locale.
DEPLOY_MODE monolith (default) or split — separates API from inference container
MODELS_URL URL of the models service in split mode (default: http://llmzip-models:8001)
API_KEY Optional security key for /v1/* endpoints

📊 The Science & Benchmarks

llm-zip is powered by Microsoft's LLMLingua-2. According to their research paper evaluated on the LongBench dataset:

  • Compression sweet spot: optimal performance between 2× and 5× compression
  • Quality retention: 90–98% Exact Match performance vs. uncompressed prompts
  • Latency reduction: end-to-end latency improvement of 1.6× to 2.9× (task-agnostic, no prompt needed to start)

🧪 Internal Test Results

The following results were obtained by running llm-zip against real documents during development. They are not synthetic benchmarks — they reflect actual compression output on representative material.

How savings are calculated: tokens_saved × input_price_per_token, using live prices fetched from LiteLLM at run time. For OpenAI models, tokenization is exact (tiktoken). For Anthropic, Google and DeepSeek, a character-ratio heuristic is used (±10% margin). Only input token savings are counted — output token reduction, which also occurs in many workflows, is not included. The figures below are approximate lower-bound estimates: real savings may be higher or lower depending on your actual usage pattern and the model you call.

Document Lang Ratio Tokens In Tokens Out Compression Preservation Est. Saving¹
A Survey of LLMs (100+ p.) EN def 311,659 181,197 1.72× 0.9564 ~$0.391
Attention Is All You Need EN 0.5 11,478 4,553 2.52× 0.8509 ~$0.021
Generic customs manual² (Technical) ES 0.9 11,996 4,765 2.52× 0.8942 ~$0.021

¹ Estimated saving for claude-sonnet-4-6 input tokens only. See methodology note above. ² Synthetic test dataset modeled after Argentine customs documentation (Código Aduanero, NCM, ARCA/DGA). Not a real operational document.

📋 Hardware benchmarks (click to expand)

Community-maintained — no verified numbers yet. If you run llm-zip on real hardware, please submit your results via PR.

Hardware Model Tokens Time
— — — —
📋 Use-case benchmarks (click to expand)

Community-maintained — no verified numbers yet. If you use llm-zip in a real workload, please submit your results via PR.

Use case Tokens In Ratio Preservation Est. Saving
— — — — —

Limitations & Caveats

  • Language support — LLMLingua-2 was trained on English meeting transcripts. Spanish and other languages work but may see 10–15% lower compression quality. Community benchmarks are welcome.
  • Extractive compression — tokens are removed, not rewritten. Some nuance may be lost at aggressive ratios (above 0.7).
  • Pricing accuracy — savings are estimates. Non-OpenAI tokenizers use a character-ratio heuristic with a ±10% margin of error.
  • Format loss — file conversion extracts plain text only. Layout, tables, and complex formatting are not preserved.
  • Production testing — this is v0.2.0. Concurrent batch processing should be monitored closely in high-throughput environments.

Contributing

The most valuable contributions right now are benchmark results across different languages, domains, and models. If you use llm-zip in a real project, a PR with your numbers helps everyone calibrate expectations.

Bug reports, feature requests, and code contributions are also welcome — see CONTRIBUTING.md.

git clone https://github.com/finktech-dev/llm-zip.git
cd llm-zip
pip install -e ".[dev]"
pytest

License & Disclaimer

MIT © FinkTech

Built utilizing LLMLingua-2 and MarkItDown open-source libraries.

This project is an independent, community-driven open-source tool. It is not affiliated with, endorsed by, or sponsored by Microsoft Corporation, OpenAI, Anthropic, or any other LLM provider. All trademarks and registered trademarks are the property of their respective owners.

Metadata

Release files for llm-zip 0.3.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for llm-zip 0.3.1
File Size Uploaded
llm_zip-0.3.1.tar.gz 55.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for llm-zip 0.3.1
File Interpreter ABI Platform
llm_zip-0.3.1-py3-none-any.whl Python 3 none any Details

Total release size: 113.6 kB

Release files / llm_zip-0.3.1.tar.gz

Download URL llm_zip-0.3.1.tar.gz
Size 55.1 kB
Tags Source
SHA-256 checksum
How to use checksums
0b63716a7b289e89b81335cc547870ce9b9f8e32f8da8eda440df9da7717f35d
BLAKE2b-256 checksum
How to use checksums
20a929b9765f928626a88b29fe24fb35786dde9bae66e7c6bc991bdba7a0d269
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.15

Release files / llm_zip-0.3.1-py3-none-any.whl

Download URL llm_zip-0.3.1-py3-none-any.whl
Size 58.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e3fc44c06b94e5a7801cdd17e6aeaf88b1c7970964fb88a68e603400a2697913
BLAKE2b-256 checksum
How to use checksums
1bbba970d81579bd065440b96bbde38f618ea7a1d6964269bd9a3701c77a75ce
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.15

Release history Release notifications | RSS feed

This release

0.3.1 This release

2 release files

0.3.0

2 release files

0.2.2

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.9

2 release files

0.1.8

2 release files

0.1.7

2 release files

0.1.5

2 release files

0.1.4

2 release files

0.1.3

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page