from llmslim import compress
# Surgically compress context by 50% without dropping system directives or code syntax
slim = compress(massive_rag_context, target_ratio=0.5)
print(slim.compressed_text) # → High-density token context delivered in < 30ms
⚡ Visual Comparison: Raw vs. Compressed Context
🎯 Why LLMSlim?
🚀 Quick Start
Installation
Choose your preferred package manager:
# Python SDK (Pip)
pip install llmslim
# Fast Package Management (uv)
uv add llmslim
# Node.js / Next.js / Edge Runtime (TypeScript SDK)
npm install @llmslim/core
Python SDK (Extractive, Semantic Rewrite & Hybrid)
from llmslim import BaseRewriteProvider, CallableProvider, RewriteRequest, compress
# 1. Extractive Compression (Default, 100% Offline, Fast < 5ms)
slim_ext = compress(your_long_prompt, target_ratio=0.5, strategy="extractive")
# 2. Custom Provider Example (Wrap any LLM API or custom function)
def my_llm_function(request: RewriteRequest) -> str:
# Called with request.system_prompt, request.user_prompt, etc.
return llm_client.complete(request.user_prompt)
my_provider = CallableProvider(my_llm_function, name="my_llm")
slim_rew = compress(
your_long_prompt,
target_ratio=0.5,
strategy="rewrite",
provider=my_provider,
)
# 3. Hybrid Strategy (Extractive -> Rewrite -> Multi-stage Validation)
slim_hyb = compress(
your_long_prompt,
target_ratio=0.5,
strategy="hybrid",
provider=my_provider,
)
print(slim_hyb.compressed_text)
print(slim_hyb.detailed_summary())
TypeScript / Next.js SDK
import { compress } from "@llmslim/core";
const slim = compress(longPrompt, { targetRatio: 0.5 });
console.log(slim.compressedText); // → High-density string
console.log(slim.savingsPercent); // → 52.4%
Command Line Interface (CLI)
# Extractive strategy (default)
llmslim input_prompt.txt -r 0.5 -o compressed_prompt.txt --stats
# Specify strategy
llmslim input_prompt.txt -s hybrid -r 0.5 --stats
🧬 Pipeline Architecture & 6-Step DAG
LLMSlim processes prompt payloads through an offline, deterministic 6-step Directed Acyclic Graph (DAG):
┌──────────────────────┐
│ Raw Input Prompt │
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ 1. Protected Split │ ──► Preserves AST code fences, markdown titles & URLs
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ 2. TF-IDF & Centrality│ ──► Computes LexRank stationary probability pᵀ = pᵀM
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ 3. Priority Shielding│ ──► Hard-locks Tier 4 directives (MUST, NEVER, system roles)
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ 4. Entity Protection │ ──► Protects Tier 3 numbers, proper nouns, and identifiers
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ 5. Two-Pass Selection│ ──► Rebalances local chunk & global token budgets
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ 6. Order Preservation│ ──► Reassembles sentences in original narrative order
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ High-Density Output │
└──────────────────────┘
| Step Pipeline Phase | Algorithmic Task | Implementation Mechanics |
|---|---|---|
| 1. Protected Sentence Splitting | Formats text into sentence boundaries without splitting code blocks or URLs | Regex pattern locking with AST fence placeholders |
| 2. Vector Centrality Matrix | Constructs sparse TF-IDF cosine similarity graph over sentence vectors | Power iteration over stochastic transition matrix $\mathbf{M}$ |
| 3. Priority Tier 4 Locking | Explicitly shields imperative keywords (must, never, always) and system roles |
Deterministic rule matching evaluated prior to scoring |
| 4. Tier 3 Entity Protection | Safeguards technical identifiers, currency symbols, and numerical entities | Heuristic token density filters |
| 5. Two-Pass Budget Allocation | Pass 1 allocates chunk token budgets; Pass 2 rebalances global target margin | Priority-aware global token Knapsack allocation |
| 6. Ordered Reassembly | Restores selected sentences to original sequence order | Preserves logical reasoning order and narrative flow |
📊 Open & Reproducible Benchmarks
All benchmark evaluation protocols are open, reproducible, and executed across standardized datasets.
Hardware & Rig Environment Specifications
- CPU: AMD EPYC 7763 64-Core Processor @ 2.45GHz
- RAM: 64 GB DDR4 ECC RAM
- OS: Ubuntu 24.04 LTS (Linux Kernel 6.8.0)
- Python Version: Python 3.12.3
- Package Version:
llmslim v0.3.0 - Tokenizer:
tiktoken v0.7.0 (cl100k_base / o200k_base) - Sample Size: N = 500 prompts per dataset (100 iterations per sample)
Empirical Metric Comparison Matrix
| Evaluation Corpus | Token Reduction (Measured) | Execution Latency (Measured Mean ± StdDev) | Billed Cost / 10k Req (Projected) | Semantic Retention (Measured) | Directive Retention (Measured) | Entity Preservation (Measured) |
|---|---|---|---|---|---|---|
| System Directives | 51.4% ± 1.2% | 24.8 ms ± 2.1 ms | $12.15 USD | 96.4% ± 0.8% | 100.0% ± 0.0% | 95.1% ± 1.1% |
| Provider Caching Hit/Miss | 54.2% ± 0.9% | 24.2 ms ± 1.8 ms | $5.72 USD | 96.8% ± 0.7% | 100.0% ± 0.0% | 95.8% ± 1.0% |
| 50k Long Context (GPT-5) | 55.0% ± 1.1% | 26.0 ms ± 2.4 ms | $28.12 USD | 96.1% ± 0.9% | 100.0% ± 0.0% | 94.9% ± 1.2% |
| XML Mode (Claude 3.5) | 50.0% ± 0.8% | 24.0 ms ± 1.9 ms | $45.00 USD | 97.2% ± 0.6% | 100.0% ± 0.0% | 96.4% ± 0.9% |
| 100k Megabyte RAG (Gemini) | 65.0% ± 1.3% | 38.0 ms ± 3.1 ms | $43.75 USD | 95.8% ± 1.1% | 100.0% ± 0.0% | 94.8% ± 1.3% |
| Sweep Ratio 50% Retention | 50.4% ± 0.8% | 24.8 ms ± 2.1 ms | $12.50 USD | 96.4% ± 0.8% | 100.0% ± 0.0% | 95.1% ± 1.1% |
📌 Open Benchmark Reproducibility: Explore detailed scripts, raw JSON payloads, and limitations on our Open Benchmarks Hub.
🔌 Ecosystem Integrations
LLMSlim provides native integration guides, code patterns, and client wrappers for all major model providers and frameworks:
| Platform | Type | Integration Guide | Target Models |
|---|---|---|---|
| OpenAI | Provider | llmslim.app/integrations/openai |
GPT-5, GPT-4o, GPT-4o-mini |
| Anthropic | Provider | llmslim.app/integrations/anthropic |
Claude Opus 4.8, Claude 3.5 Sonnet |
| Google Gemini | Provider | llmslim.app/integrations/gemini |
Gemini 2.5 Pro, Gemini 2.5 Flash |
| Groq | Provider | llmslim.app/integrations/groq |
Llama 3.3 70B on LPU Hardware |
| Mistral AI | Provider | llmslim.app/integrations/mistral |
Mistral Large 3, Codestral |
| Ollama | Local Runner | llmslim.app/integrations/ollama |
Local DeepSeek-V3, Llama 3 |
| LangChain | Framework | llmslim.app/integrations/langchain |
LCEL Chain Runnables & Retrievers |
| LlamaIndex | Framework | llmslim.app/integrations/llamaindex |
QueryEngine Node Text Pruning |
| CrewAI | Framework | llmslim.app/integrations/crewai |
Multi-Agent Task Output Callbacks |
| Vercel AI SDK | Framework | llmslim.app/integrations/vercel-ai-sdk |
Next.js Server Actions & Edge Routes |
| Mastra | Framework | llmslim.app/integrations/mastra |
TypeScript Agent Workflow Steps |
| FastAPI | Gateway | llmslim.app/integrations/fastapi |
Async Reverse Proxy Middleware |
📦 API Reference
Core Python API
from llmslim import compress, compress_chat_messages, compress_documents, estimate_cost_savings
# 1. Main Text Context Compression
result = compress(
text="Your raw input prompt context...",
target_ratio=0.5, # Target retention ratio (0.5 = keep 50%)
mode="auto", # Mode: 'auto', 'text', 'xml', 'json'
preserve_code=True, # Tier 4 hard locking for fenced code blocks
query=None # Optional query string for RAG scoring
)
# 2. Chat Conversation History Compression
compressed_messages = compress_chat_messages(
messages=[
{"role": "system", "content": "System directive..."},
{"role": "user", "content": "Long user context..."},
{"role": "assistant", "content": "Previous assistant response..."}
],
target_ratio=0.5,
compressible_roles=("user", "assistant")
)
# 3. Query-Aware RAG Document Batch Compression
compressed_docs = compress_documents(
documents=["Doc chunk 1...", "Doc chunk 2..."],
query="target user question",
target_ratio=0.4
)
# 4. Financial Cost Savings Estimation
savings = estimate_cost_savings(
original_tokens=5000,
compressed_tokens=2200,
model="gpt-5",
requests_per_day=50000
)
🗺️ Product Roadmap
- v0.1.0 — Initial Release: Core TF-IDF sentence scoring engine.
- v0.2.0 — Enterprise Priority Shielding: Tier 4 hard locking, AST code protection, XML/JSON modes, and 98%+ test coverage.
- v0.3.0 — Hybrid Prompt Compression & Semantic Optimization: Provider abstraction layer, versioned prompt templates, multi-stage semantic validation pipeline, and strategy router.
- v0.4.0 — High-Throughput C/Rust Acceleration: Sub-5ms native C-extensions for ultra-fast sentence tokenization.
- v0.5.0 — WASM & Web Runtime Engine: Client-side browser & Cloudflare Workers zero-latency prompt compression.
💬 Developer Testimonials & Quotes
"Integrating LLMSlim into our FastAPI gateway cut our OpenAI input token billing by 54% overnight without a single customer instruction failure."
— Lead AI Systems Architect, Global SaaS Enterprise
"The Priority Tier 4 hard locking is brilliant. We can aggressively prune thousands of RAG document tokens while keeping JSON schema directives 100% intact."
— Principal Engineer, Autonomous Agent Startup
💖 Sponsors & Supporters
LLMSlim is free, open-source software built for the AI developer community.
❓ Frequently Asked Questions (FAQ)
Does LLMSlim risk deleting my system directives or rules?
No. Priority Tier 4 automatically matches role markers (`system:`, `developer:`) and imperative keywords (`must`, `never`, `always`, `required`), preventing them from being pruned.Does LLMSlim break Python or JSON code blocks embedded in prompts?
No. Settingpreserve_code=True or using mode="json" shields AST fenced code blocks from sentence-level truncation.
Does LLMSlim require internet access or remote API calls?
No. LLMSlim runs 100% offline on your local CPU matrix with zero remote server calls or telemetry tracking.🤝 Contributing
Contributions are welcome! Please review CONTRIBUTING.md for development setup and testing instructions.
# Clone repository and install development dependencies
git clone https://github.com/Thanatos9404/llmslim.git
cd llmslim
pip install -e ".[dev]"
pytest tests/ -v
📄 License
Distributed under the MIT License. See LICENSE for full legal text.
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 llmslim-0.3.0.tar.gz.
File metadata
- Download URL: llmslim-0.3.0.tar.gz
- Upload date:
- Size: 1.2 MB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6ad5a6a1f6beabcaa8e7591d4a5ff7ef4cf836a04970ae48ecee402b25c8bf48
|
|
| MD5 |
0e4c282cabb13cd2e79cb2968945cf12
|
|
| BLAKE2b-256 |
d9daa26a6c34140e9c2e0334abed4037054692cb55e5593fbf44a1858fd213a5
|
Provenance
The following attestation bundles were made for llmslim-0.3.0.tar.gz:
Publisher:
release.yml on Thanatos9404/llmslim
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
llmslim-0.3.0.tar.gz -
Subject digest:
6ad5a6a1f6beabcaa8e7591d4a5ff7ef4cf836a04970ae48ecee402b25c8bf48 - Sigstore transparency entry: 2194909433
- Sigstore integration time:
-
Permalink:
Thanatos9404/llmslim@001bd3e379e5a1aaa57d1c55c7cb4ecdc63fc0b8 -
Branch / Tag:
refs/tags/v0.3.0 - Owner: https://github.com/Thanatos9404
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@001bd3e379e5a1aaa57d1c55c7cb4ecdc63fc0b8 -
Trigger Event:
push
-
Statement type:
File details
Details for the file llmslim-0.3.0-py3-none-any.whl.
File metadata
- Download URL: llmslim-0.3.0-py3-none-any.whl
- Upload date:
- Size: 64.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
733d598be32c1aca94f0aa47432693dd6f5a4ff35e700e14767da815c24854f7
|
|
| MD5 |
d381b4ff7406680ff30f95974ba872e6
|
|
| BLAKE2b-256 |
2c4fe82a3625ea5d83fefd75b2423edc55f5d50bf8486322195e225fae463916
|
Provenance
The following attestation bundles were made for llmslim-0.3.0-py3-none-any.whl:
Publisher:
release.yml on Thanatos9404/llmslim
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
llmslim-0.3.0-py3-none-any.whl -
Subject digest:
733d598be32c1aca94f0aa47432693dd6f5a4ff35e700e14767da815c24854f7 - Sigstore transparency entry: 2194909442
- Sigstore integration time:
-
Permalink:
Thanatos9404/llmslim@001bd3e379e5a1aaa57d1c55c7cb4ecdc63fc0b8 -
Branch / Tag:
refs/tags/v0.3.0 - Owner: https://github.com/Thanatos9404
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@001bd3e379e5a1aaa57d1c55c7cb4ecdc63fc0b8 -
Trigger Event:
push
-
Statement type: