Skip to main content

prompt-compressor

Rule-based LLM prompt compression — 30+ algorithms, zero dependencies.

PyPI version Python 3.9+ License: MIT

Compress prompts before sending them to any LLM API. No model required, no API calls, zero overhead. Works with OpenAI, Anthropic, AWS Bedrock, Cohere, or any token-based API.

No model. No API key. Deterministic. Zero dependencies. Your data never leaves your machine. Most prompt compressors (e.g. LLMLingua) run a language model to decide what to cut. This one uses 30+ rule-based algorithms, so the same input always gives the same output and it is safe for data you can't send anywhere. At the default level it cut 25% of tokens across 8 real-world prompt types while keeping 94/94 critical instructions and leaving JSON intact (benchmark).

🌐 Web app: prompt-compressor.com
📦 npm: prompt-compressor
🤖 MCP server (Claude, Cursor, VS Code): claude mcp add prompt-compressor -- npx -y prompt-compressor-mcp

⭐ Find it useful? Star it on GitHub · 🐛 Found a bug or have an idea? Open an issue


Install

pip install prompt-compressor

Python API

from prompt_compressor import compress

result = compress(system_prompt, level="low")

print(result.output)           # compressed text
print(result.tokens_before)    # e.g. 1200
print(result.tokens_after)     # e.g. 820
print(result.saved)            # 380
print(result.reduction_pct)    # 31.7

Convenience function

from prompt_compressor import compress_text

compressed = compress_text(my_prompt, level="very-low")

With AWS Bedrock

import boto3
from prompt_compressor import compress

bedrock = boto3.client("bedrock-runtime", region_name="us-east-1")

result = compress(system_prompt, level="low")

response = bedrock.invoke_model(
    modelId="anthropic.claude-3-5-sonnet-20241022-v2:0",
    body=json.dumps({
        "anthropic_version": "bedrock-2023-05-31",
        "system": result.output,   # compressed!
        "messages": [{"role": "user", "content": user_message}],
        "max_tokens": 1024,
    }),
)

CLI

# Compress a file
prompt-compressor system_prompt.txt --level low

# With stats
prompt-compressor system_prompt.txt --level medium --stats

# Pipe
cat my_prompt.txt | prompt-compressor --level very-low

# Save to file
prompt-compressor input.txt --level low --output compressed.txt

Levels

Level Algorithms Measured reduction (benchmark)
none Whitespace, unicode, ANSI, punctuation 3% avg (0–10%)
very-low + Filler removal, phrase shortening, JSON/SQL minify, license headers 9% avg (1–31%)
low ✅ default + Hedging, meta-commentary, transitions, number normalization, code comments, exact dedup 25% avg (0–61%), 100% of critical facts kept
medium + Near-duplicate removal (fuzzy / n-gram / Levenshtein), list grouping, TextRank on plain prose only 26% avg (5–61%), 100% of critical facts kept

medium = low + near-duplicate removal + light summarization of plain prose. Code blocks, lists, tables, Key: value lines, questions, and any sentence with a rule, number, ID or variable are never removed. On the dense prompts in the benchmark it saves about the same as low (26% vs 25%) and kept 94/94 critical facts. It helps most on long, chatty prose.

🔧 Upgrade to 0.1.2 or later. In 0.1.1 and earlier, medium chained several summarizers and kept only about 34% of critical facts, and JSON null-field removal re-indented minified JSON (11% saving instead of 45%). Both are fixed.

Variable Protection

Variables in {{var}}, {var}, <tag>, and ${var} format are always protected by default:

result = compress("Hello {{name}}, query: {user_query}", level="medium")
# {{name}} and {user_query} are preserved exactly

Disable with protect_vars=False.


Benchmark

The same 8 production-style prompts and must-keep facts as the JS package benchmark, run against this Python implementation: support system prompt, RAG context, agent instructions, tool JSON, code review, logs, chat history and an email thread (bench/prompts, bench/facts.json).

Results at the default level (low)

Prompt Tokens before Tokens after Saved $ saved per 1M calls* Must-keep facts kept
Support bot system prompt 325 306 6% $57 12/12 ✅
RAG context (4 retrieved docs) 431 338 22% $279 13/13 ✅
Agent instructions + tool specs 333 316 5% $51 17/17 ✅
Tool output (JSON orders) 448 248 45% $600 11/11 ✅
Code review request (Python) 292 114 61% $534 9/9 ✅
Production logs + stack trace 873 564 35% $927 9/9 ✅
Chat history (8 turns) 310 309 0% $3 11/11 ✅
Email thread to summarize 327 312 5% $45 12/12 ✅
Total 3,339 2,507 25% $2,496 94/94

* At $3 per 1M input tokens. For your model, multiply by (your price ÷ 3). Tokens counted with OpenAI's o200k_base tokenizer.

