Metadata-Version: 2.5
Name: prompt-compressor
Version: 0.1.3
Summary: Rule-based LLM prompt compression — 30+ algorithms, zero dependencies
Project-URL: Homepage, https://prompt-compressor.com
Project-URL: Repository, https://github.com/kettertom/prompt-compressor
Project-URL: Bug Tracker, https://github.com/kettertom/prompt-compressor/issues
Author: Tom Ketter
License: MIT
License-File: LICENSE
Keywords: anthropic,bedrock,compression,llm,openai,prompt,tokens
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Text Processing
Requires-Python: >=3.9
Description-Content-Type: text/markdown

# prompt-compressor

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

[![PyPI version](https://badge.fury.io/py/prompt-compressor.svg)](https://pypi.org/project/prompt-compressor/)
[![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

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 24% of tokens across 8 real-world prompt types while keeping 94/94 critical instructions and leaving JSON intact** ([benchmark](#benchmark)).

🌐 **Web app**: [prompt-compressor.com](https://prompt-compressor.com)  
📦 **npm**: [prompt-compressor](https://www.npmjs.com/package/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](https://github.com/kettertom/prompt-compressor-py)** · 🐛 **Found a bug or have an idea? [Open an issue](https://github.com/kettertom/prompt-compressor-py/issues/new)**

---

## Install

```bash
pip install prompt-compressor
```

## Python API

```python
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

```python
from prompt_compressor import compress_text

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

### With AWS Bedrock

```python
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

```bash
# 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](#benchmark)) |
|-------|-----------|-------------------|
| `none` | Whitespace, unicode, ANSI, punctuation | 0% avg (0–1%) |
| `very-low` | + Filler removal, phrase shortening, JSON/SQL minify, license headers | 8% avg (1–31%) |
| `low` ✅ default | + Hedging, meta-commentary, transitions, number normalization, code comments, exact dedup | **24% avg (0–58%)**, 100% of critical facts kept |
| `medium` | + Near-duplicate removal (fuzzy / n-gram / Levenshtein), list grouping, TextRank on plain prose only | 26% avg (5–58%), 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 24%) and kept 94/94 critical facts. It helps most on long, chatty prose.

> 🔧 **Upgrade to 0.1.3 or later.** 0.1.2 and earlier collapsed indentation inside code blocks to one space (Python code no longer compiled) and removed `()` from function calls (`go();` → `go;`). 0.1.1 and earlier also kept only ~34% of critical facts at `medium` and re-indented minified JSON. All fixed and covered by tests and the benchmark.

## Variable Protection

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

```python
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](https://github.com/kettertom/prompt-compressor#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/prompts), [`bench/facts.json`](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 | 122 | **58%** | $510 | 9/9 ✅ |
| Production logs + stack trace | 873 | 570 | **35%** | $909 | 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,521** | **24%** | **$2,454** | **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` | 8% | 94/94 (100%) | 1/1 ✅ |
| `low` | 24% | 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
