delbina 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.
- delbina-0.1.0/LICENSE +201 -0
- delbina-0.1.0/PKG-INFO +95 -0
- delbina-0.1.0/README.md +72 -0
- delbina-0.1.0/pyproject.toml +37 -0
- delbina-0.1.0/setup.cfg +4 -0
- delbina-0.1.0/src/delbina/__init__.py +12 -0
- delbina-0.1.0/src/delbina/cli.py +43 -0
- delbina-0.1.0/src/delbina/compress.py +58 -0
- delbina-0.1.0/src/delbina/ollama.py +32 -0
- delbina-0.1.0/src/delbina/tokens.py +23 -0
- delbina-0.1.0/src/delbina.egg-info/PKG-INFO +95 -0
- delbina-0.1.0/src/delbina.egg-info/SOURCES.txt +17 -0
- delbina-0.1.0/src/delbina.egg-info/dependency_links.txt +1 -0
- delbina-0.1.0/src/delbina.egg-info/entry_points.txt +2 -0
- delbina-0.1.0/src/delbina.egg-info/requires.txt +6 -0
- delbina-0.1.0/src/delbina.egg-info/top_level.txt +1 -0
- delbina-0.1.0/tests/test_cli.py +21 -0
- delbina-0.1.0/tests/test_compress.py +25 -0
- delbina-0.1.0/tests/test_tokens.py +15 -0
delbina-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
delbina-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: delbina
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Context-compression layer that cuts the token cost of long LLM chats
|
|
5
|
+
Author: Krupakar SB
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/delbina/delbina
|
|
8
|
+
Project-URL: Issues, https://github.com/delbina/delbina/issues
|
|
9
|
+
Keywords: llm,tokens,context,compression,chat
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: tiktoken>=0.7
|
|
18
|
+
Provides-Extra: dev
|
|
19
|
+
Requires-Dist: pytest; extra == "dev"
|
|
20
|
+
Requires-Dist: build; extra == "dev"
|
|
21
|
+
Requires-Dist: twine; extra == "dev"
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
<p align="center"><img src="https://raw.githubusercontent.com/delbina/delbina/main/brand/delbina-logo-transparent-1024.png" width="160" alt="delbina"></p>
|
|
25
|
+
|
|
26
|
+
# delbina
|
|
27
|
+
|
|
28
|
+
A context-compression layer that sits in front of existing LLMs to cut the token cost of long chats.
|
|
29
|
+
|
|
30
|
+
Every chat turn re-sends the whole history, so total token cost grows roughly quadratically with chat length. delbina measures that cost and compresses the history before it reaches the model.
|
|
31
|
+
|
|
32
|
+
> **Status: alpha (0.x).** Token-cost measurement and simple strategies work. Answer-quality evaluation is not built yet, so savings numbers say nothing about whether the model still answers correctly. The API may change.
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install delbina
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
On first use, tiktoken downloads its encoding file, so the first run needs network access.
|
|
41
|
+
|
|
42
|
+
## Quick start
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from delbina import cost, full, last_n, rolling_summary
|
|
46
|
+
|
|
47
|
+
turns = ["user: ...", "assistant: ...", "user: ...", "assistant: ..."]
|
|
48
|
+
|
|
49
|
+
print(cost(turns, full)) # tokens if full history is re-sent every turn
|
|
50
|
+
print(cost(turns, last_n(4))) # tokens if only the last 4 turns are sent
|
|
51
|
+
|
|
52
|
+
context = rolling_summary(keep=2)(turns) # what you would actually send
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### With a local model (Ollama)
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from delbina import ollama_summarizer, rolling_summary
|
|
59
|
+
|
|
60
|
+
strategy = rolling_summary(keep=4, summarize=ollama_summarizer("qwen2.5:1.5b"))
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Requires a running [Ollama](https://ollama.com) server. No extra Python dependencies.
|
|
64
|
+
|
|
65
|
+
## CLI
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
delbina bench chat.json # compare strategies
|
|
69
|
+
delbina bench chat.json --ollama qwen2.5:1.5b # use a local model for summaries
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
`chat.json` format: `{"turns": ["...", "..."]}`
|
|
73
|
+
|
|
74
|
+
## Strategies
|
|
75
|
+
|
|
76
|
+
| Strategy | What is sent each turn |
|
|
77
|
+
|---|---|
|
|
78
|
+
| `full` | the whole history (baseline) |
|
|
79
|
+
| `last_n(n)` | the last n turns |
|
|
80
|
+
| `head_tail(h, t)` | the first h turns (task setup) + the last t turns |
|
|
81
|
+
| `rolling_summary(keep, summarize)` | a summary of older turns + the last `keep` turns |
|
|
82
|
+
|
|
83
|
+
Note: `cost()` counts tokens sent to the main model. It does not yet count the tokens spent by the summarizer itself.
|
|
84
|
+
|
|
85
|
+
## Development
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
python -m venv .venv
|
|
89
|
+
pip install -e ".[dev]"
|
|
90
|
+
pytest -q
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## License
|
|
94
|
+
|
|
95
|
+
Apache-2.0
|
delbina-0.1.0/README.md
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
<p align="center"><img src="https://raw.githubusercontent.com/delbina/delbina/main/brand/delbina-logo-transparent-1024.png" width="160" alt="delbina"></p>
|
|
2
|
+
|
|
3
|
+
# delbina
|
|
4
|
+
|
|
5
|
+
A context-compression layer that sits in front of existing LLMs to cut the token cost of long chats.
|
|
6
|
+
|
|
7
|
+
Every chat turn re-sends the whole history, so total token cost grows roughly quadratically with chat length. delbina measures that cost and compresses the history before it reaches the model.
|
|
8
|
+
|
|
9
|
+
> **Status: alpha (0.x).** Token-cost measurement and simple strategies work. Answer-quality evaluation is not built yet, so savings numbers say nothing about whether the model still answers correctly. The API may change.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install delbina
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
On first use, tiktoken downloads its encoding file, so the first run needs network access.
|
|
18
|
+
|
|
19
|
+
## Quick start
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from delbina import cost, full, last_n, rolling_summary
|
|
23
|
+
|
|
24
|
+
turns = ["user: ...", "assistant: ...", "user: ...", "assistant: ..."]
|
|
25
|
+
|
|
26
|
+
print(cost(turns, full)) # tokens if full history is re-sent every turn
|
|
27
|
+
print(cost(turns, last_n(4))) # tokens if only the last 4 turns are sent
|
|
28
|
+
|
|
29
|
+
context = rolling_summary(keep=2)(turns) # what you would actually send
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
### With a local model (Ollama)
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from delbina import ollama_summarizer, rolling_summary
|
|
36
|
+
|
|
37
|
+
strategy = rolling_summary(keep=4, summarize=ollama_summarizer("qwen2.5:1.5b"))
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Requires a running [Ollama](https://ollama.com) server. No extra Python dependencies.
|
|
41
|
+
|
|
42
|
+
## CLI
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
delbina bench chat.json # compare strategies
|
|
46
|
+
delbina bench chat.json --ollama qwen2.5:1.5b # use a local model for summaries
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`chat.json` format: `{"turns": ["...", "..."]}`
|
|
50
|
+
|
|
51
|
+
## Strategies
|
|
52
|
+
|
|
53
|
+
| Strategy | What is sent each turn |
|
|
54
|
+
|---|---|
|
|
55
|
+
| `full` | the whole history (baseline) |
|
|
56
|
+
| `last_n(n)` | the last n turns |
|
|
57
|
+
| `head_tail(h, t)` | the first h turns (task setup) + the last t turns |
|
|
58
|
+
| `rolling_summary(keep, summarize)` | a summary of older turns + the last `keep` turns |
|
|
59
|
+
|
|
60
|
+
Note: `cost()` counts tokens sent to the main model. It does not yet count the tokens spent by the summarizer itself.
|
|
61
|
+
|
|
62
|
+
## Development
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
python -m venv .venv
|
|
66
|
+
pip install -e ".[dev]"
|
|
67
|
+
pytest -q
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## License
|
|
71
|
+
|
|
72
|
+
Apache-2.0
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "delbina"
|
|
3
|
+
dynamic = ["version"]
|
|
4
|
+
description = "Context-compression layer that cuts the token cost of long LLM chats"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
authors = [{ name = "Krupakar SB" }]
|
|
9
|
+
requires-python = ">=3.10"
|
|
10
|
+
dependencies = ["tiktoken>=0.7"]
|
|
11
|
+
keywords = ["llm", "tokens", "context", "compression", "chat"]
|
|
12
|
+
classifiers = [
|
|
13
|
+
"Development Status :: 3 - Alpha",
|
|
14
|
+
"Intended Audience :: Developers",
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
[project.optional-dependencies]
|
|
20
|
+
dev = ["pytest", "build", "twine"]
|
|
21
|
+
|
|
22
|
+
[project.scripts]
|
|
23
|
+
delbina = "delbina.cli:main"
|
|
24
|
+
|
|
25
|
+
[project.urls]
|
|
26
|
+
Homepage = "https://github.com/delbina/delbina"
|
|
27
|
+
Issues = "https://github.com/delbina/delbina/issues"
|
|
28
|
+
|
|
29
|
+
[build-system]
|
|
30
|
+
requires = ["setuptools>=77"]
|
|
31
|
+
build-backend = "setuptools.build_meta"
|
|
32
|
+
|
|
33
|
+
[tool.setuptools.dynamic]
|
|
34
|
+
version = { attr = "delbina.__version__" }
|
|
35
|
+
|
|
36
|
+
[tool.setuptools.packages.find]
|
|
37
|
+
where = ["src"]
|
delbina-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""delbina: compress chat context before it reaches the model."""
|
|
2
|
+
__version__ = "0.1.0"
|
|
3
|
+
|
|
4
|
+
from .compress import cost, full, head_tail, last_n, naive_summarizer, rolling_summary
|
|
5
|
+
from .ollama import ollama_summarizer
|
|
6
|
+
from .tokens import count, cumulative_cost
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"__version__", "count", "cumulative_cost", "cost",
|
|
10
|
+
"full", "last_n", "head_tail", "rolling_summary",
|
|
11
|
+
"naive_summarizer", "ollama_summarizer",
|
|
12
|
+
]
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Command line: `delbina bench chat.json [--ollama MODEL]`."""
|
|
2
|
+
import argparse
|
|
3
|
+
import json
|
|
4
|
+
import sys
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from . import __version__
|
|
8
|
+
from .compress import cost, full, head_tail, last_n, rolling_summary
|
|
9
|
+
from .tokens import count
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def bench(path: Path, ollama_model: str | None = None) -> None:
|
|
13
|
+
turns = json.loads(path.read_text(encoding="utf-8"))["turns"]
|
|
14
|
+
summarizer = None
|
|
15
|
+
if ollama_model:
|
|
16
|
+
from .ollama import ollama_summarizer
|
|
17
|
+
summarizer = ollama_summarizer(ollama_model)
|
|
18
|
+
strategies = [full, last_n(4), head_tail(1, 3)]
|
|
19
|
+
strategies.append(rolling_summary(keep=2, summarize=summarizer) if summarizer else rolling_summary(keep=2))
|
|
20
|
+
|
|
21
|
+
base = cost(turns, full)
|
|
22
|
+
print(f"{path.name}: {len(turns)} turns, {sum(count(t) for t in turns)} tokens once\n")
|
|
23
|
+
print(f"{'strategy':<16}{'tokens':>8}{'saved':>8}")
|
|
24
|
+
for s in strategies:
|
|
25
|
+
c = cost(turns, s)
|
|
26
|
+
print(f"{s.__name__:<16}{c:>8}{1 - c / base:>8.0%}")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def main(argv: list[str] | None = None) -> int:
|
|
30
|
+
p = argparse.ArgumentParser(prog="delbina", description="Measure and compress chat context token cost.")
|
|
31
|
+
p.add_argument("--version", action="version", version=f"delbina {__version__}")
|
|
32
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
33
|
+
b = sub.add_parser("bench", help="compare strategy token cost on a chat JSON file")
|
|
34
|
+
b.add_argument("file", type=Path, help='JSON file: {"turns": ["...", ...]}')
|
|
35
|
+
b.add_argument("--ollama", metavar="MODEL", help="use a local Ollama model for rolling_summary")
|
|
36
|
+
args = p.parse_args(argv)
|
|
37
|
+
if args.cmd == "bench":
|
|
38
|
+
bench(args.file, args.ollama)
|
|
39
|
+
return 0
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
if __name__ == "__main__":
|
|
43
|
+
sys.exit(main())
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Compression strategies.
|
|
2
|
+
|
|
3
|
+
A strategy maps the chat history so far (list of turns) to the context
|
|
4
|
+
actually sent to the model on that turn.
|
|
5
|
+
"""
|
|
6
|
+
from typing import Callable
|
|
7
|
+
|
|
8
|
+
from .tokens import count
|
|
9
|
+
|
|
10
|
+
Strategy = Callable[[list[str]], list[str]]
|
|
11
|
+
Summarizer = Callable[[list[str]], str]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def full(history: list[str]) -> list[str]:
|
|
15
|
+
"""Baseline: send everything."""
|
|
16
|
+
return history
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def last_n(n: int) -> Strategy:
|
|
20
|
+
"""Keep only the last n turns."""
|
|
21
|
+
def s(history: list[str]) -> list[str]:
|
|
22
|
+
return history[-n:]
|
|
23
|
+
s.__name__ = f"last_{n}"
|
|
24
|
+
return s
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def head_tail(head: int, tail: int) -> Strategy:
|
|
28
|
+
"""Keep the first `head` turns (task setup) and the last `tail` turns."""
|
|
29
|
+
def s(history: list[str]) -> list[str]:
|
|
30
|
+
if len(history) <= head + tail:
|
|
31
|
+
return history
|
|
32
|
+
return history[:head] + history[-tail:]
|
|
33
|
+
s.__name__ = f"head{head}_tail{tail}"
|
|
34
|
+
return s
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def naive_summarizer(turns: list[str], max_words: int = 12) -> str:
|
|
38
|
+
"""Placeholder: first few words of each turn. Swap for a local LLM later."""
|
|
39
|
+
return " | ".join(" ".join(t.split()[:max_words]) for t in turns)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def rolling_summary(keep: int, summarize: Summarizer = naive_summarizer) -> Strategy:
|
|
43
|
+
"""Summarize everything except the last `keep` turns."""
|
|
44
|
+
def s(history: list[str]) -> list[str]:
|
|
45
|
+
if len(history) <= keep:
|
|
46
|
+
return history
|
|
47
|
+
old, recent = history[:-keep], history[-keep:]
|
|
48
|
+
return ["[summary] " + summarize(old)] + recent
|
|
49
|
+
s.__name__ = f"summary_keep{keep}"
|
|
50
|
+
return s
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def cost(turns: list[str], strategy: Strategy) -> int:
|
|
54
|
+
"""Total tokens sent across the chat under a strategy."""
|
|
55
|
+
return sum(
|
|
56
|
+
sum(count(t) for t in strategy(turns[: i + 1]))
|
|
57
|
+
for i in range(len(turns))
|
|
58
|
+
)
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Summarizer backed by a local Ollama server (stdlib only, no extra deps)."""
|
|
2
|
+
import json
|
|
3
|
+
import urllib.request
|
|
4
|
+
|
|
5
|
+
from .compress import Summarizer
|
|
6
|
+
|
|
7
|
+
PROMPT = (
|
|
8
|
+
"Summarize the following chat turns as compactly as possible. "
|
|
9
|
+
"Keep facts, decisions, names, numbers and open questions. "
|
|
10
|
+
"Drop greetings and filler.\n\n{chat}\n\nSummary:"
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def ollama_summarizer(
|
|
15
|
+
model: str = "qwen2.5:1.5b",
|
|
16
|
+
host: str = "http://localhost:11434",
|
|
17
|
+
timeout: float = 120.0,
|
|
18
|
+
) -> Summarizer:
|
|
19
|
+
"""Return a summarizer that calls Ollama's /api/generate endpoint."""
|
|
20
|
+
url = host.rstrip("/") + "/api/generate"
|
|
21
|
+
|
|
22
|
+
def summarize(turns: list[str]) -> str:
|
|
23
|
+
body = json.dumps({
|
|
24
|
+
"model": model,
|
|
25
|
+
"prompt": PROMPT.format(chat="\n".join(f"- {t}" for t in turns)),
|
|
26
|
+
"stream": False,
|
|
27
|
+
}).encode()
|
|
28
|
+
req = urllib.request.Request(url, data=body, headers={"Content-Type": "application/json"})
|
|
29
|
+
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
30
|
+
return json.loads(r.read())["response"].strip()
|
|
31
|
+
|
|
32
|
+
return summarize
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from functools import lru_cache
|
|
2
|
+
|
|
3
|
+
import tiktoken
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@lru_cache(maxsize=None)
|
|
7
|
+
def _encoding(name: str = "cl100k_base") -> tiktoken.Encoding:
|
|
8
|
+
# Loaded lazily: tiktoken downloads the file on first use, so importing
|
|
9
|
+
# delbina must not need network.
|
|
10
|
+
return tiktoken.get_encoding(name)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def count(text: str) -> int:
|
|
14
|
+
return len(_encoding().encode(text))
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def cumulative_cost(turns: list[str]) -> int:
|
|
18
|
+
"""Total tokens if the full history is re-sent each turn."""
|
|
19
|
+
total, history = 0, 0
|
|
20
|
+
for t in turns:
|
|
21
|
+
history += count(t)
|
|
22
|
+
total += history
|
|
23
|
+
return total
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: delbina
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Context-compression layer that cuts the token cost of long LLM chats
|
|
5
|
+
Author: Krupakar SB
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/delbina/delbina
|
|
8
|
+
Project-URL: Issues, https://github.com/delbina/delbina/issues
|
|
9
|
+
Keywords: llm,tokens,context,compression,chat
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: tiktoken>=0.7
|
|
18
|
+
Provides-Extra: dev
|
|
19
|
+
Requires-Dist: pytest; extra == "dev"
|
|
20
|
+
Requires-Dist: build; extra == "dev"
|
|
21
|
+
Requires-Dist: twine; extra == "dev"
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
<p align="center"><img src="https://raw.githubusercontent.com/delbina/delbina/main/brand/delbina-logo-transparent-1024.png" width="160" alt="delbina"></p>
|
|
25
|
+
|
|
26
|
+
# delbina
|
|
27
|
+
|
|
28
|
+
A context-compression layer that sits in front of existing LLMs to cut the token cost of long chats.
|
|
29
|
+
|
|
30
|
+
Every chat turn re-sends the whole history, so total token cost grows roughly quadratically with chat length. delbina measures that cost and compresses the history before it reaches the model.
|
|
31
|
+
|
|
32
|
+
> **Status: alpha (0.x).** Token-cost measurement and simple strategies work. Answer-quality evaluation is not built yet, so savings numbers say nothing about whether the model still answers correctly. The API may change.
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install delbina
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
On first use, tiktoken downloads its encoding file, so the first run needs network access.
|
|
41
|
+
|
|
42
|
+
## Quick start
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from delbina import cost, full, last_n, rolling_summary
|
|
46
|
+
|
|
47
|
+
turns = ["user: ...", "assistant: ...", "user: ...", "assistant: ..."]
|
|
48
|
+
|
|
49
|
+
print(cost(turns, full)) # tokens if full history is re-sent every turn
|
|
50
|
+
print(cost(turns, last_n(4))) # tokens if only the last 4 turns are sent
|
|
51
|
+
|
|
52
|
+
context = rolling_summary(keep=2)(turns) # what you would actually send
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### With a local model (Ollama)
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from delbina import ollama_summarizer, rolling_summary
|
|
59
|
+
|
|
60
|
+
strategy = rolling_summary(keep=4, summarize=ollama_summarizer("qwen2.5:1.5b"))
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Requires a running [Ollama](https://ollama.com) server. No extra Python dependencies.
|
|
64
|
+
|
|
65
|
+
## CLI
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
delbina bench chat.json # compare strategies
|
|
69
|
+
delbina bench chat.json --ollama qwen2.5:1.5b # use a local model for summaries
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
`chat.json` format: `{"turns": ["...", "..."]}`
|
|
73
|
+
|
|
74
|
+
## Strategies
|
|
75
|
+
|
|
76
|
+
| Strategy | What is sent each turn |
|
|
77
|
+
|---|---|
|
|
78
|
+
| `full` | the whole history (baseline) |
|
|
79
|
+
| `last_n(n)` | the last n turns |
|
|
80
|
+
| `head_tail(h, t)` | the first h turns (task setup) + the last t turns |
|
|
81
|
+
| `rolling_summary(keep, summarize)` | a summary of older turns + the last `keep` turns |
|
|
82
|
+
|
|
83
|
+
Note: `cost()` counts tokens sent to the main model. It does not yet count the tokens spent by the summarizer itself.
|
|
84
|
+
|
|
85
|
+
## Development
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
python -m venv .venv
|
|
89
|
+
pip install -e ".[dev]"
|
|
90
|
+
pytest -q
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## License
|
|
94
|
+
|
|
95
|
+
Apache-2.0
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/delbina/__init__.py
|
|
5
|
+
src/delbina/cli.py
|
|
6
|
+
src/delbina/compress.py
|
|
7
|
+
src/delbina/ollama.py
|
|
8
|
+
src/delbina/tokens.py
|
|
9
|
+
src/delbina.egg-info/PKG-INFO
|
|
10
|
+
src/delbina.egg-info/SOURCES.txt
|
|
11
|
+
src/delbina.egg-info/dependency_links.txt
|
|
12
|
+
src/delbina.egg-info/entry_points.txt
|
|
13
|
+
src/delbina.egg-info/requires.txt
|
|
14
|
+
src/delbina.egg-info/top_level.txt
|
|
15
|
+
tests/test_cli.py
|
|
16
|
+
tests/test_compress.py
|
|
17
|
+
tests/test_tokens.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
delbina
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
from delbina import ollama_summarizer
|
|
4
|
+
from delbina.cli import main
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def test_bench_runs(tmp_path, capsys):
|
|
8
|
+
f = tmp_path / "chat.json"
|
|
9
|
+
f.write_text(json.dumps({"turns": [f"turn {i} " + "word " * 10 for i in range(8)]}))
|
|
10
|
+
assert main(["bench", str(f)]) == 0
|
|
11
|
+
out = capsys.readouterr().out
|
|
12
|
+
assert "full" in out and "last_4" in out
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def test_ollama_summarizer_parses_response(monkeypatch):
|
|
16
|
+
class Resp:
|
|
17
|
+
def __enter__(self): return self
|
|
18
|
+
def __exit__(self, *a): pass
|
|
19
|
+
def read(self): return json.dumps({"response": " short summary "}).encode()
|
|
20
|
+
monkeypatch.setattr("urllib.request.urlopen", lambda req, timeout: Resp())
|
|
21
|
+
assert ollama_summarizer()(["a", "b"]) == "short summary"
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from delbina import cost, cumulative_cost, full, head_tail, last_n, rolling_summary
|
|
2
|
+
|
|
3
|
+
TURNS = [f"turn {i} " + "word " * 20 for i in range(10)]
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def test_full_matches_baseline():
|
|
7
|
+
assert cost(TURNS, full) == cumulative_cost(TURNS)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def test_last_n_keeps_tail():
|
|
11
|
+
assert last_n(3)(TURNS) == TURNS[-3:]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_head_tail_keeps_both_ends():
|
|
15
|
+
out = head_tail(1, 2)(TURNS)
|
|
16
|
+
assert out == [TURNS[0]] + TURNS[-2:]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_short_history_untouched():
|
|
20
|
+
assert rolling_summary(keep=5)(TURNS[:3]) == TURNS[:3]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_compression_saves_tokens():
|
|
24
|
+
for s in (last_n(3), head_tail(1, 2), rolling_summary(keep=2)):
|
|
25
|
+
assert cost(TURNS, s) < cost(TURNS, full)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from delbina import count, cumulative_cost
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def test_count_nonzero():
|
|
5
|
+
assert count("hello world") > 0
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def test_cumulative_is_triangular():
|
|
9
|
+
turns = ["a b c", "d e f", "g h i"]
|
|
10
|
+
c = [count(t) for t in turns]
|
|
11
|
+
assert cumulative_cost(turns) == c[0] + (c[0] + c[1]) + (c[0] + c[1] + c[2])
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_empty():
|
|
15
|
+
assert cumulative_cost([]) == 0
|