trl-token-reduction 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.
Files changed (66) hide show
  1. trl_token_reduction-0.1.0/LICENSE +201 -0
  2. trl_token_reduction-0.1.0/NOTICE +4 -0
  3. trl_token_reduction-0.1.0/PKG-INFO +391 -0
  4. trl_token_reduction-0.1.0/README.md +319 -0
  5. trl_token_reduction-0.1.0/plugin/__init__.py +2 -0
  6. trl_token_reduction-0.1.0/plugin/claude-code/.mcp.json +16 -0
  7. trl_token_reduction-0.1.0/plugin/claude-code/SKILL.md +7 -0
  8. trl_token_reduction-0.1.0/plugin/cli.py +31 -0
  9. trl_token_reduction-0.1.0/plugin/codex/config.toml +15 -0
  10. trl_token_reduction-0.1.0/plugin/index_store.py +71 -0
  11. trl_token_reduction-0.1.0/plugin/mcp_server.py +143 -0
  12. trl_token_reduction-0.1.0/plugin/retrieval_policy.py +109 -0
  13. trl_token_reduction-0.1.0/proxy/__init__.py +5 -0
  14. trl_token_reduction-0.1.0/proxy/compress_endpoint.py +49 -0
  15. trl_token_reduction-0.1.0/proxy/server.py +179 -0
  16. trl_token_reduction-0.1.0/proxy/test_live.py +59 -0
  17. trl_token_reduction-0.1.0/proxy/transform.py +220 -0
  18. trl_token_reduction-0.1.0/pyproject.toml +61 -0
  19. trl_token_reduction-0.1.0/setup.cfg +4 -0
  20. trl_token_reduction-0.1.0/tests/test_ast_extract.py +199 -0
  21. trl_token_reduction-0.1.0/tests/test_bigcode_bench_offline.py +50 -0
  22. trl_token_reduction-0.1.0/tests/test_cache_stable_prefix.py +89 -0
  23. trl_token_reduction-0.1.0/tests/test_cascade.py +25 -0
  24. trl_token_reduction-0.1.0/tests/test_cascade_router.py +96 -0
  25. trl_token_reduction-0.1.0/tests/test_claude_cli_parse.py +81 -0
  26. trl_token_reduction-0.1.0/tests/test_compress_endpoint.py +44 -0
  27. trl_token_reduction-0.1.0/tests/test_compress_unit.py +250 -0
  28. trl_token_reduction-0.1.0/tests/test_engine_process.py +165 -0
  29. trl_token_reduction-0.1.0/tests/test_heavy_bench_offline.py +186 -0
  30. trl_token_reduction-0.1.0/tests/test_index_persistence.py +37 -0
  31. trl_token_reduction-0.1.0/tests/test_local_model.py +179 -0
  32. trl_token_reduction-0.1.0/tests/test_nl_rerank_eval.py +48 -0
  33. trl_token_reduction-0.1.0/tests/test_ollama_smoke.py +34 -0
  34. trl_token_reduction-0.1.0/tests/test_pdf.py +23 -0
  35. trl_token_reduction-0.1.0/tests/test_pipeline.py +14 -0
  36. trl_token_reduction-0.1.0/tests/test_plugin_package.py +63 -0
  37. trl_token_reduction-0.1.0/tests/test_providers_shape.py +64 -0
  38. trl_token_reduction-0.1.0/tests/test_proxy_server.py +76 -0
  39. trl_token_reduction-0.1.0/tests/test_proxy_transform.py +105 -0
  40. trl_token_reduction-0.1.0/tests/test_resolve_repo.py +60 -0
  41. trl_token_reduction-0.1.0/tests/test_retrieval.py +94 -0
  42. trl_token_reduction-0.1.0/tests/test_retrieve_unit.py +305 -0
  43. trl_token_reduction-0.1.0/tests/test_savings_log.py +26 -0
  44. trl_token_reduction-0.1.0/tests/test_text_retrieval.py +35 -0
  45. trl_token_reduction-0.1.0/tests/test_util.py +114 -0
  46. trl_token_reduction-0.1.0/trl/__init__.py +12 -0
  47. trl_token_reduction-0.1.0/trl/cache.py +37 -0
  48. trl_token_reduction-0.1.0/trl/cascade.py +39 -0
  49. trl_token_reduction-0.1.0/trl/compress.py +144 -0
  50. trl_token_reduction-0.1.0/trl/engine.py +82 -0
  51. trl_token_reduction-0.1.0/trl/local_model.py +168 -0
  52. trl_token_reduction-0.1.0/trl/message.py +33 -0
  53. trl_token_reduction-0.1.0/trl/retrieval/__init__.py +10 -0
  54. trl_token_reduction-0.1.0/trl/retrieval/ast_index.py +353 -0
  55. trl_token_reduction-0.1.0/trl/retrieval/embed.py +22 -0
  56. trl_token_reduction-0.1.0/trl/retrieval/llm_rerank.py +39 -0
  57. trl_token_reduction-0.1.0/trl/retrieval/pdf.py +33 -0
  58. trl_token_reduction-0.1.0/trl/retrieval/retrieve.py +313 -0
  59. trl_token_reduction-0.1.0/trl/retrieval/text_index.py +113 -0
  60. trl_token_reduction-0.1.0/trl/util.py +87 -0
  61. trl_token_reduction-0.1.0/trl_token_reduction.egg-info/PKG-INFO +391 -0
  62. trl_token_reduction-0.1.0/trl_token_reduction.egg-info/SOURCES.txt +64 -0
  63. trl_token_reduction-0.1.0/trl_token_reduction.egg-info/dependency_links.txt +1 -0
  64. trl_token_reduction-0.1.0/trl_token_reduction.egg-info/entry_points.txt +4 -0
  65. trl_token_reduction-0.1.0/trl_token_reduction.egg-info/requires.txt +60 -0
  66. trl_token_reduction-0.1.0/trl_token_reduction.egg-info/top_level.txt +3 -0