By risk level

Level Avg. saved Must-keep facts kept JSON blocks intact
very-low 9% 94/94 (100%) 1/1 ✅
low 25% 94/94 (100%) 1/1 ✅
medium 26% 94/94 (100%) 1/1 ✅

"JSON blocks intact" = every ```json block still parses and holds the same data as the original (null / empty fields are removed on purpose).

Facts lost (if any):

  • None: every must-keep fact survived at every level.

Reproduce it: pip install tiktoken && python bench/run.py

Algorithm Reference

Structural (none / very-low)

Algorithm Description
normalize_whitespace Collapse spaces, trailing whitespace, blank lines
normalize_unicode Replace fancy quotes, dashes, NBSP with ASCII
strip_ansi Remove ANSI escape codes
normalize_punctuation Remove !!!! → !, .... → ...
strip_license_headers Remove MIT/Apache/GPL header blocks
normalize_indentation 4-space → 2-space indent

Language (very-low / low)

Algorithm Description
remove_fillers "It is important to note that", "basically", "actually"
shorten_phrases "in order to" → "to", "make use of" → "use" (50+ rules)
remove_hedging "I think that", "In my opinion"
remove_meta_commentary "Sure, I'd be happy to help!", "Let me know if..."
remove_transitions Redundant "Furthermore,", "Additionally,"
remove_parentheticals Cross-reference parentheses
normalize_numbers "twenty" → "20", "five" → "5"
normalize_dates "January 5th, 2024" → "2024-01-05"

Code (low)

Algorithm Description
strip_code_comments # and // comments in fenced blocks
strip_docstrings Python triple-quoted docstrings
minify_json JSON code blocks → minified
remove_null_json_fields Remove null fields from JSON
minify_sql SQL blocks → whitespace-collapsed
minify_css CSS blocks → minified
strip_base64 Long base64 strings → [base64_data]
strip_hex_dumps Long hex strings → [hex_data]
truncate_stack_traces Keep first 5 frames
strip_ts_types TypeScript type annotations

Deduplication (low / medium)

Algorithm Description
dedup_exact_lines Consecutive duplicate lines (never inside code blocks or on code/JSON-like lines)
dedup_exact_sentences Exact duplicate sentences (never inside code blocks)
dedup_fuzzy Jaccard similarity ≥ 0.85; numbers/IDs must match
dedup_ngram N-gram overlap ≥ 0.7; numbers/IDs must match
dedup_levenshtein Edit distance < 15%; numbers/IDs must match
remove_frequent_patterns Apriori-style repeated phrases (opt-in, not part of any level: cuts inside sentences)
trie_prefix_compress Bullet groups with shared prefix

Extractive (medium: textrank_compress only)

Only plain prose sentences are candidates. Code blocks, lists, Key: value lines, questions and sentences with rules, numbers, IDs or variables are always kept.

Algorithm Description
tf_compress Drop lowest term-frequency prose sentences (opt-in)
tfidf_compress Drop lowest TF-IDF prose sentences (opt-in)
textrank_compress Drop least central prose sentences (PageRank-style)

Zero Dependencies

prompt-compressor uses only the Python standard library. No numpy, nltk, spacy, tiktoken, or anything else to install.


License

MIT © Tom Ketter

Metadata

Release files for prompt-compressor 0.1.2

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

Source distribution (sdist)

Source distribution for prompt-compressor 0.1.2
File Size Uploaded Provenance Actions
prompt_compressor-0.1.2.tar.gz 32.9 kB With provenance Details for prompt_compressor-0.1.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for prompt-compressor 0.1.2
File Interpreter ABI Platform Actions
prompt_compressor-0.1.2-py3-none-any.whl Python 3 none any Details for prompt_compressor-0.1.2-py3-none-any.whl

Total release size: 57.8 kB

Release files / prompt_compressor-0.1.2.tar.gz

Download URL prompt_compressor-0.1.2.tar.gz
Size 32.9 kB
Tags Source
SHA-256 checksum
How to use checksums
bafadefe99488d58e208377cb70a4094348b47d3944e9ff8c621a55e0cd97391
BLAKE2b-256 checksum
How to use checksums
462fa22fdeee46ba217f86336963a4ad1d16ff562f9c45d415b77406e41643a6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

Release files / prompt_compressor-0.1.2-py3-none-any.whl

Download URL prompt_compressor-0.1.2-py3-none-any.whl
Size 24.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cc77e592bba3010a5a6787307f8aee88322f74f6ce78ed30960890489dba0d9d
BLAKE2b-256 checksum
How to use checksums
3fe6086f2fd3b26ed4de98215ebec02de69080c905785831c56acabf3385ff46
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

Security for prompt-compressor 0.1.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for prompt_compressor-0.1.2.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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