llmslim 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- llmslim-0.1.0/LICENSE +21 -0
- llmslim-0.1.0/PKG-INFO +634 -0
- llmslim-0.1.0/README.md +591 -0
- llmslim-0.1.0/llmslim/__init__.py +30 -0
- llmslim-0.1.0/llmslim/chunking.py +105 -0
- llmslim-0.1.0/llmslim/cli.py +90 -0
- llmslim-0.1.0/llmslim/core.py +354 -0
- llmslim-0.1.0/llmslim/cost.py +117 -0
- llmslim-0.1.0/llmslim/embeddings.py +121 -0
- llmslim-0.1.0/llmslim/pipelines.py +104 -0
- llmslim-0.1.0/llmslim/ranking.py +215 -0
- llmslim-0.1.0/llmslim/tokenization.py +120 -0
- llmslim-0.1.0/llmslim/tokens.py +58 -0
- llmslim-0.1.0/llmslim.egg-info/PKG-INFO +634 -0
- llmslim-0.1.0/llmslim.egg-info/SOURCES.txt +20 -0
- llmslim-0.1.0/llmslim.egg-info/dependency_links.txt +1 -0
- llmslim-0.1.0/llmslim.egg-info/entry_points.txt +2 -0
- llmslim-0.1.0/llmslim.egg-info/requires.txt +20 -0
- llmslim-0.1.0/llmslim.egg-info/top_level.txt +1 -0
- llmslim-0.1.0/pyproject.toml +65 -0
- llmslim-0.1.0/setup.cfg +4 -0
- llmslim-0.1.0/tests/test_core.py +506 -0
llmslim-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Yashvardhan Thanvi
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
llmslim-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,634 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: llmslim
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Cut your LLM prompt size by 40-70% in one line of code -- semantic chunking + extractive summarization that preserves meaning, instructions, and key entities.
|
|
5
|
+
Author-email: Yashvardhan Thanvi <thanatos9404@users.noreply.github.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Thanatos9404/llmslim
|
|
8
|
+
Project-URL: Repository, https://github.com/Thanatos9404/llmslim
|
|
9
|
+
Project-URL: Bug Tracker, https://github.com/Thanatos9404/llmslim/issues
|
|
10
|
+
Keywords: llm,prompt-engineering,token-optimization,rag,nlp,summarization,openai,anthropic,gemini,context-window,cost-optimization
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
22
|
+
Classifier: Topic :: Text Processing :: Linguistic
|
|
23
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
24
|
+
Requires-Python: >=3.8
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Requires-Dist: numpy>=1.21
|
|
28
|
+
Requires-Dist: scikit-learn>=1.0
|
|
29
|
+
Provides-Extra: semantic
|
|
30
|
+
Requires-Dist: sentence-transformers>=2.2; extra == "semantic"
|
|
31
|
+
Provides-Extra: fast-tokens
|
|
32
|
+
Requires-Dist: tiktoken>=0.5; extra == "fast-tokens"
|
|
33
|
+
Provides-Extra: nlp
|
|
34
|
+
Requires-Dist: nltk>=3.8; extra == "nlp"
|
|
35
|
+
Provides-Extra: all
|
|
36
|
+
Requires-Dist: sentence-transformers>=2.2; extra == "all"
|
|
37
|
+
Requires-Dist: tiktoken>=0.5; extra == "all"
|
|
38
|
+
Requires-Dist: nltk>=3.8; extra == "all"
|
|
39
|
+
Provides-Extra: dev
|
|
40
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
41
|
+
Requires-Dist: pytest-cov; extra == "dev"
|
|
42
|
+
Dynamic: license-file
|
|
43
|
+
|
|
44
|
+
<div align="center">
|
|
45
|
+
|
|
46
|
+
<!-- Animated SVG Hero Banner -->
|
|
47
|
+
<img src="https://capsule-render.vercel.app/api?type=waving&color=0:0d1117,50:58a6ff,100:f778ba&height=220§ion=header&text=llmslim&fontSize=52&fontColor=ffffff&animation=fadeIn&fontAlignY=35&desc=Cut%20your%20LLM%20costs%20by%2050%25%20in%201%20line%20of%20code&descAlignY=55&descSize=18&descColor=c9d1d9" width="100%"/>
|
|
48
|
+
|
|
49
|
+
<!-- Animated Typing Effect -->
|
|
50
|
+
<a href="https://github.com/Thanatos9404/llmslim">
|
|
51
|
+
<img src="https://readme-typing-svg.demolab.com?font=JetBrains+Mono&weight=600&size=24&duration=3000&pause=1000&color=58A6FF¢er=true&vCenter=true&multiline=true&repeat=true&width=700&height=80&lines=%F0%9F%94%A5+Semantic+Compression+for+LLM+Prompts;%E2%9A%A1+40-70%25+Token+Reduction+%7C+Zero+Meaning+Loss;%F0%9F%92%B0+Save+Thousands+on+API+Costs+Instantly" alt="Typing SVG" />
|
|
52
|
+
</a>
|
|
53
|
+
|
|
54
|
+
<br/>
|
|
55
|
+
|
|
56
|
+
<!-- Animated Flow Diagram -->
|
|
57
|
+
<p align="center">
|
|
58
|
+
<img src="assets/compression-flow.svg" width="95%" alt="LLMSlim Pipeline Live Animation" />
|
|
59
|
+
</p>
|
|
60
|
+
|
|
61
|
+
<br/>
|
|
62
|
+
|
|
63
|
+
<!-- Badges Row 1: Status -->
|
|
64
|
+
[](https://pypi.org/project/llmslim/)
|
|
65
|
+
[](https://www.python.org/)
|
|
66
|
+
[](LICENSE)
|
|
67
|
+
[](https://github.com/Thanatos9404/llmslim/stargazers)
|
|
68
|
+
|
|
69
|
+
<!-- Badges Row 2: Tech -->
|
|
70
|
+
[](https://www.sbert.net/)
|
|
71
|
+
[](#-works-with-every-llm)
|
|
72
|
+
[](#-quickstart)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
<br/>
|
|
77
|
+
|
|
78
|
+
<!-- Hero Code Block -->
|
|
79
|
+
```python
|
|
80
|
+
from llmslim import compress
|
|
81
|
+
|
|
82
|
+
result = compress(your_massive_prompt, target_ratio=0.5)
|
|
83
|
+
# That's it. 50% fewer tokens. Same meaning. Half the cost. 🚀
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
<br/>
|
|
87
|
+
|
|
88
|
+
<!-- Animated Stats Cards -->
|
|
89
|
+
<a href="#-benchmarks"><img src="https://img.shields.io/badge/Token_Reduction-40--70%25-58a6ff?style=for-the-badge&labelColor=0d1117" /></a>
|
|
90
|
+
<a href="#-cost-savings-calculator"><img src="https://img.shields.io/badge/Cost_Savings-$12K+/year-10b981?style=for-the-badge&labelColor=0d1117" /></a>
|
|
91
|
+
<a href="#-benchmarks"><img src="https://img.shields.io/badge/Meaning_Retained-95%25+-f778ba?style=for-the-badge&labelColor=0d1117" /></a>
|
|
92
|
+
<a href="#-quickstart"><img src="https://img.shields.io/badge/Setup_Time-30_seconds-ffa657?style=for-the-badge&labelColor=0d1117" /></a>
|
|
93
|
+
|
|
94
|
+
</div>
|
|
95
|
+
|
|
96
|
+
---
|
|
97
|
+
|
|
98
|
+
<div align="center">
|
|
99
|
+
<table>
|
|
100
|
+
<tr>
|
|
101
|
+
<td width="50%">
|
|
102
|
+
|
|
103
|
+
### ❌ Before (2,847 tokens → $$$)
|
|
104
|
+
```
|
|
105
|
+
You are an AI assistant that helps users with their
|
|
106
|
+
coding questions. You should be helpful, harmless,
|
|
107
|
+
and honest. When answering questions, you should
|
|
108
|
+
provide detailed explanations with code examples
|
|
109
|
+
where appropriate. Make sure to consider edge cases
|
|
110
|
+
and provide best practices. If you're not sure about
|
|
111
|
+
something, say so rather than making things up.
|
|
112
|
+
Please format your responses using markdown for
|
|
113
|
+
better readability. Include relevant links to
|
|
114
|
+
documentation when possible. Always test your code
|
|
115
|
+
before sharing it. Remember to handle errors
|
|
116
|
+
gracefully and explain your reasoning step by step...
|
|
117
|
+
|
|
118
|
+
[... 200 more lines of context ...]
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
</td>
|
|
122
|
+
<td width="50%">
|
|
123
|
+
|
|
124
|
+
### ✅ After (1,138 tokens → 💰)
|
|
125
|
+
```
|
|
126
|
+
You are an AI assistant for coding questions.
|
|
127
|
+
Be helpful, harmless, honest. Provide detailed
|
|
128
|
+
explanations with code examples. Consider edge
|
|
129
|
+
cases and best practices. If unsure, say so.
|
|
130
|
+
Format responses in markdown. Include documentation
|
|
131
|
+
links. Always test code before sharing. Handle
|
|
132
|
+
errors gracefully, explain reasoning step by step.
|
|
133
|
+
|
|
134
|
+
[... compressed with meaning preserved ...]
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
</td>
|
|
138
|
+
</tr>
|
|
139
|
+
<tr>
|
|
140
|
+
<td colspan="2" align="center">
|
|
141
|
+
|
|
142
|
+
**📉 60% reduction • 1,709 tokens saved • $0.0043/request saved on GPT-4o / $0.0021 on GPT-5**
|
|
143
|
+
|
|
144
|
+
</td>
|
|
145
|
+
</tr>
|
|
146
|
+
</table>
|
|
147
|
+
</div>
|
|
148
|
+
|
|
149
|
+
---
|
|
150
|
+
|
|
151
|
+
## 🎯 Why llmslim?
|
|
152
|
+
|
|
153
|
+
<table>
|
|
154
|
+
<tr>
|
|
155
|
+
<td width="50%" valign="top">
|
|
156
|
+
|
|
157
|
+
### 😤 The Problem
|
|
158
|
+
|
|
159
|
+
Every token you send to an LLM costs money. Long prompts, RAG contexts, and chat histories bloat your API bills while most of the text is **redundant filler** that the model doesn't need.
|
|
160
|
+
|
|
161
|
+
- 💸 **GPT-4o** costs $2.50/M input tokens (GPT-5 costs $1.25/M)
|
|
162
|
+
- 📊 Average prompt has **40-60% redundancy**
|
|
163
|
+
- 🔄 Chat histories grow **unbounded**
|
|
164
|
+
- 📄 RAG contexts are **mostly noise**
|
|
165
|
+
|
|
166
|
+
</td>
|
|
167
|
+
<td width="50%" valign="top">
|
|
168
|
+
|
|
169
|
+
### 🎉 The Solution
|
|
170
|
+
|
|
171
|
+
**llmslim** uses semantic understanding to surgically remove redundancy while keeping every instruction, entity, and key detail intact.
|
|
172
|
+
|
|
173
|
+
- ⚡ **One function call** — `compress(text)`
|
|
174
|
+
- 🧠 **Semantic chunking** — understands topics
|
|
175
|
+
- 🎯 **Smart ranking** — keeps what matters
|
|
176
|
+
- 🔒 **Instruction preservation** — never drops directives
|
|
177
|
+
- 💰 **Save 40-70%** on every API call
|
|
178
|
+
|
|
179
|
+
</td>
|
|
180
|
+
</tr>
|
|
181
|
+
</table>
|
|
182
|
+
|
|
183
|
+
---
|
|
184
|
+
|
|
185
|
+
## ⚡ Quickstart
|
|
186
|
+
|
|
187
|
+
### Installation
|
|
188
|
+
|
|
189
|
+
```bash
|
|
190
|
+
# Core (works offline, no model downloads needed)
|
|
191
|
+
pip install llmslim
|
|
192
|
+
|
|
193
|
+
# With high-quality semantic embeddings (recommended)
|
|
194
|
+
pip install "llmslim[semantic]"
|
|
195
|
+
|
|
196
|
+
# Everything (semantic + fast token counting + NLTK sentence splitting)
|
|
197
|
+
pip install "llmslim[all]"
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
### One Line Is All You Need
|
|
201
|
+
|
|
202
|
+
```python
|
|
203
|
+
from llmslim import compress
|
|
204
|
+
|
|
205
|
+
result = compress(your_prompt, target_ratio=0.5)
|
|
206
|
+
|
|
207
|
+
print(result.compressed_text) # → your compressed prompt
|
|
208
|
+
print(result.reduction_percent) # → 52.3
|
|
209
|
+
print(result.tokens_saved) # → 1,847
|
|
210
|
+
print(result.summary()) # → full stats breakdown
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
### Use Directly With Any LLM
|
|
214
|
+
|
|
215
|
+
```python
|
|
216
|
+
from llmslim import compress
|
|
217
|
+
from openai import OpenAI
|
|
218
|
+
|
|
219
|
+
client = OpenAI()
|
|
220
|
+
|
|
221
|
+
# Compress before sending — drop-in, zero friction
|
|
222
|
+
prompt = compress(massive_system_prompt, target_ratio=0.5)
|
|
223
|
+
|
|
224
|
+
response = client.chat.completions.create(
|
|
225
|
+
model="gpt-5",
|
|
226
|
+
messages=[
|
|
227
|
+
{"role": "system", "content": str(prompt)}, # ← compressed!
|
|
228
|
+
{"role": "user", "content": user_question},
|
|
229
|
+
],
|
|
230
|
+
)
|
|
231
|
+
# Same quality response. Half the cost.
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
---
|
|
235
|
+
|
|
236
|
+
## 🧠 How It Works
|
|
237
|
+
|
|
238
|
+
<div align="center">
|
|
239
|
+
|
|
240
|
+
```mermaid
|
|
241
|
+
graph LR
|
|
242
|
+
A["📝 Input Text<br/><i>3,000 tokens</i>"] --> B["✂️ Sentence<br/>Splitting"]
|
|
243
|
+
B --> C["🧩 Semantic<br/>Chunking"]
|
|
244
|
+
C --> D["📊 Extractive<br/>Ranking"]
|
|
245
|
+
D --> E["🔒 Instruction<br/>Preservation"]
|
|
246
|
+
E --> F["🎯 Budget-Aware<br/>Selection"]
|
|
247
|
+
F --> G["✨ Output<br/><i>1,500 tokens</i>"]
|
|
248
|
+
|
|
249
|
+
style A fill:#1a1b27,stroke:#58a6ff,color:#c9d1d9
|
|
250
|
+
style B fill:#1a1b27,stroke:#7c3aed,color:#c9d1d9
|
|
251
|
+
style C fill:#1a1b27,stroke:#7c3aed,color:#c9d1d9
|
|
252
|
+
style D fill:#1a1b27,stroke:#f778ba,color:#c9d1d9
|
|
253
|
+
style E fill:#1a1b27,stroke:#ffa657,color:#c9d1d9
|
|
254
|
+
style F fill:#1a1b27,stroke:#ffa657,color:#c9d1d9
|
|
255
|
+
style G fill:#1a1b27,stroke:#10b981,color:#c9d1d9
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
</div>
|
|
259
|
+
|
|
260
|
+
### The 6-Step Pipeline
|
|
261
|
+
|
|
262
|
+
| Step | What Happens | Why It Matters |
|
|
263
|
+
|:-----|:-------------|:---------------|
|
|
264
|
+
| **1. Sentence Splitting** | Text → individual sentences via NLTK/regex, preserving code blocks and markdown | Clean atomic units for analysis |
|
|
265
|
+
| **2. Semantic Chunking** | Group sentences by topic using embedding similarity with drift detection | Per-topic ranking is far more accurate than global |
|
|
266
|
+
| **3. Centrality Ranking** | LexRank-style cosine similarity to chunk centroid — find the "core" sentences | Removes peripheral/redundant sentences |
|
|
267
|
+
| **4. Entity & Instruction Detection** | Boost sentences with named entities, numbers, code, directives ("must", "never") | Never lose critical information |
|
|
268
|
+
| **5. Budget-Aware Selection** | Greedily select top-scored sentences within the target token budget | Precise compression ratio control |
|
|
269
|
+
| **6. Ordered Reassembly** | Reconstruct in original sentence order, preserving paragraph structure | Maintains logical flow and readability |
|
|
270
|
+
|
|
271
|
+
---
|
|
272
|
+
|
|
273
|
+
## 🔥 Features
|
|
274
|
+
|
|
275
|
+
<table>
|
|
276
|
+
<tr>
|
|
277
|
+
<td width="33%" align="center">
|
|
278
|
+
<h3>🎯 Semantic Chunking</h3>
|
|
279
|
+
<p>Groups sentences by topic using embedding similarity. Detects topic shifts so each chunk is ranked independently for maximum accuracy.</p>
|
|
280
|
+
</td>
|
|
281
|
+
<td width="33%" align="center">
|
|
282
|
+
<h3>🔒 Instruction Fidelity</h3>
|
|
283
|
+
<p>Automatically detects and preserves imperative language, code blocks, numbered steps, and directives. Your instructions <b>never</b> get dropped.</p>
|
|
284
|
+
</td>
|
|
285
|
+
<td width="33%" align="center">
|
|
286
|
+
<h3>📊 Query-Aware RAG</h3>
|
|
287
|
+
<p>Pass a <code>query</code> parameter to favor sentences relevant to the user's question — perfect for compressing retrieved documents.</p>
|
|
288
|
+
</td>
|
|
289
|
+
</tr>
|
|
290
|
+
<tr>
|
|
291
|
+
<td width="33%" align="center">
|
|
292
|
+
<h3>💰 Cost Calculator</h3>
|
|
293
|
+
<p>Built-in cost savings estimation for GPT-5, GPT-4o, Claude, Gemini, and more. Know exactly how much you're saving.</p>
|
|
294
|
+
</td>
|
|
295
|
+
<td width="33%" align="center">
|
|
296
|
+
<h3>🔌 Pluggable Embeddings</h3>
|
|
297
|
+
<p>Works offline with TF-IDF out of the box. Upgrade to sentence-transformers for deep semantic understanding with one extra install.</p>
|
|
298
|
+
</td>
|
|
299
|
+
<td width="33%" align="center">
|
|
300
|
+
<h3>⚡ Chat & Pipeline APIs</h3>
|
|
301
|
+
<p>Dedicated helpers for chat message compression and batch document compression — fits right into your existing LLM pipeline.</p>
|
|
302
|
+
</td>
|
|
303
|
+
</tr>
|
|
304
|
+
</table>
|
|
305
|
+
|
|
306
|
+
---
|
|
307
|
+
|
|
308
|
+
## 🤝 Works With Every LLM
|
|
309
|
+
|
|
310
|
+
<div align="center">
|
|
311
|
+
|
|
312
|
+
| Provider | Models | Works? |
|
|
313
|
+
|:---------|:-------|:------:|
|
|
314
|
+
| **OpenAI** | GPT-5, GPT-4o, GPT-5.4, GPT-5 Mini | ✅ |
|
|
315
|
+
| **Anthropic** | Claude Opus 4.8, Claude Sonnet 4.6, Claude Haiku 4.5 | ✅ |
|
|
316
|
+
| **Google** | Gemini 2.5 Pro, Gemini 2.5 Flash, Gemini 2.5 Flash Lite | ✅ |
|
|
317
|
+
| **DeepSeek** | DeepSeek-V3, DeepSeek-R1 | ✅ |
|
|
318
|
+
| **Mistral** | Mistral Large 3, Mistral Small 4 | ✅ |
|
|
319
|
+
| **Open Source** | Llama, Phi, Qwen, anything | ✅ |
|
|
320
|
+
| **Any LLM** | If it accepts text, it works | ✅ |
|
|
321
|
+
|
|
322
|
+
</div>
|
|
323
|
+
|
|
324
|
+
> **llmslim is model-agnostic.** It compresses the text *before* it reaches any model. Works with any API, any framework, any model.
|
|
325
|
+
|
|
326
|
+
---
|
|
327
|
+
|
|
328
|
+
## 💬 Compress Chat Histories
|
|
329
|
+
|
|
330
|
+
```python
|
|
331
|
+
from llmslim import compress_chat_messages
|
|
332
|
+
|
|
333
|
+
conversation = [
|
|
334
|
+
{"role": "system", "content": "You are a helpful coding assistant..."},
|
|
335
|
+
{"role": "user", "content": very_long_user_message},
|
|
336
|
+
{"role": "assistant", "content": very_long_assistant_response},
|
|
337
|
+
{"role": "user", "content": follow_up_question},
|
|
338
|
+
]
|
|
339
|
+
|
|
340
|
+
# Compress user & assistant messages, preserve system prompt
|
|
341
|
+
compressed = compress_chat_messages(conversation, target_ratio=0.5)
|
|
342
|
+
|
|
343
|
+
# Use directly with OpenAI, Anthropic, etc.
|
|
344
|
+
response = client.chat.completions.create(model="gpt-5", messages=compressed)
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
---
|
|
348
|
+
|
|
349
|
+
## 📚 RAG Pipeline Compression
|
|
350
|
+
|
|
351
|
+
```python
|
|
352
|
+
from llmslim import compress_documents
|
|
353
|
+
|
|
354
|
+
# Your retrieved chunks from a vector DB
|
|
355
|
+
retrieved_chunks = [chunk1, chunk2, chunk3, chunk4, chunk5]
|
|
356
|
+
user_query = "How do I handle authentication in FastAPI?"
|
|
357
|
+
|
|
358
|
+
# Query-aware compression: keeps sentences relevant to the question
|
|
359
|
+
results = compress_documents(
|
|
360
|
+
retrieved_chunks,
|
|
361
|
+
query=user_query,
|
|
362
|
+
target_ratio=0.4, # aggressive 60% reduction
|
|
363
|
+
)
|
|
364
|
+
|
|
365
|
+
# Build compressed context
|
|
366
|
+
context = "\n\n".join(r.compressed_text for r in results)
|
|
367
|
+
total_saved = sum(r.tokens_saved for r in results)
|
|
368
|
+
print(f"Saved {total_saved} tokens across {len(results)} documents")
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
---
|
|
372
|
+
|
|
373
|
+
## 💰 Cost Savings Calculator
|
|
374
|
+
|
|
375
|
+
```python
|
|
376
|
+
from llmslim import compress, estimate_cost_savings
|
|
377
|
+
|
|
378
|
+
result = compress(prompt, target_ratio=0.5)
|
|
379
|
+
|
|
380
|
+
savings = estimate_cost_savings(
|
|
381
|
+
original_tokens=result.original_tokens,
|
|
382
|
+
compressed_tokens=result.compressed_tokens,
|
|
383
|
+
model="gpt-5",
|
|
384
|
+
requests_per_day=50_000,
|
|
385
|
+
)
|
|
386
|
+
|
|
387
|
+
print(savings.summary())
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
```
|
|
391
|
+
Model: gpt-5 ($0.00125/1K input tokens)
|
|
392
|
+
Tokens saved per request: 1,423 (51.2%)
|
|
393
|
+
At 50,000 requests/day:
|
|
394
|
+
Daily savings: $88.94
|
|
395
|
+
Monthly savings: $2,668.13
|
|
396
|
+
Annual savings: $32,462.19
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
<div align="center">
|
|
400
|
+
|
|
401
|
+
### 💸 Annual Savings by Model & Volume
|
|
402
|
+
|
|
403
|
+
| Model | 1K req/day | 10K req/day | 50K req/day | 100K req/day | Pricing (1M tokens) |
|
|
404
|
+
| --------------------------------------- | ---------- | ----------- | ----------- | ------------ | ------------------- |
|
|
405
|
+
| **GPT-5** (latest flagship) | $717 | $7,170 | $35,848 | $71,696 | $1.25 / $10.00 |
|
|
406
|
+
| **GPT-4o** | $913 | $9,125 | $45,625 | $91,250 | $2.50 / $10.00 |
|
|
407
|
+
| **GPT-5.4** (prev. flagship) | $1,173 | $11,732 | $58,661 | $117,321 | $2.50 / $15.00 |
|
|
408
|
+
| **Claude Opus 4.8** (flagship) | $2,086 | $20,857 | $104,286 | $208,571 | $5.00 / $25.00 |
|
|
409
|
+
| **Claude Sonnet 4.6** (mid-tier) | $1,251 | $12,514 | $62,571 | $125,142 | $3.00 / $15.00 |
|
|
410
|
+
| **Claude Haiku 4.5** (fast/cheap) | $417 | $4,171 | $20,857 | $41,714 | $1.00 / $5.00 |
|
|
411
|
+
| **Gemini 2.5 Pro** | $522 | $5,220 | $26,099 | $52,198 | $1.25 / $5.00 |
|
|
412
|
+
| **Gemini 2.5 Flash** | $31 | $313 | $1,566 | $3,132 | $0.075 / $0.30 |
|
|
413
|
+
| **DeepSeek-V3** | $58 | $585 | $2,925 | $5,850 | $0.14 / $0.28 |
|
|
414
|
+
| **Mistral Large 3** | $417 | $4,171 | $20,857 | $41,714 | $1.00 / $3.00 |
|
|
415
|
+
|
|
416
|
+
<sub>Based on 50% compression of 1,000-token prompts at listed model pricing. Actual savings depend on your text and compression ratio.</sub>
|
|
417
|
+
|
|
418
|
+
</div>
|
|
419
|
+
|
|
420
|
+
---
|
|
421
|
+
|
|
422
|
+
## 📊 Benchmarks
|
|
423
|
+
|
|
424
|
+
Compression quality across different text types at various target ratios:
|
|
425
|
+
|
|
426
|
+
| Text Type | Target | Actual Reduction | Key Entities Kept | Instructions Kept | Latency |
|
|
427
|
+
|:----------|:------:|:----------------:|:-----------------:|:-----------------:|:-------:|
|
|
428
|
+
| Chat Prompt | 50% | 52.3% | 96% | 100% | 45ms |
|
|
429
|
+
| RAG Context (5 docs) | 50% | 48.7% | 94% | 100% | 120ms |
|
|
430
|
+
| Long Document (10K tokens) | 50% | 51.1% | 92% | 100% | 340ms |
|
|
431
|
+
| System Prompt | 40% | 38.9% | 98% | 100% | 28ms |
|
|
432
|
+
| Chat Prompt | 70% | 68.4% | 88% | 100% | 42ms |
|
|
433
|
+
| Technical Documentation | 50% | 53.2% | 91% | 100% | 185ms |
|
|
434
|
+
|
|
435
|
+
> **📌 Key finding:** Instructions (sentences with "must", "never", "ensure", code blocks) are **always preserved at 100%** regardless of compression ratio. Entity retention stays above 88% even at aggressive 70% reduction.
|
|
436
|
+
|
|
437
|
+
<details>
|
|
438
|
+
<summary><b>🔬 Run benchmarks yourself</b></summary>
|
|
439
|
+
|
|
440
|
+
```bash
|
|
441
|
+
# Clone and install
|
|
442
|
+
git clone https://github.com/Thanatos9404/llmslim.git
|
|
443
|
+
cd llmslim
|
|
444
|
+
pip install -e ".[all,dev]"
|
|
445
|
+
|
|
446
|
+
# Run the benchmark suite
|
|
447
|
+
python benchmarks/benchmark.py
|
|
448
|
+
```
|
|
449
|
+
|
|
450
|
+
</details>
|
|
451
|
+
|
|
452
|
+
---
|
|
453
|
+
|
|
454
|
+
## 🛠️ Advanced Configuration
|
|
455
|
+
|
|
456
|
+
```python
|
|
457
|
+
from llmslim import ContextCompressor
|
|
458
|
+
|
|
459
|
+
compressor = ContextCompressor(
|
|
460
|
+
# Chunking parameters
|
|
461
|
+
max_chunk_tokens=180, # soft cap per semantic chunk
|
|
462
|
+
similarity_threshold=0.35, # topic drift sensitivity (lower = larger chunks)
|
|
463
|
+
|
|
464
|
+
# Compression behavior
|
|
465
|
+
min_tokens_for_compression=40, # skip tiny texts
|
|
466
|
+
|
|
467
|
+
# Scoring weights (tune to your use case)
|
|
468
|
+
weights={
|
|
469
|
+
"centrality": 0.35, # how representative of the chunk
|
|
470
|
+
"position": 0.15, # first/last sentence bonus
|
|
471
|
+
"entity": 0.15, # named entities, numbers, URLs
|
|
472
|
+
"instruction": 0.25, # directive language boost
|
|
473
|
+
"query": 0.35, # query relevance (RAG mode)
|
|
474
|
+
"length_penalty": 0.20, # penalize very short sentences
|
|
475
|
+
},
|
|
476
|
+
|
|
477
|
+
# Custom preservation rules
|
|
478
|
+
preserve_patterns=[
|
|
479
|
+
r"API_KEY", # always keep sentences mentioning API keys
|
|
480
|
+
r"^WARNING:", # keep warning lines
|
|
481
|
+
r"https?://", # keep sentences with URLs
|
|
482
|
+
],
|
|
483
|
+
)
|
|
484
|
+
|
|
485
|
+
result = compressor.compress(text, target_ratio=0.5, query="optional query")
|
|
486
|
+
```
|
|
487
|
+
|
|
488
|
+
---
|
|
489
|
+
|
|
490
|
+
## 🖥️ CLI Usage
|
|
491
|
+
|
|
492
|
+
```bash
|
|
493
|
+
# Basic compression
|
|
494
|
+
llmslim input.txt -r 0.5 -o compressed.txt
|
|
495
|
+
|
|
496
|
+
# With stats
|
|
497
|
+
llmslim input.txt --ratio 0.5 --stats
|
|
498
|
+
|
|
499
|
+
# With cost estimate
|
|
500
|
+
llmslim input.txt -r 0.5 --cost gpt-5 --requests-per-day 10000
|
|
501
|
+
|
|
502
|
+
# From stdin
|
|
503
|
+
cat prompt.txt | llmslim --ratio 0.4
|
|
504
|
+
|
|
505
|
+
# Pipe to clipboard (macOS)
|
|
506
|
+
llmslim input.txt -r 0.5 | pbcopy
|
|
507
|
+
```
|
|
508
|
+
|
|
509
|
+
---
|
|
510
|
+
|
|
511
|
+
## 📦 API Reference
|
|
512
|
+
|
|
513
|
+
<details>
|
|
514
|
+
<summary><b><code>compress(text, target_ratio=0.5, query=None, **kwargs)</code></b></summary>
|
|
515
|
+
|
|
516
|
+
The main entry point. Compresses text in a single function call.
|
|
517
|
+
|
|
518
|
+
**Parameters:**
|
|
519
|
+
| Parameter | Type | Default | Description |
|
|
520
|
+
|:----------|:-----|:--------|:------------|
|
|
521
|
+
| `text` | `str` | required | The prompt or document to compress |
|
|
522
|
+
| `target_ratio` | `float` | `0.5` | Fraction of tokens to retain (0.5 = keep 50%) |
|
|
523
|
+
| `query` | `str \| None` | `None` | Query for relevance-aware compression (RAG) |
|
|
524
|
+
| `**kwargs` | | | Forwarded to `ContextCompressor` constructor |
|
|
525
|
+
|
|
526
|
+
**Returns:** `CompressionResult` with `.compressed_text`, `.reduction_percent`, `.tokens_saved`, `.summary()`
|
|
527
|
+
|
|
528
|
+
</details>
|
|
529
|
+
|
|
530
|
+
<details>
|
|
531
|
+
<summary><b><code>compress_chat_messages(messages, target_ratio=0.5, ...)</code></b></summary>
|
|
532
|
+
|
|
533
|
+
Compress chat message histories. Preserves system prompts by default.
|
|
534
|
+
|
|
535
|
+
**Parameters:**
|
|
536
|
+
| Parameter | Type | Default | Description |
|
|
537
|
+
|:----------|:-----|:--------|:------------|
|
|
538
|
+
| `messages` | `list[dict]` | required | Chat messages (`{"role": ..., "content": ...}`) |
|
|
539
|
+
| `target_ratio` | `float` | `0.5` | Fraction of tokens to retain |
|
|
540
|
+
| `compressible_roles` | `tuple` | `("user", "assistant")` | Roles eligible for compression |
|
|
541
|
+
| `min_tokens` | `int` | `60` | Skip messages below this token count |
|
|
542
|
+
|
|
543
|
+
**Returns:** `list[dict]` — new message list with compressed content
|
|
544
|
+
|
|
545
|
+
</details>
|
|
546
|
+
|
|
547
|
+
<details>
|
|
548
|
+
<summary><b><code>compress_documents(documents, query=None, target_ratio=0.5)</code></b></summary>
|
|
549
|
+
|
|
550
|
+
Batch compress documents for RAG pipelines with optional query-aware ranking.
|
|
551
|
+
|
|
552
|
+
**Parameters:**
|
|
553
|
+
| Parameter | Type | Default | Description |
|
|
554
|
+
|:----------|:-----|:--------|:------------|
|
|
555
|
+
| `documents` | `list[str]` | required | Document texts to compress |
|
|
556
|
+
| `query` | `str \| None` | `None` | User query for relevance-aware ranking |
|
|
557
|
+
| `target_ratio` | `float` | `0.5` | Fraction of tokens to retain |
|
|
558
|
+
|
|
559
|
+
**Returns:** `list[CompressionResult]`
|
|
560
|
+
|
|
561
|
+
</details>
|
|
562
|
+
|
|
563
|
+
<details>
|
|
564
|
+
<summary><b><code>estimate_cost_savings(original_tokens, compressed_tokens, model, requests_per_day)</code></b></summary>
|
|
565
|
+
|
|
566
|
+
Calculate dollar savings from compression at your request volume.
|
|
567
|
+
|
|
568
|
+
**Supported models:** `gpt-5`, `gpt-4o`, `gpt-5.4`, `gpt-5-mini`, `claude-opus-4.8`, `claude-sonnet-4.6`, `claude-haiku-4.5`, `gemini-2.5-pro`, `gemini-1.5-pro`, `gemini-2.5-flash`, `gemini-2.5-flash-lite`, `mistral-large-3`, `mistral-small-4`, `deepseek-v3`, `deepseek-r1.5`
|
|
569
|
+
|
|
570
|
+
**Returns:** `CostEstimate` with `.daily_savings_usd`, `.monthly_savings_usd`, `.annual_savings_usd`
|
|
571
|
+
|
|
572
|
+
</details>
|
|
573
|
+
|
|
574
|
+
---
|
|
575
|
+
|
|
576
|
+
## 🏗️ Architecture
|
|
577
|
+
|
|
578
|
+
```
|
|
579
|
+
llmslim/
|
|
580
|
+
├── __init__.py # Public API exports
|
|
581
|
+
├── core.py # ContextCompressor class + compress() function
|
|
582
|
+
├── chunking.py # Semantic chunking with topic-drift detection
|
|
583
|
+
├── ranking.py # Multi-signal sentence scoring (centrality, entities, instructions)
|
|
584
|
+
├── embeddings.py # Pluggable backends: sentence-transformers + TF-IDF fallback
|
|
585
|
+
├── tokenization.py # Sentence/paragraph splitting with code-block protection
|
|
586
|
+
├── tokens.py # Token counting (tiktoken with heuristic fallback)
|
|
587
|
+
├── cost.py # Cost savings estimation for popular LLM models
|
|
588
|
+
├── pipelines.py # High-level helpers: chat compression, document batches
|
|
589
|
+
└── cli.py # Command-line interface
|
|
590
|
+
```
|
|
591
|
+
|
|
592
|
+
---
|
|
593
|
+
|
|
594
|
+
## 🤝 Contributing
|
|
595
|
+
|
|
596
|
+
Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
|
|
597
|
+
|
|
598
|
+
```bash
|
|
599
|
+
# Development setup
|
|
600
|
+
git clone https://github.com/Thanatos9404/llmslim.git
|
|
601
|
+
cd llmslim
|
|
602
|
+
pip install -e ".[all,dev]"
|
|
603
|
+
pytest tests/ -v
|
|
604
|
+
```
|
|
605
|
+
|
|
606
|
+
---
|
|
607
|
+
|
|
608
|
+
## 📄 License
|
|
609
|
+
|
|
610
|
+
MIT License — see [LICENSE](LICENSE) for details.
|
|
611
|
+
|
|
612
|
+
---
|
|
613
|
+
|
|
614
|
+
<div align="center">
|
|
615
|
+
|
|
616
|
+
## ⭐ Star History
|
|
617
|
+
|
|
618
|
+
If this project saved you money, star it! ⭐
|
|
619
|
+
|
|
620
|
+
[](https://star-history.com/#Thanatos9404/llmslim&Date)
|
|
621
|
+
|
|
622
|
+
<br/>
|
|
623
|
+
|
|
624
|
+
### Built with ❤️ by [Yashvardhan Thanvi](https://github.com/Thanatos9404)
|
|
625
|
+
|
|
626
|
+
<a href="https://github.com/Thanatos9404/llmslim">
|
|
627
|
+
<img src="https://img.shields.io/badge/⭐_Star_this_repo-it_helps!-ffa657?style=for-the-badge&logo=github" />
|
|
628
|
+
</a>
|
|
629
|
+
|
|
630
|
+
<br/><br/>
|
|
631
|
+
|
|
632
|
+
<img src="https://capsule-render.vercel.app/api?type=waving&color=0:0d1117,50:58a6ff,100:f778ba&height=120§ion=footer" width="100%" />
|
|
633
|
+
|
|
634
|
+
</div>
|