@@ -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 Derivative
95
+ 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 2026 Aryan Gonsalves
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.
@@ -0,0 +1,4 @@
1
+ Token Reduction Layer for LLM Apps & Agents
2
+ Copyright 2026 Aryan Gonsalves
3
+
4
+ Licensed under the Apache License, Version 2.0 (see LICENSE).
@@ -0,0 +1,391 @@
1
+ Metadata-Version: 2.4
2
+ Name: trl-token-reduction
3
+ Version: 0.1.0
4
+ Summary: Vendor-neutral token-reduction layer for LLM apps and agents: caching, compression+fact-guard, AST/text retrieval, and cascade — with published quality-neutrality benchmarks.
5
+ Author: Aryan Gonsalves
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/AryanGonsalves/trl-token-reduction
8
+ Project-URL: Repository, https://github.com/AryanGonsalves/trl-token-reduction
9
+ Keywords: llm,tokens,cost,retrieval,compression,mcp,proxy,agents,claude,openai,codex
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Software Development :: Libraries
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ License-File: NOTICE
19
+ Provides-Extra: retrieval
20
+ Requires-Dist: tree_sitter>=0.21; extra == "retrieval"
21
+ Requires-Dist: tree_sitter_python>=0.21; extra == "retrieval"
22
+ Requires-Dist: tree_sitter_javascript>=0.21; extra == "retrieval"
23
+ Requires-Dist: tree_sitter_typescript>=0.21; extra == "retrieval"
24
+ Requires-Dist: tree_sitter_go>=0.21; extra == "retrieval"
25
+ Requires-Dist: tree_sitter_rust>=0.21; extra == "retrieval"
26
+ Requires-Dist: tree_sitter_java>=0.21; extra == "retrieval"
27
+ Requires-Dist: tree_sitter_c_sharp>=0.21; extra == "retrieval"
28
+ Requires-Dist: tree_sitter_c>=0.21; extra == "retrieval"
29
+ Requires-Dist: tree_sitter_cpp>=0.21; extra == "retrieval"
30
+ Requires-Dist: tree_sitter_ruby>=0.21; extra == "retrieval"
31
+ Requires-Dist: tree_sitter_php>=0.22; extra == "retrieval"
32
+ Requires-Dist: tree_sitter_kotlin>=1.0; extra == "retrieval"
33
+ Requires-Dist: pathspec>=0.11; extra == "retrieval"
34
+ Provides-Extra: proxy
35
+ Requires-Dist: pyyaml>=6.0; extra == "proxy"
36
+ Requires-Dist: tiktoken>=0.7.0; extra == "proxy"
37
+ Provides-Extra: models
38
+ Requires-Dist: anthropic>=0.40.0; extra == "models"
39
+ Requires-Dist: openai>=1.40.0; extra == "models"
40
+ Requires-Dist: tiktoken>=0.7.0; extra == "models"
41
+ Provides-Extra: mcp
42
+ Requires-Dist: mcp>=1.0; extra == "mcp"
43
+ Provides-Extra: embed
44
+ Requires-Dist: model2vec>=0.3; extra == "embed"
45
+ Provides-Extra: pdf
46
+ Requires-Dist: pypdf>=4.0; extra == "pdf"
47
+ Provides-Extra: all
48
+ Requires-Dist: tree_sitter>=0.21; extra == "all"
49
+ Requires-Dist: tree_sitter_python>=0.21; extra == "all"
50
+ Requires-Dist: tree_sitter_javascript>=0.21; extra == "all"
51
+ Requires-Dist: tree_sitter_typescript>=0.21; extra == "all"
52
+ Requires-Dist: tree_sitter_go>=0.21; extra == "all"
53
+ Requires-Dist: tree_sitter_rust>=0.21; extra == "all"
54
+ Requires-Dist: tree_sitter_java>=0.21; extra == "all"
55
+ Requires-Dist: tree_sitter_c_sharp>=0.21; extra == "all"
56
+ Requires-Dist: tree_sitter_c>=0.21; extra == "all"
57
+ Requires-Dist: tree_sitter_cpp>=0.21; extra == "all"
58
+ Requires-Dist: tree_sitter_ruby>=0.21; extra == "all"
59
+ Requires-Dist: tree_sitter_php>=0.22; extra == "all"
60
+ Requires-Dist: tree_sitter_kotlin>=1.0; extra == "all"
61
+ Requires-Dist: pathspec>=0.11; extra == "all"
62
+ Requires-Dist: pyyaml>=6.0; extra == "all"
63
+ Requires-Dist: tiktoken>=0.7.0; extra == "all"
64
+ Requires-Dist: anthropic>=0.40.0; extra == "all"
65
+ Requires-Dist: openai>=1.40.0; extra == "all"
66
+ Requires-Dist: mcp>=1.0; extra == "all"
67
+ Requires-Dist: model2vec>=0.3; extra == "all"
68
+ Requires-Dist: pypdf>=4.0; extra == "all"
69
+ Provides-Extra: dev
70
+ Requires-Dist: pytest>=7.0; extra == "dev"
71
+ Dynamic: license-file
72
+
73
+ # Token-Reduction Layer for LLM Apps & Agents
74
+
75
+ A vendor-neutral efficiency layer that sits in front of an expensive API model
76
+ (Claude / GPT) and cuts token spend **several-fold with a published,
77
+ quality-neutral benchmark** — not a hand-wavy claim. Four composable levers, each
78
+ measured against the rule: **remove what the model doesn't need; never what it does.**
79
+
80
+ > Status: research build. Every lever below is implemented, benchmarked, and
81
+ > unit-tested offline. Numbers are from the included benchmarks (see *Reproduce*).
82
+ > The engine is real; some big-model arms use mocks/oracles where noted — the
83
+ > *structure* and the *quality-neutrality tests* are the contribution.
84
+
85
+ ## Why this exists
86
+
87
+ Agents are pathologically wasteful: they resend the full system prompt + tool
88
+ schemas + entire history every step, dump huge raw tool outputs, and route every
89
+ step — routine or hard — to the frontier model. The savings come from removing
90
+ that redundancy, irrelevance, and grunt work, **measured** so you know quality
91
+ didn't move.
92
+
93
+ ## The four levers (all built, all measured)
94
+
95
+ | Lever | What it does | Result (benchmark) | Quality |
96
+ |-------|--------------|--------------------|---------|
97
+ | **Caching** | bill the stable prefix once at the cache rate, not full freight each step | neutral vs a *cache-enabled* baseline (the honest baseline) | — |
98
+ | **Compression + guard** | a local model summarizes/dedupes the growing tail; a deterministic guard re-injects any number it drops | ~37% fewer tail tokens | **100%** (guard makes it exact-safe) |
99
+ | **Retrieval** | replace whole-file code dumps with only the relevant AST slices (tree-sitter, local, zero API tokens) | **5.9× / 83%** fewer context tokens on code-QA | **100%**, verbatim slices |
100
+ | **Cascade** | answer verifiable/easy steps on the cheap local pipeline; escalate only hard steps to the big model | **75% fewer big-model calls** | **100%**, 0 false-accepts |
101
+
102
+ **Compound (all four, one 20-turn code-agent session):**
103
+ `18.1× cheaper · 94.5% less $ · 80% fewer big-model calls · quality 100% = naive.`
104
+ The levers *multiply*, not just add.
105
+
106
+ Honest caveat, stated up front: the compound number is a *favorable* synthetic
107
+ workload (cascade handles the verifiable majority). Real agent mixes vary — our
108
+ long-standing story is **3–10× on favorable workloads, modest on pure novel
109
+ reasoning.** The point of the 18× demo is that the levers stack multiplicatively,
110
+ not the exact figure.
111
+
112
+ > **Read the retrieval numbers carefully (updated after a paired billed-token test).** The ~93% / ~99%
113
+ > figures below measure *content reduction* — how much smaller a returned slice is than reading the
114
+ > whole file(s) it came from. That is **not** billed-token savings in an agent loop. In a paired test
115
+ > on a real repo (provider-billed input tokens summed over every turn, answers graded, vs a plain
116
+ > grep+read agent), retrieval was **quality-neutral** and cheaper *per retrieval*, but a current
117
+ > **over-retrieval failure mode** can make the *total* net-neutral-to-worse (two runs swung from ~15%
118
+ > cheaper to ~70% costlier). So read ~93% / ~99% as "vs reading whole files," not "vs a competent
119
+ > shell agent." The paired harness, the numbers, and the honest breakdown are in the Hoard case study
120
+ > below.
121
+
122
+ ## Validated on real APIs (billed tokens, not estimates)
123
+
124
+ The benchmarks above run offline. But the levers were also proven **end-to-end
125
+ against live models**, and every number here is the **provider's own reported
126
+ billed token count** (OpenAI `usage.prompt_tokens`; Anthropic `usage.input_tokens`
127
+ including cache) — not our estimate, not a mock.
128
+
129
+ **Flagship models, heavy tasks (the headline result).** Run on the two most advanced
130
+ models available, over heavy tasks built from *real* content (the project's own docs
131
+ and code, ~6–10k tokens each), baseline vs token-reduced:
132
+
133
+ | Flagship model | Input tokens | Quality |
134
+ |----------------|--------------|---------|
135
+ | **OpenAI GPT-5.5** | **16,875 → 2,232 (86.8% fewer)** | **3/3 → 3/3, non-inferior PASS** |
136
+ | **Anthropic Claude Opus 4.8** | **26,573 → 3,343 (87.4% fewer)** | **3/3 → 3/3, non-inferior PASS** |
137
+
138
+ ~87% of input tokens removed on the current frontier, with quality fully preserved on
139
+ both. (Reproduce: `validate/heavy_bench.py`, hard-capped at $1.80/provider.) The three
140
+ tasks are a long-document QA, a bloated agent turn, and a code-context QA.
141
+
142
+ **Cross-file, multi-file codebase (the "does it hold on a bigger codebase?" test).**
143
+ Three questions that each require tracing across 2–3 files, answered from the *whole*
144
+ codebase (~30k tokens) vs the retrieval-reduced context, same non-inferiority test:
145
+
146
+ | Cross-file codebase QA (~30k-token repo) | Input tokens | Quality |
147
+ |------------------------------------------|--------------|---------|
148
+ | **OpenAI GPT-5.5** | **89,845 → 3,891 (95.7% fewer)** | **3/3 → 3/3, non-inferior PASS** |
149
+ | **Anthropic Claude Opus 4.8** | **141,628 → 6,102 (95.7% fewer)** | **3/3 → 3/3, non-inferior PASS** |
150
+
151
+ On a real multi-file codebase, the retrieval-reduced context answered the cross-file
152
+ tracing tasks as well as the full context. Honest scope: this is a ~30k-token repo —
153
+ *medium* scale, not a 500k-line monorepo, and n=3 tasks. (Reproduce:
154
+ `validate/bigcode_bench.py`, hard-capped at $1.80/provider.)
155
+
156
+ **Independent out-of-distribution check.** Pointed the retriever at a *separate
157
+ ~52k-token production Python codebase it had never seen* (35 files, 359 symbols) and ran
158
+ 8 natural-language audit queries. Retrieval returned ~1k tokens of slices per query vs the
159
+ 52k whole-dump — **~98% fewer** — with the answer-bearing module/symbol as the top hit on
160
+ descriptively-named queries. (Informal relevance check, not a labeled precision eval; point
161
+ it at your own repo: `python -m validate.measure_repo_reduction --repo <path>`.)
162
+
163
+ **Real-world longitudinal usage — an entire game built with the plugin (live, logged).**
164
+ Beyond the offline/API benchmarks, the plugin was dogfooded across a *full project*: a Roblox
165
+ game ("Hoard") built with Claude Code across the full project build (many feature, integration, and hardening
166
+ sessions), from an empty scaffold to a 52-file / ~164k-token codebase. Two independent things were
167
+ measured at every phase — the **direct** retrieval reduction on the repo, and the plugin's **own
168
+ live savings log** (`TRL_SAVINGS_LOG`): exactly what the agent called and what each returned slice
169
+ replaced.
170
+
171
+ | Hoard (Luau/Roblox), tracked as the repo grew | Result |
172
+ |---|---|
173
+ | **Direct** reduction vs whole-repo dump | **52% -> 99%** as the repo scaled ~2.2k -> ~164k tokens (10/10 relevant top-hits on descriptive queries) |
174
+ | **Live** agent usage (the plugin's savings log) | **188 real calls, ~2.12M tokens saved, 92.9% fewer** vs the file(s) those slices would otherwise have been read from |
175
+
176
+ The live curve climbed with the codebase (85% -> 93% cumulative across phases) toward the ~98%
177
+ per-call direct ceiling — i.e. the bigger the project got, the more a ~few-hundred-token slice beat
178
+ reading whole files. Honest caveats, stated plainly: (1) the live "counterfactual" is the whole
179
+ *file(s)* each slice came from — what the agent would otherwise read — not the whole repo, so it's a
180
+ realistic per-call baseline, not a favorable one; (2) savings only accrue on **adoption** —
181
+ feature-*creation* phases call retrieval little, integration/refactor/hardening phases call it heavily
182
+ (where it pays most), so the cumulative number reflects real mixed usage; (3) scope is one project,
183
+ one developer, one language, and two early phases' calls were **lost to a logging bug before it was
184
+ fixed** (disclosed and excluded) — so the 188 calls are the reliably-logged subset and the true total
185
+ was higher. Reproduce on your own project: `python -m validate.measure_repo_reduction --repo <path>`
186
+ (direct) and set `TRL_SAVINGS_LOG`, then `python -m validate.savings_report <log>` (live). The exact game repo (WIP, published as a verifiable benchmark) is at **github.com/AryanGonsalves/hoard**.
187
+
188
+ **Paired billed-token test (added after fair criticism).** The figures above are *content* reduction
189
+ (slice vs whole-file), not billed tokens, and "whole file" is a generous baseline. So we ran the
190
+ harder test: the same tasks through a real agent loop twice — once with the `retrieve_code` /
191
+ `explain_symbol` MCP, once with a plain grep+read agent (`code_search` + `read_file`) — summing
192
+ **provider-billed input tokens over every turn** (tool schemas + growing history + results) on
193
+ `claude-sonnet-5`, with both answers graded 0–3 against the code. Honestly:
194
+
195
+ - **Quality: neutral** (grader ~1.5/1.5, tied).
196
+ - **Cheaper per retrieval** than grep+read on well-behaved tasks (~2–6×, since one retrieve replaces
197
+ several search-then-read round-trips).
198
+ - **But an over-retrieval failure mode**: on ~1/3 of tasks the agent looped to 25+ calls and the
199
+ accumulated slice history ballooned to 280–380k tokens, flipping the total. Across two runs the
200
+ billed total swung from ~15% cheaper to ~70% costlier vs the shell agent.
201
+
202
+ So the honest scope: retrieval clearly wins **vs whole-file reads** (a common default) and is
203
+ quality-neutral, but it is **not** a blanket "90%+ billed savings" vs a disciplined shell agent, and
204
+ the over-retrieval blowup is a real defect being fixed (cap calls / leaner slices / stop-and-answer).
205
+ Reproduce: `python -m validate.paired_billed_bench --repo <path> --model claude-sonnet-5`.
206
+
207
+ | Earlier single-lever / mid-tier runs | Reduction | Quality / correctness |
208
+ |----------------|-----------|-----------------------|
209
+ | Realistic verifier suite — **OpenAI**, safe mode | **2.59× cheaper**, 43.1% fewer input tokens, 62.7% fewer sub-units | 100% → 100%, non-inferiority **PASS** |
210
+ | Live proxy, one bloated turn — **OpenAI gpt-4o-mini** | **1,672 → 730** billed input tokens (**56.3% fewer**) | output correct, fact-guard held |
211
+ | Compression lever — **OpenAI gpt-4o-mini** | **966 → 305** (**68% fewer**) | correct |
212
+ | Document retrieval — **OpenAI gpt-4o-mini** | **1,374 → 318** (**77% fewer**) | correct |
213
+ | Cascade — **OpenAI gpt-4o-mini** | **89%** of steps answered locally ($0 to the API) | **100%** accuracy, 0 false-accepts |
214
+ | Live proxy, compression + cache — **Anthropic claude-haiku-4.5** | **1,198 → 477** billed input tokens (**60% fewer**) | correct |
215
+
216
+ Honest caveats, stated plainly: the suites are small, the multi-lever suite is a
217
+ *favorable* workload, it's one model per provider, and the live-proxy rows each
218
+ isolate a single lever. These are directional — but they are **real billed tokens
219
+ on real models through the actual proxy**, which is the bar that matters. Reproduce
220
+ them with your own key via `RUN.md` (`validate/live_openai.py`, `validate/live_anthropic.py`).
221
+
222
+ ## What we measured and learned (the honest findings)
223
+
224
+ - A **cache-enabled baseline** neutralizes the caching lever — the real
225
+ differential comes from the tail (compression + retrieval) and from cascade.
226
+ - **A real 3B local model is a lossy compressor**: llama-3.2-3b dropped a
227
+ load-bearing fact ~1 in 3 times on a hard workload. The **fact-preserving
228
+ guard** (re-inject any dropped number, deterministically) restores quality to
229
+ 100% while keeping most savings. Compression is only shippable *with* the guard.
230
+ - **Text & PDFs get the same treatment**: a separate chunk-based retriever
231
+ slices prose/PDF documents to the passages that matter (numbers preserved for
232
+ disambiguation), so non-code requests cost fewer tokens too — without touching
233
+ the code path.
234
+ - **Semantic ranking, tested honestly**: on deliberately vague queries, static
235
+ embeddings gave *no* lift over keyword (dropped); an LLM-reranker is a small,
236
+ real, regression-free gain but costs one cheap model call, so it ships opt-in.
237
+ - **For code, retrieval beats compression on both axes** — bigger token cut *and*
238
+ quality-safe by construction (exact slices can't paraphrase a fact away).
239
+ - **Subscription limits (Claude Pro/Max) are server-side** — you can't turn a
240
+ subscription into cheap bulk API calls; the OAuth token authenticates but is
241
+ hard rate-limited. The clean, attackable target is metered API $, plus
242
+ *local-side* reduction inside coding-agent clients.
243
+
244
+ ## Architecture
245
+
246
+ ```
247
+ CODEBASE-AWARE surface (library / MCP plugin / agent integration — can see your repo):
248
+ request ──► retrieve (AST slices, local) # lever 3: don't stuff whole files
249
+ ──► cascade (easy → local, $0) # lever 4: needs a local model
250
+ ──► Engine.process:
251
+ ├─ cache-mark stable prefix # lever 1
252
+ └─ compress tail + fact guard # lever 2
253
+ ──► big model (only when needed)
254
+
255
+ BLIND proxy (base_url swap — CANNOT see your repo):
256
+ request ──► Engine.process: cache-mark prefix + compress tail + fact guard # levers 1 & 2
257
+ ──► retrieve ONLY over context you pass in a `documents` field # lever 3, opt-in
258
+ ──► big model
259
+ (cascade and codebase-wide retrieval are NOT available on the blind proxy)
260
+ ```
261
+
262
+ ### Which lever lives on which surface
263
+
264
+ The headline retrieval numbers (95.7% cross-file, and the ~87% frontier runs) come
265
+ from the RETRIEVAL-heavy code-agent regime, which needs a surface that can **index
266
+ your codebase**. The blind proxy can't see your repo, so on the proxy only caching +
267
+ compression fire automatically. **Never read the 87%/95.7% as a blind-proxy number.**
268
+
269
+ | Surface | caching (1) | compression + guard (2) | retrieval (3) | cascade (4) |
270
+ |---|---|---|---|---|
271
+ | **Blind proxy** (base_url swap) | ✓ auto | ✓ auto | only over a `documents` field you pass | ✗ |
272
+ | **Library / Engine** (in your agent) | ✓ | ✓ | ✓ indexes your repo | ✓ if local model |
273
+ | **MCP plugin** (Claude Code / Codex) | ✓ | ✓ | ✓ | ✓ if local model |
274
+ | **Browser extension** (`/compress`) | — | ✓ | ✓ (text) | ✗ |
275
+
276
+ The full-stack ~99% offline reduction over this repo (`validate/integrated_loop.py`)
277
+ is a *codebase-aware* run — retrieval doing most of the work, compression + caching
278
+ stacking on top. The blind proxy delivers the compression + caching portion only
279
+ (the single-lever live-proxy rows above: ~56–68% on a bloated turn).
280
+
281
+ - `trl/` — the shared engine (caching, compression+guard, cascade router) and
282
+ `trl/retrieval/` (tree-sitter extractor + retriever, **13 languages / 20 file
283
+ types**: Python, JS/JSX, TS/TSX, Go, Rust, Java, C#, C, C++, Ruby, PHP, Kotlin, Luau/Roblox),
284
+ plus a general **text + PDF** retriever (`text_index.py`, `pdf.py`) so non-code
285
+ documents get the same slice-don't-dump treatment.
286
+ - `bench/` — the harness: baseline (cache-enabled) vs treatment, real token/$
287
+ accounting, **non-inferiority** quality gates, and one benchmark per lever plus
288
+ the compound `pipeline_bench.py`.
289
+ - `tests/` — unit tests for every lever and provider parser.
290
+
291
+ ## Install
292
+
293
+ ```bash
294
+ pip install trl-token-reduction # core (stdlib only)
295
+ pip install "trl-token-reduction[all]" # + retrieval grammars, proxy, model SDKs, MCP, PDF
296
+ ```
297
+ Or from source: `git clone … && pip install -e ".[all]"`. Installing exposes three
298
+ commands — `trl-proxy`, `trl-retrieve`, `trl-cli` — used below. Extras are modular:
299
+ `[retrieval]`, `[proxy]`, `[models]`, `[mcp]`, `[embed]`, `[pdf]`.
300
+
301
+ **Who benefits (be honest):** anyone paying **metered API** per token (pay-as-you-go),
302
+ and anyone on a **token-metered subscription** — Claude Code (a flat monthly fee, but
303
+ usage is *metered in tokens* against your weekly caps) and Codex (which OpenAI moved to
304
+ token-based pricing in Apr 2026). On a subscription this doesn't cut a bill — it makes
305
+ you burn your quota slower, so you hit the weekly/5-hour caps later (more work per plan).
306
+ It does **not** help the ChatGPT/Claude *chat websites* (closed endpoints; ChatGPT's cap
307
+ is per-message, not per-token).
308
+
309
+ ## How you use it
310
+
311
+ Four ways to put it in front of your model — pick by how much you want to change.
312
+
313
+ ### 1. Drop-in proxy (any app, zero code changes)
314
+ The proxy speaks both the OpenAI **and** Anthropic wire formats. Point your
315
+ client's `base_url` at it; keep your own key (the proxy never stores it). Every
316
+ request gets **caching + compression (+ fact guard)** applied on the way through,
317
+ and comes back with an `X-TRL-Tokens-Saved` header so you can see the cut per call.
318
+ (The blind proxy can't see your codebase, so the retrieval and cascade levers live
319
+ on the codebase-aware surfaces below — see the surface/lever table above.)
320
+
321
+ ```bash
322
+ trl-proxy # listens on :8899, forwards upstream
323
+ # (or: python -m proxy.server)
324
+ ```
325
+ ```python
326
+ # OpenAI SDK — the ONLY change is base_url
327
+ client = OpenAI(base_url="http://localhost:8899/v1", api_key=YOUR_KEY)
328
+ # Anthropic SDK works the same via /v1/messages
329
+ ```
330
+ Want a document shrunk before it hits the model? Add a non-standard
331
+ `documents: [...]` field to the request — the proxy retrieves only the relevant
332
+ passages and injects them, instead of you pasting the whole file.
333
+
334
+ ### 2. Coding-agent plugin (Claude Code, Codex, or any MCP client)
335
+ Installs an MCP server `trl-retrieve` exposing `retrieve_code(query)` and
336
+ `explain_symbol(name)`. Your agent asks for *code that answers a question* and
337
+ gets AST slices (file:line + source) instead of stuffing whole files. Drop
338
+ `plugin/claude-code/.mcp.json` into a repo and point `TRL_REPO` at it. **Codex**
339
+ uses the same STDIO server — drop the `[mcp_servers.trl-retrieve]` block from
340
+ `plugin/codex/config.toml` into `~/.codex/config.toml`. See `plugin/INSTALL.md`.
341
+ No agent? Same thing from the shell:
342
+
343
+ ```bash
344
+ trl-cli "how does auth refresh work?" --repo /path/to/repo
345
+ # (or: python -m plugin.cli ...)
346
+ ```
347
+
348
+ ### 3. Library (embed the engine directly)
349
+ Call the pieces from your own code when you control the request path:
350
+
351
+ ```python
352
+ from trl import Engine, Message, load_config
353
+
354
+ engine = Engine(load_config("config.yaml"))
355
+ result = engine.process([
356
+ Message(role="system", content=BIG_SYSTEM_PROMPT),
357
+ Message(role="user", content="your request"),
358
+ ])
359
+ # result.messages -> cache-marked prefix + compressed tail, ready to send upstream
360
+ # result.cache_prefix_tokens -> stable-prefix tokens billed at the cache rate
361
+ # result.meta -> which levers fired
362
+ ```
363
+
364
+ ## Claude Code plugin (retrieval tier)
365
+
366
+ The repo doubles as a Claude Code plugin **and** its own marketplace — no store, no
367
+ review, just files. Add the marketplace (`AryanGonsalves/trl-token-reduction`) and
368
+ install the `trl` plugin. It ships:
369
+
370
+ - the `trl-retrieve` **MCP server** (`retrieve_code`, `explain_symbol`) — the agent
371
+ pulls exact AST slices instead of reading whole files;
372
+ - a **skill** that tells the agent to actually use those tools;
373
+ - `/trl-index` (build/refresh the index) and `/trl-status` (show savings).
374
+
375
+ It auto-targets YOUR project at runtime (`$TRL_REPO` / `$CLAUDE_PROJECT_DIR` / nearest `.git` / cwd) and caches the index at `<project>/.trl/index.json`; if it can't resolve the project it asks you to run `/trl-index` or set `TRL_REPO`.
376
+
377
+ **Honest scope:** the plugin delivers the **retrieval tier** — cutting context tokens by
378
+ fetching slices, not whole files. It does **not** deliver the full proxy-path headline
379
+ (~87%); prefix caching + tail compression require running the local proxy and pointing
380
+ your agent's base URL at it (two-tier note above).
381
+
382
+ ### Optional hosted rerank (precision, off by default)
383
+
384
+ For vague natural-language questions where keyword retrieval misses the right symbol,
385
+ `retrieve(rerank="hosted")` asks a hosted model (your own `ANTHROPIC_API_KEY`,
386
+ `claude-haiku-4-5-20251001` by default) to reorder the shortlist. Validated on a
387
+ 15-query NL set (2 runs): free `doc_boost` **6/15** → Haiku **11/15**, Sonnet
388
+ **8.5/15** (oracle ceiling **12/15**), with the 6/6 code loop non-inferior. It is a
389
+ **precision option, not a token saver** — ~1¢/query via Haiku on your own key — and is
390
+ **off by default**. The remaining 11→12 gap is retrieval-recall/shortlist coverage, not
391
+ the reranker.