Intelligent compression algorithms for LLM prompts that reduce token usage
Project description
Compress Light Reach
Intelligent compression algorithms for LLM prompts that reduce token usage
Compress Light Reach is a Python library that intelligently compresses LLM prompts by replacing repeated substrings with shorter placeholders, significantly reducing token usage and costs while maintaining perfect decompression.
Features
- Token-aware compression: Only replaces substrings >1 token with 1-token placeholders
- Dual algorithms:
- Fast greedy (~99% optimal) for daily use
- Optimal DP (O(n²)) for critical prompts
- Lossless: Perfect decompression guaranteed
- Output compression: Optional model output compression support
- Cloud API: Uses Light Reach's cloud service for compression
- Model-aware: Optimized for GPT-4, GPT-3.5-turbo, Claude, and more
- Intelligent Routing: Automatic model selection based on quality requirements
Installation
pip install compress-lightreach
Quick Start (v1.0.0)
The SDK uses intelligent model routing and targets POST /api/v2/complete.
- Authenticate with your LightReach API key (env var
PCOMPRESLR_API_KEY) - Manage provider keys (OpenAI/Anthropic/Google) in the dashboard (BYOK)
- System automatically selects optimal model based on your requirements
from pcompresslr import PcompresslrAPIClient
client = PcompresslrAPIClient(api_key="your-lightreach-api-key")
result = client.complete(
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Explain quantum computing in simple terms."},
],
desired_hle=30, # Quality preference (0-40, where 40 is SOTA)
)
print(result["decompressed_response"])
print(f"Selected: {result['routing_info']['selected_model']}")
print(f"Token savings: {result['compression_stats']['token_savings']}")
With Output Compression
result = client.complete(
messages=[{"role": "user", "content": "Generate a long report..."}],
desired_hle=25,
compress_output=True,
)
print(result["decompressed_response"])
Intelligent Model Routing (v1.0.0)
The system automatically selects the optimal model based on quality requirements and your available provider keys:
from pcompresslr import PcompresslrAPIClient
client = PcompresslrAPIClient(api_key="your-lightreach-api-key")
# Cross-provider optimization: system picks cheapest model meeting your quality bar
result = client.complete(
messages=[{"role": "user", "content": "Explain quantum computing"}],
desired_hle=30, # Quality preference (0-40, where 40 is SOTA)
)
# Check what was selected
print(result["routing_info"]["selected_model"]) # e.g., "gpt-4o-mini"
print(result["routing_info"]["selected_provider"]) # e.g., "openai"
print(result["routing_info"]["model_hle"]) # e.g., 32.5
print(result["routing_info"]["model_price_per_million"]) # e.g., 0.15
Provider-Constrained Routing
Optionally constrain to a specific provider:
# Only use OpenAI models, but pick the cheapest one meeting HLE 35
result = client.complete(
messages=[{"role": "user", "content": "Write a poem"}],
llm_provider="openai", # Optional: constrain to one provider
desired_hle=35,
)
HLE Cascading with Admin Controls
Admins can set quality ceilings via the dashboard (global or per-tag) to control costs. Your desired_hle is a preference, but requests will error if they exceed the admin-set ceiling:
# Admin set global HLE ceiling to 30%
# Requesting above the ceiling will error
try:
result = client.complete(
messages=[{"role": "user", "content": "Process payment"}],
desired_hle=35, # ❌ ERROR: exceeds ceiling of 30
tags={"env": "production"},
)
except APIRequestError as e:
print(f"Error: {e}") # "Requested HLE 35% exceeds workspace maximum of 30%"
# Correct usage: request within ceiling
result = client.complete(
messages=[{"role": "user", "content": "Process payment"}],
desired_hle=25, # ✅ OK: below ceiling of 30
tags={"env": "production"},
)
# Check if your HLE was lowered by admin ceiling
if result["routing_info"]["hle_clamped"]:
print(f"HLE lowered from {result['routing_info']['requested_hle']} "
f"to {result['routing_info']['effective_hle']} "
f"by {result['routing_info']['hle_source']}-level ceiling")
HLE Ceiling Logic:
effective_hle = min(desired_hle, tag_hle, global_hle)- most restrictive ceiling wins- Lower ceiling = force cheaper models (better cost control)
- Engineers get errors if requesting above ceiling
- Tag-level ceilings can override global ceiling (lowest wins)
Command Line Interface
# Set your API key
export PCOMPRESLR_API_KEY=your-api-key
# Compress a prompt
pcompresslr "Your prompt with repeated text here..."
# Use optimal algorithm only
pcompresslr "Your prompt here" --optimal-only
# Use greedy algorithm only
pcompresslr "Your prompt here" --greedy-only
API Reference
PcompresslrAPIClient
Main API client for intelligent model routing and compression.
Constructor Parameters
api_key(str, optional): LightReach API key. If not provided, checksPCOMPRESLR_API_KEY.api_url(str, optional): Override base API URL (advanced/testing).timeout(int): Request timeout in seconds (default: 120).
Methods
complete(messages, ...)
Messages-first completion with intelligent routing (POST /api/v2/complete).
Parameters:
messages(required): Conversation history as list of dicts withroleandcontentllm_provider(optional): Provider constraint ("openai","anthropic","google", etc.). Omit for cross-provider optimization.desired_hle(optional): Quality preference (0-40, where 40 is SOTA). Must not exceed admin's global/tag-level ceilings (request will error if it does).tags(optional): Dict of tags for cost attribution and tag-level HLE ceilingscompress(optional): Whether to compress messages (default:True)compress_output(optional): Whether to request compressed output from LLM (default:False)algorithm(optional): Compression algorithm ("greedy"or"optimal", default:"greedy")temperature(optional): LLM temperature parametermax_tokens(optional): Maximum tokens to generatecompression_config(optional): Per-role compression settingsmax_history_messages(optional): Limit conversation history length
Response includes:
decompressed_response: Final decompressed LLM responserouting_info: Details about model selection:selected_model: Model chosen by systemselected_provider: Provider chosen by systemmodel_hle: HLE score of selected modeleffective_hle: Effective HLE after applying admin ceilings (min of desired/tag/global)hle_source: Which ceiling was applied:"request","tag","global", or"none"hle_clamped:Trueif admin ceiling lowered your requested HLE
compression_stats: Token savings statisticsllm_stats: Token usage from the LLMwarnings: List of any warnings
compress(prompt, model, algorithm, tags)
Compression-only (POST /api/v1/compress).
decompress(llm_format)
Decompress an LLM-formatted compressed prompt (POST /api/v1/decompress).
health_check()
Check API health status (GET /health).
Environment Variables
PCOMPRESLR_API_KEY(orLIGHTREACH_API_KEY): Your LightReach API key.PCOMPRESLR_API_URL: Override the API base URL (advanced/testing).
Exceptions
APIKeyError: Raised when API key is invalid or missingRateLimitError: Raised when rate limit is exceededAPIRequestError: Raised for general API errors (including routing failures)PcompresslrAPIError: Base exception class
How It Works
Compress Light Reach uses intelligent algorithms to identify repeated substrings in your prompts and replace them with shorter placeholders.
The library:
- Identifies repeated substrings using efficient suffix array algorithms
- Calculates token savings for each potential replacement
- Selects optimal replacements that reduce total token count
- Intelligently routes to the best model based on your quality requirements
- Formats the result for easy LLM consumption
- Provides perfect decompression
Examples
Example: Using complete() (Recommended)
from pcompresslr import PcompresslrAPIClient
client = PcompresslrAPIClient(api_key="your-lightreach-api-key")
result = client.complete(
messages=[
{"role": "system", "content": "You are a creative writing assistant."},
{"role": "user", "content": "Write a story about a cat, a dog, and a bird."},
],
desired_hle=30,
compression_config={"compress_user": True, "compress_only_last_n_user": 1},
)
print(result["decompressed_response"])
print(f"Model used: {result['routing_info']['selected_model']}")
print(f"Token savings: {result['compression_stats']['token_savings']}")
Example 2: Complete with Output Compression
from pcompresslr import PcompresslrAPIClient
client = PcompresslrAPIClient(api_key="your-lightreach-api-key")
result = client.complete(
messages=[{"role": "user", "content": "Generate a long report with repeated sections..."}],
desired_hle=35,
compress_output=True,
)
print(result["decompressed_response"])
Getting an API Key
To use Compress Light Reach, you need an API key from compress.lightreach.io.
- Visit compress.lightreach.io
- Sign up for an account
- Get your API key from the dashboard
- Set it as an environment variable:
export PCOMPRESLR_API_KEY=your-key
Security & Privacy
BYOK model: Provider keys (OpenAI/Anthropic/Google) are managed in the dashboard and never passed through this SDK. The SDK only uses your LightReach API key for authentication with the service.
BYOK Provider Key Encryption (Required for Dashboard Settings → Provider Keys)
Provider keys are encrypted at rest using Fernet (symmetric authenticated encryption). The backend requires a Fernet key via:
API_KEY_ENCRYPTION_KEY
Generate a key:
python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
Set it in your runtime environment (examples):
- Docker Compose: set
API_KEY_ENCRYPTION_KEYin your shell or.envbefore runningdocker compose up - GitHub Actions: store the value as a GitHub Secret, then map it to the environment variable
API_KEY_ENCRYPTION_KEYin your deploy workflow
Requirements
- Python 3.8+
- tiktoken >= 0.5.0
- requests >= 2.31.0
- urllib3 >= 2.0.0
License
MIT License - see LICENSE file for details.
Support
- Documentation: compress.lightreach.io/docs
- Issues: GitHub Issues
- Email: jonathankt@lightreach.io
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
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 compress_lightreach-1.0.0.tar.gz.
File metadata
- Download URL: compress_lightreach-1.0.0.tar.gz
- Upload date:
- Size: 55.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
504f5f2438396def250ed178b782c04cce54981f1d64deef44e160849ff5777c
|
|
| MD5 |
5ca047e00ab9df1e7deea7eb82a252bc
|
|
| BLAKE2b-256 |
b097fb52f940bb11d40505df3338ba354fddf26d77b36bdc3b5e7810d08eca14
|
File details
Details for the file compress_lightreach-1.0.0-py3-none-any.whl.
File metadata
- Download URL: compress_lightreach-1.0.0-py3-none-any.whl
- Upload date:
- Size: 17.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.5
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e29d2988b0de21c77ba0cad58313edb1f97c37683890d689a504dcbcc980f886
|
|
| MD5 |
71b28ec79d68c89032d524b3d25853f0
|
|
| BLAKE2b-256 |
d978dd20e6ee01f021f7863c7bc632e56ac0e753fd0b12a5b481b4171f181ee1
|