tokenbiryani 0.2.0__py3-none-any.whl
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.
- tokenbiryani/__init__.py +3 -0
- tokenbiryani/api/__init__.py +0 -0
- tokenbiryani/api/app.py +583 -0
- tokenbiryani/api/asgi.py +32 -0
- tokenbiryani/cli.py +1045 -0
- tokenbiryani/config.py +532 -0
- tokenbiryani/core/__init__.py +0 -0
- tokenbiryani/core/account.py +258 -0
- tokenbiryani/core/batch.py +135 -0
- tokenbiryani/core/breaker.py +53 -0
- tokenbiryani/core/cacheadvice.py +239 -0
- tokenbiryani/core/diagnostics.py +131 -0
- tokenbiryani/core/estimator.py +180 -0
- tokenbiryani/core/gateway.py +2395 -0
- tokenbiryani/core/handoff.py +87 -0
- tokenbiryani/core/keys.py +199 -0
- tokenbiryani/core/limits.py +440 -0
- tokenbiryani/core/oauth.py +222 -0
- tokenbiryani/core/pacing.py +320 -0
- tokenbiryani/core/queue.py +132 -0
- tokenbiryani/core/router.py +323 -0
- tokenbiryani/core/secrets.py +114 -0
- tokenbiryani/core/session.py +117 -0
- tokenbiryani/dashboard/__init__.py +56 -0
- tokenbiryani/dashboard/console.css +610 -0
- tokenbiryani/dashboard/console.html +3250 -0
- tokenbiryani/observability/__init__.py +0 -0
- tokenbiryani/observability/events.py +171 -0
- tokenbiryani/observability/usage.py +226 -0
- tokenbiryani/prices.yaml +77 -0
- tokenbiryani/providers/__init__.py +0 -0
- tokenbiryani/providers/anthropic_api.py +118 -0
- tokenbiryani/providers/base.py +173 -0
- tokenbiryani/providers/bedrock.py +182 -0
- tokenbiryani/providers/oauth.py +165 -0
- tokenbiryani/providers/oauth_credentials.py +293 -0
- tokenbiryani/providers/translate.py +35 -0
- tokenbiryani/providers/vertex.py +144 -0
- tokenbiryani/proxy/__init__.py +0 -0
- tokenbiryani/proxy/errors.py +169 -0
- tokenbiryani/proxy/sse.py +98 -0
- tokenbiryani/store/__init__.py +0 -0
- tokenbiryani/store/base.py +150 -0
- tokenbiryani/store/memory.py +149 -0
- tokenbiryani/store/redis_store.py +222 -0
- tokenbiryani/store/sqlite.py +336 -0
- tokenbiryani-0.2.0.dist-info/METADATA +697 -0
- tokenbiryani-0.2.0.dist-info/RECORD +51 -0
- tokenbiryani-0.2.0.dist-info/WHEEL +4 -0
- tokenbiryani-0.2.0.dist-info/entry_points.txt +2 -0
- tokenbiryani-0.2.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,697 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: tokenbiryani
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: A pooling gateway for Claude accounts: routes on live rate-limit headers, keeps prompt caches warm, fails over without dropping a stream.
|
|
5
|
+
Project-URL: Homepage, https://github.com/Abhi-shekes/tokenbiryani
|
|
6
|
+
Project-URL: Documentation, https://abhi-shekes.github.io/tokenbiryani/
|
|
7
|
+
Project-URL: Repository, https://github.com/Abhi-shekes/tokenbiryani
|
|
8
|
+
Project-URL: Issues, https://github.com/Abhi-shekes/tokenbiryani/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/Abhi-shekes/tokenbiryani/blob/main/CHANGELOG.md
|
|
10
|
+
License:
|
|
11
|
+
Apache License
|
|
12
|
+
Version 2.0, January 2004
|
|
13
|
+
http://www.apache.org/licenses/
|
|
14
|
+
|
|
15
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
16
|
+
|
|
17
|
+
1. Definitions.
|
|
18
|
+
|
|
19
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
20
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
21
|
+
|
|
22
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
23
|
+
the copyright owner that is granting the License.
|
|
24
|
+
|
|
25
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
26
|
+
other entities that control, are controlled by, or are under common
|
|
27
|
+
control with that entity. For the purposes of this definition,
|
|
28
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
29
|
+
direction or management of such entity, whether by contract or
|
|
30
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
31
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
32
|
+
|
|
33
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
34
|
+
exercising permissions granted by this License.
|
|
35
|
+
|
|
36
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
37
|
+
including but not limited to software source code, documentation
|
|
38
|
+
source, and configuration files.
|
|
39
|
+
|
|
40
|
+
"Object" form shall mean any form resulting from mechanical
|
|
41
|
+
transformation or translation of a Source form, including but
|
|
42
|
+
not limited to compiled object code, generated documentation,
|
|
43
|
+
and conversions to other media types.
|
|
44
|
+
|
|
45
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
46
|
+
Object form, made available under the License, as indicated by a
|
|
47
|
+
copyright notice that is included in or attached to the work
|
|
48
|
+
(an example is provided in the Appendix below).
|
|
49
|
+
|
|
50
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
51
|
+
form, that is based on (or derived from) the Work and for which the
|
|
52
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
53
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
54
|
+
of this License, Derivative Works shall not include works that remain
|
|
55
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
56
|
+
the Work and Derivative Works thereof.
|
|
57
|
+
|
|
58
|
+
"Contribution" shall mean any work of authorship, including
|
|
59
|
+
the original version of the Work and any modifications or additions
|
|
60
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
61
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
62
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
63
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
64
|
+
means any form of electronic, verbal, or written communication sent
|
|
65
|
+
to the Licensor or its representatives, including but not limited to
|
|
66
|
+
communication on electronic mailing lists, source code control systems,
|
|
67
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
68
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
69
|
+
excluding communication that is conspicuously marked or otherwise
|
|
70
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
71
|
+
|
|
72
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
73
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
74
|
+
subsequently incorporated within the Work.
|
|
75
|
+
|
|
76
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
77
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
78
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
79
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
80
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
81
|
+
Work and such Derivative Works in Source or Object form.
|
|
82
|
+
|
|
83
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
84
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
85
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
86
|
+
(except as stated in this section) patent license to make, have made,
|
|
87
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
88
|
+
where such license applies only to those patent claims licensable
|
|
89
|
+
by such Contributor that are necessarily infringed by their
|
|
90
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
91
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
92
|
+
institute patent litigation against any entity (including a
|
|
93
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
94
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
95
|
+
or contributory patent infringement, then any patent licenses
|
|
96
|
+
granted to You under this License for that Work shall terminate
|
|
97
|
+
as of the date such litigation is filed.
|
|
98
|
+
|
|
99
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
100
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
101
|
+
modifications, and in Source or Object form, provided that You
|
|
102
|
+
meet the following conditions:
|
|
103
|
+
|
|
104
|
+
(a) You must give any other recipients of the Work or
|
|
105
|
+
Derivative Works a copy of this License; and
|
|
106
|
+
|
|
107
|
+
(b) You must cause any modified files to carry prominent notices
|
|
108
|
+
stating that You changed the files; and
|
|
109
|
+
|
|
110
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
111
|
+
that You distribute, all copyright, patent, trademark, and
|
|
112
|
+
attribution notices from the Source form of the Work,
|
|
113
|
+
excluding those notices that do not pertain to any part of
|
|
114
|
+
the Derivative Works; and
|
|
115
|
+
|
|
116
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
117
|
+
distribution, then any Derivative Works that You distribute must
|
|
118
|
+
include a readable copy of the attribution notices contained
|
|
119
|
+
within such NOTICE file, excluding those notices that do not
|
|
120
|
+
pertain to any part of the Derivative Works, in at least one
|
|
121
|
+
of the following places: within a NOTICE text file distributed
|
|
122
|
+
as part of the Derivative Works; within the Source form or
|
|
123
|
+
documentation, if provided along with the Derivative Works; or,
|
|
124
|
+
within a display generated by the Derivative Works, if and
|
|
125
|
+
wherever such third-party notices normally appear. The contents
|
|
126
|
+
of the NOTICE file are for informational purposes only and
|
|
127
|
+
do not modify the License. You may add Your own attribution
|
|
128
|
+
notices within Derivative Works that You distribute, alongside
|
|
129
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
130
|
+
that such additional attribution notices cannot be construed
|
|
131
|
+
as modifying the License.
|
|
132
|
+
|
|
133
|
+
You may add Your own copyright statement to Your modifications and
|
|
134
|
+
may provide additional or different license terms and conditions
|
|
135
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
136
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
137
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
138
|
+
the conditions stated in this License.
|
|
139
|
+
|
|
140
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
141
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
142
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
143
|
+
this License, without any additional terms or conditions.
|
|
144
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
145
|
+
the terms of any separate license agreement you may have executed
|
|
146
|
+
with Licensor regarding such Contributions.
|
|
147
|
+
|
|
148
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
149
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
150
|
+
except as required for reasonable and customary use in describing the
|
|
151
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
152
|
+
|
|
153
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
154
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
155
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
156
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
157
|
+
implied, including, without limitation, any warranties or conditions
|
|
158
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
159
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
160
|
+
appropriateness of using or redistributing the Work and assume any
|
|
161
|
+
risks associated with Your exercise of permissions under this License.
|
|
162
|
+
|
|
163
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
164
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
165
|
+
unless required by applicable law (such as deliberate and grossly
|
|
166
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
167
|
+
liable to You for damages, including any direct, indirect, special,
|
|
168
|
+
incidental, or consequential damages of any character arising as a
|
|
169
|
+
result of this License or out of the use or inability to use the
|
|
170
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
171
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
172
|
+
other commercial damages or losses), even if such Contributor
|
|
173
|
+
has been advised of the possibility of such damages.
|
|
174
|
+
|
|
175
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
176
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
177
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
178
|
+
or other liability obligations and/or rights consistent with this
|
|
179
|
+
License. However, in accepting such obligations, You may act only
|
|
180
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
181
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
182
|
+
defend, and hold each Contributor harmless for any liability
|
|
183
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
184
|
+
of your accepting any such warranty or additional liability.
|
|
185
|
+
|
|
186
|
+
END OF TERMS AND CONDITIONS
|
|
187
|
+
|
|
188
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
189
|
+
|
|
190
|
+
To apply the Apache License to your work, attach the following
|
|
191
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
192
|
+
replaced with your own identifying information. (Don't include
|
|
193
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
194
|
+
comment syntax for the file format. We also recommend that a
|
|
195
|
+
file or class name and description of purpose be included on the
|
|
196
|
+
same "printed page" as the copyright notice for easier
|
|
197
|
+
identification within third-party archives.
|
|
198
|
+
|
|
199
|
+
Copyright [yyyy] [name of copyright owner]
|
|
200
|
+
|
|
201
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
202
|
+
you may not use this file except in compliance with the License.
|
|
203
|
+
You may obtain a copy of the License at
|
|
204
|
+
|
|
205
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
206
|
+
|
|
207
|
+
Unless required by applicable law or agreed to in writing, software
|
|
208
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
209
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
210
|
+
See the License for the specific language governing permissions and
|
|
211
|
+
limitations under the License.
|
|
212
|
+
License-File: LICENSE
|
|
213
|
+
Keywords: anthropic,claude,claude-code,gateway,llm-gateway,load-balancing,prompt-caching,proxy,rate-limit
|
|
214
|
+
Classifier: Development Status :: 3 - Alpha
|
|
215
|
+
Classifier: Intended Audience :: Developers
|
|
216
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
217
|
+
Classifier: Programming Language :: Python :: 3
|
|
218
|
+
Classifier: Topic :: Internet :: Proxy Servers
|
|
219
|
+
Requires-Python: >=3.8
|
|
220
|
+
Requires-Dist: cryptography>=41.0
|
|
221
|
+
Requires-Dist: fastapi>=0.100
|
|
222
|
+
Requires-Dist: httpx>=0.24
|
|
223
|
+
Requires-Dist: pyyaml>=6.0
|
|
224
|
+
Requires-Dist: uvicorn>=0.23
|
|
225
|
+
Provides-Extra: all
|
|
226
|
+
Requires-Dist: botocore>=1.31; extra == 'all'
|
|
227
|
+
Requires-Dist: google-auth>=2.20; extra == 'all'
|
|
228
|
+
Requires-Dist: redis>=5.0; extra == 'all'
|
|
229
|
+
Provides-Extra: bedrock
|
|
230
|
+
Requires-Dist: botocore>=1.31; extra == 'bedrock'
|
|
231
|
+
Provides-Extra: dev
|
|
232
|
+
Requires-Dist: botocore>=1.31; extra == 'dev'
|
|
233
|
+
Requires-Dist: fakeredis>=2.20; extra == 'dev'
|
|
234
|
+
Requires-Dist: google-auth>=2.20; extra == 'dev'
|
|
235
|
+
Requires-Dist: mypy>=1.8; extra == 'dev'
|
|
236
|
+
Requires-Dist: playwright>=1.40; extra == 'dev'
|
|
237
|
+
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
|
|
238
|
+
Requires-Dist: pytest-cov>=4.1; extra == 'dev'
|
|
239
|
+
Requires-Dist: pytest>=7.4; extra == 'dev'
|
|
240
|
+
Requires-Dist: redis>=5.0; extra == 'dev'
|
|
241
|
+
Requires-Dist: ruff>=0.1; extra == 'dev'
|
|
242
|
+
Requires-Dist: types-pyyaml; extra == 'dev'
|
|
243
|
+
Requires-Dist: watchfiles>=0.21; extra == 'dev'
|
|
244
|
+
Provides-Extra: docs
|
|
245
|
+
Requires-Dist: mkdocs-material<10,>=9.5; extra == 'docs'
|
|
246
|
+
Provides-Extra: redis
|
|
247
|
+
Requires-Dist: redis>=5.0; extra == 'redis'
|
|
248
|
+
Provides-Extra: secrets
|
|
249
|
+
Provides-Extra: vertex
|
|
250
|
+
Requires-Dist: google-auth>=2.20; extra == 'vertex'
|
|
251
|
+
Description-Content-Type: text/markdown
|
|
252
|
+
|
|
253
|
+
# tokenbiryani
|
|
254
|
+
|
|
255
|
+
**A pooling gateway for Claude accounts.** One Anthropic-compatible endpoint in front of
|
|
256
|
+
every credential you own. It routes on live rate-limit headers, keeps a conversation on
|
|
257
|
+
the account holding its prompt cache, fails over without dropping a stream, and queues
|
|
258
|
+
honestly when the whole pool is dry.
|
|
259
|
+
|
|
260
|
+
```bash
|
|
261
|
+
pip install tokenbiryani # or: pipx install tokenbiryani
|
|
262
|
+
tokenbiryani init # writes tokenbiryani.yaml + a virtual key
|
|
263
|
+
tokenbiryani serve # starts with an empty pool
|
|
264
|
+
tokenbiryani console # opens the browser, already signed in
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+

|
|
270
|
+
|
|
271
|
+
Nothing needs exporting first. The console's wizard takes your first credential,
|
|
272
|
+
**verifies it** — the same rate-limit-header check `tokenbiryani doctor` performs — and
|
|
273
|
+
hands you the two lines that use it, with a working key already in them:
|
|
274
|
+
|
|
275
|
+
```bash
|
|
276
|
+
export ANTHROPIC_BASE_URL=http://localhost:8787
|
|
277
|
+
export ANTHROPIC_AUTH_TOKEN=bir_...
|
|
278
|
+
claude # Claude Code now runs through the pool
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
Prefer the terminal:
|
|
282
|
+
|
|
283
|
+
```bash
|
|
284
|
+
tokenbiryani accounts add work --api-key sk-ant-... # probed before it is stored
|
|
285
|
+
tokenbiryani accounts test # all of them, headers included
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
No client changes. The gateway speaks the Messages API verbatim — it swaps the auth
|
|
289
|
+
header and picks an upstream, and touches nothing else in the request.
|
|
290
|
+
|
|
291
|
+
> The one exception is the Bedrock and Vertex adapters. Those platforms address the
|
|
292
|
+
> model in the URL and stamp their own `anthropic_version`, so exactly two fields are
|
|
293
|
+
> translated, in one file (`providers/translate.py`), and nowhere else. Everything else
|
|
294
|
+
> the caller sent — including parameters this gateway has never heard of — travels
|
|
295
|
+
> through untouched.
|
|
296
|
+
|
|
297
|
+
---
|
|
298
|
+
|
|
299
|
+
## Why not just use a generic proxy
|
|
300
|
+
|
|
301
|
+
LiteLLM, Portkey and friends are breadth plays: many providers, lowest-common-denominator
|
|
302
|
+
routing. This is a depth play on one provider, and four things fall out of that.
|
|
303
|
+
|
|
304
|
+
| | tokenbiryani | Generic proxy |
|
|
305
|
+
|---|---|---|
|
|
306
|
+
| **Routing signal** | Live mirror of `anthropic-ratelimit-*` headers — real remaining request and token budget, per account, per reset window | Round-robin, or reactive backoff after a 429 lands |
|
|
307
|
+
| **Prompt cache** | Session affinity keeps a conversation on the account holding its cache; cache-break is a tracked metric | Round-robin shreds the cache silently |
|
|
308
|
+
| **Claude Code** | First-class client — long streaming turns, huge cached prefixes, tool loops | Treated as generic chat completion |
|
|
309
|
+
| **Failover** | Transparent up to the first streamed token, with an explicit documented boundary | Usually all-or-nothing |
|
|
310
|
+
|
|
311
|
+
### The benchmark
|
|
312
|
+
|
|
313
|
+
The same workload — 24 concurrent conversations, 8 turns each, across 4 accounts —
|
|
314
|
+
under each strategy, against a mock upstream that models Anthropic's per-credential
|
|
315
|
+
prompt cache. Prices are illustrative ratios, not a price list.
|
|
316
|
+
|
|
317
|
+
| Strategy | Cache hit | Cache breaks | Cost | vs sticky | Billed input |
|
|
318
|
+
|---|---|---|---|---|---|
|
|
319
|
+
| sticky_headroom | 79.6% | 0 | $0.4774 | — | 433,152 |
|
|
320
|
+
| round_robin | 47.8% | 144 | $0.9535 | 2.00x | 433,152 |
|
|
321
|
+
| least_loaded | 47.8% | 144 | $0.9535 | 2.00x | 433,152 |
|
|
322
|
+
| headroom | 47.8% | 144 | $0.9535 | 2.00x | 433,152 |
|
|
323
|
+
|
|
324
|
+
**Cache-blind routing costs 2.00x here.** And note that round-robin, least-loaded and
|
|
325
|
+
most-headroom all pay exactly the same penalty: any strategy that ignores affinity
|
|
326
|
+
visits every account once per conversation, so they all take the same number of cache
|
|
327
|
+
misses. The penalty is inherent to cache-blindness, not a quirk of round-robin.
|
|
328
|
+
|
|
329
|
+
Reproduce it with `python benchmarks/cache_affinity.py`. `tests/test_benchmark.py` fails if sticky ever stops winning.
|
|
330
|
+
|
|
331
|
+
### The prompt cache is the constraint
|
|
332
|
+
|
|
333
|
+
Anthropic's cache is scoped per credential. A Claude Code turn resends a large stable
|
|
334
|
+
prefix each time; warm, it bills at roughly a tenth of the input rate. **A gateway that
|
|
335
|
+
balances load without cache awareness can cost several times more than no gateway at
|
|
336
|
+
all.** So the default strategy is sticky, not balanced: affinity first, rebalance only
|
|
337
|
+
when the owner genuinely cannot serve. Every forced break is counted.
|
|
338
|
+
|
|
339
|
+
---
|
|
340
|
+
|
|
341
|
+
## How a request flows
|
|
342
|
+
|
|
343
|
+
```
|
|
344
|
+
auth → admit → route → lease → proxy → reconcile → recover
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
1. **Auth** — a virtual key (`bir_…`); real credentials never leave the process.
|
|
348
|
+
2. **Admit** — estimate cost; if no account could *ever* serve it, fail fast rather than
|
|
349
|
+
queue forever.
|
|
350
|
+
3. **Route** — filter to eligible accounts, score, pick.
|
|
351
|
+
4. **Lease** — atomically reserve the estimate so concurrent requests can't collectively
|
|
352
|
+
overshoot one account into a 429.
|
|
353
|
+
5. **Proxy** — stream bytes through untouched.
|
|
354
|
+
6. **Reconcile** — parse limit headers and usage; update the mirror, release the lease.
|
|
355
|
+
7. **Recover** — classify the failure, transition the account, decide whether to retry.
|
|
356
|
+
|
|
357
|
+
### Routing strategies
|
|
358
|
+
|
|
359
|
+
Set `routing.strategy`:
|
|
360
|
+
|
|
361
|
+
| Strategy | Behaviour |
|
|
362
|
+
|---|---|
|
|
363
|
+
| `sticky_headroom` | **Default.** Affinity, then most headroom. |
|
|
364
|
+
| `headroom` | `sticky_headroom` with affinity off, and nothing else changed. Identical to the default for traffic that has no cache owner, so it never routes better. |
|
|
365
|
+
| `cost_tiered` | Drain cheap accounts first, spill upward. |
|
|
366
|
+
| `priority` | Strict ordered failover: primary, then backup. |
|
|
367
|
+
| `least_loaded` | Baseline. |
|
|
368
|
+
| `round_robin` | Baseline. Ignores every signal, on purpose — it's there to benchmark against. |
|
|
369
|
+
|
|
370
|
+
Weights are config, not code. See `routing.weights` in `tokenbiryani.example.yaml`.
|
|
371
|
+
`tokenbiryani strategies` lists what this install has, including any installed plugins:
|
|
372
|
+
a strategy can ship in its own package under the `tokenbiryani.strategies` entry point,
|
|
373
|
+
supplying either weights or its own scoring.
|
|
374
|
+
|
|
375
|
+
### Failure handling
|
|
376
|
+
|
|
377
|
+
| Upstream | Account | Request |
|
|
378
|
+
|---|---|---|
|
|
379
|
+
| `429` | cooldown until `retry-after` | retry elsewhere |
|
|
380
|
+
| `529` | short cooldown | retry |
|
|
381
|
+
| `500`/`502`/`503` | error tick, breaker may trip | retry with jitter |
|
|
382
|
+
| `401`/`403` auth | **disabled**, operator alerted | retry elsewhere |
|
|
383
|
+
| `403` model denied | model marked unsupported here | retry elsewhere |
|
|
384
|
+
| `400` / `413` | none — not the account's fault | **returned as-is, never retried** |
|
|
385
|
+
|
|
386
|
+
Retrying a `400` across the whole pool is the classic amplification bug in gateways like
|
|
387
|
+
this. The taxonomy exists to prevent exactly that.
|
|
388
|
+
|
|
389
|
+
### The one failure that can't be hidden
|
|
390
|
+
|
|
391
|
+
Once the first SSE byte reaches the client, transparent failover is impossible — the
|
|
392
|
+
client is already rendering. So the gateway buffers the upstream stream until the first
|
|
393
|
+
`content_block_delta` (or `retry.first_token_grace_seconds`). A failure **before** that
|
|
394
|
+
point is retried silently on another account. A failure **after** it arrives as an SSE
|
|
395
|
+
`error` frame and the request ends.
|
|
396
|
+
|
|
397
|
+
---
|
|
398
|
+
|
|
399
|
+
## Docker
|
|
400
|
+
|
|
401
|
+
```bash
|
|
402
|
+
docker compose up -d # gateway + Redis + a mock Anthropic
|
|
403
|
+
docker compose down # stop it
|
|
404
|
+
```
|
|
405
|
+
|
|
406
|
+
Nothing to set first. The stack comes up with an empty pool, which is what the
|
|
407
|
+
onboarding wizard is for: open `http://localhost:8787/console` and add your first
|
|
408
|
+
credential there. Until you do, `/healthz` answers 503 and the container reports
|
|
409
|
+
itself unhealthy — an honest answer, since a pool with no accounts can serve
|
|
410
|
+
nothing.
|
|
411
|
+
|
|
412
|
+
`./src` is bind-mounted and watched, so editing a file on the host restarts the
|
|
413
|
+
gateway in about a second; the console's HTML and CSS need only a browser refresh;
|
|
414
|
+
and `./tests` is mounted too, so `docker compose exec gateway pytest -q` runs the
|
|
415
|
+
suite against the running stack.
|
|
416
|
+
|
|
417
|
+
The image runs as a non-root user, carries a healthcheck wired to `/healthz`, and
|
|
418
|
+
publishes to `127.0.0.1` rather than your LAN. `docker compose` builds the Dockerfile's
|
|
419
|
+
`dev` target; the default `runtime` target is what ships — wheel only, no source, no
|
|
420
|
+
test dependencies.
|
|
421
|
+
|
|
422
|
+
> The keys in `docker-compose.yml` are development values in a public repository.
|
|
423
|
+
> Copy `.env.example` to `.env` and replace them before this touches anything real —
|
|
424
|
+
> in particular `TOKENBIRYANI_SECRET_KEY`, which encrypts stored account credentials
|
|
425
|
+
> and must outlive the container. [docs/deployment.md](docs/deployment.md) explains both.
|
|
426
|
+
|
|
427
|
+
## Operating it
|
|
428
|
+
|
|
429
|
+
Open **`http://localhost:8787/console`**. Everything the gateway can do, it can do from
|
|
430
|
+
there:
|
|
431
|
+
|
|
432
|
+
- **Accounts** — add, name, test, rename, rotate, enable, disable and delete
|
|
433
|
+
credentials without editing a file. Anthropic API keys, Bedrock, Vertex, and Claude
|
|
434
|
+
subscriptions via a browser login. Credentials are encrypted at rest; accounts
|
|
435
|
+
declared in `tokenbiryani.yaml` render locked, because the file is yours.
|
|
436
|
+
- **Usage** — token, cost and cache-hit-rate charts over 1h / 24h / 7d / 30d, grouped
|
|
437
|
+
by account, model or virtual key, with a totals table. This history is persisted, so
|
|
438
|
+
it survives a restart. See [docs/usage.md](docs/usage.md).
|
|
439
|
+
- **Overview** — capacity horizon, live request feed, per-account meters.
|
|
440
|
+
- **Efficiency** — the four questions the meters cannot answer: will the quota last
|
|
441
|
+
the week, is the prompt cache even switched on, is one conversation running away,
|
|
442
|
+
and is the pool reserving output it never uses. See
|
|
443
|
+
[docs/pacing.md](docs/pacing.md).
|
|
444
|
+
- **Requests** — the routing inspector: why each request went where it did.
|
|
445
|
+
- **Connect a client** — the exact export lines for this gateway's address.
|
|
446
|
+
- **Keys** — mint and revoke virtual keys.
|
|
447
|
+
|
|
448
|
+

|
|
451
|
+
|
|
452
|
+
Click an account and it opens: its limits, what its meters can and cannot tell you,
|
|
453
|
+
where its credential came from, an error breakdown by class, and its own recent
|
|
454
|
+
requests.
|
|
455
|
+
|
|
456
|
+

|
|
460
|
+
|
|
461
|
+
Settings shows what the gateway is *currently running* — strategy and price table, each
|
|
462
|
+
marked with where its value came from, and a Reload that re-reads the file.
|
|
463
|
+
|
|
464
|
+

|
|
467
|
+
|
|
468
|
+
It is one server-rendered page plus a stylesheet, inside the package — no build step, no
|
|
469
|
+
Node toolchain added to a `pipx install`. The shell carries no data and needs no key; it
|
|
470
|
+
asks for an admin key on first load and keeps it in that browser only.
|
|
471
|
+
|
|
472
|
+
### Does it actually work against the real API?
|
|
473
|
+
|
|
474
|
+
The one thing no mock can tell you is whether Anthropic spells its rate-limit headers
|
|
475
|
+
the way the router expects. If it doesn't, the mirror stays empty, every account reads
|
|
476
|
+
as full, and routing quietly degrades to round-robin — shredding the prompt cache while
|
|
477
|
+
looking healthy.
|
|
478
|
+
|
|
479
|
+
```bash
|
|
480
|
+
tokenbiryani doctor --api-key sk-ant-...
|
|
481
|
+
```
|
|
482
|
+
|
|
483
|
+
One real request, `max_tokens=1`. It prints the headers the upstream actually returned
|
|
484
|
+
next to the nine the limit mirror looks for, and what the mirror parsed out of them.
|
|
485
|
+
Non-zero exit if anything is missing. Run it once after you first point this at
|
|
486
|
+
production.
|
|
487
|
+
|
|
488
|
+
Or stay in the terminal:
|
|
489
|
+
|
|
490
|
+
```bash
|
|
491
|
+
tokenbiryani status # the pool, in the terminal you're already in
|
|
492
|
+
tokenbiryani status --json # same data, for scripts
|
|
493
|
+
```
|
|
494
|
+
|
|
495
|
+
```
|
|
496
|
+
POOL 702k tok ready · next reset 00:12 · queue 0 · cache 94%
|
|
497
|
+
|
|
498
|
+
ACCOUNT STATE REQ INPUT OUTPUT RESET CACHE
|
|
499
|
+
acct-01 ● ready 98% 82% 79% 00:41 97%
|
|
500
|
+
acct-02 ● cooling 4% 0% 6% 00:27 —
|
|
501
|
+
|
|
502
|
+
1h 412 requests · 3 failovers · 1 cache break · 0 errors · $18.40
|
|
503
|
+
```
|
|
504
|
+
|
|
505
|
+
| Endpoint | |
|
|
506
|
+
|---|---|
|
|
507
|
+
| `GET /console` | the operator console |
|
|
508
|
+
| `POST /v1/messages` | Messages API, streaming and not |
|
|
509
|
+
| `POST /v1/messages/count_tokens`, `GET /v1/models` | passthrough |
|
|
510
|
+
| `GET /healthz` | 200 while any account is ready |
|
|
511
|
+
| `GET /admin/status` | pool snapshot |
|
|
512
|
+
| `GET /admin/usage` | bucketed usage history for the charts |
|
|
513
|
+
| `POST /admin/accounts` · `PATCH` · `DELETE` · `POST /admin/accounts/{id}/test` | manage credentials at runtime |
|
|
514
|
+
| `POST /admin/keys` · `DELETE /admin/keys/{name}` | mint and revoke keys at runtime |
|
|
515
|
+
| `GET /admin/accounts/{id}` | one account: limits, error breakdown by class, its own recent requests |
|
|
516
|
+
| `POST /admin/reload` | re-read the config file |
|
|
517
|
+
| `GET /admin/requests/{id}` | **why that request went where it did** — attempt chain, per-candidate scores, verdicts |
|
|
518
|
+
| `GET /admin/horizon` | projected capacity for the next hour |
|
|
519
|
+
| `GET /admin/estimation` | what the output estimator has learned, per model |
|
|
520
|
+
| `GET /admin/pacing` | **is this pool on course to spend its week** — or run dry early, or strand quota |
|
|
521
|
+
| `GET /admin/sessions` | the most expensive conversations in the window, runaways flagged |
|
|
522
|
+
| `GET /admin/cache-advice` | **why the cache hit rate is what it is** — whether the client ever sent a breakpoint, per key and model |
|
|
523
|
+
| `GET /admin/events` | live SSE feed |
|
|
524
|
+
|
|
525
|
+
The request inspector is the point. `filtered — cooling, 27s remaining` is a complete
|
|
526
|
+
answer; "load balanced" is not.
|
|
527
|
+
|
|
528
|
+
**`/admin/*` requires a key with `admin: true`.** It exposes account ids, spend and key
|
|
529
|
+
management, so a tenant key must not reach it. A gateway with no keys configured at all
|
|
530
|
+
is loopback development mode and stays fully open.
|
|
531
|
+
|
|
532
|
+
### Managing keys at runtime
|
|
533
|
+
|
|
534
|
+
```bash
|
|
535
|
+
curl -sX POST localhost:8787/admin/keys -H "x-api-key: $ADMIN_KEY" \
|
|
536
|
+
-d '{"name":"tenant-1","pool":["acct-02"],"rpm":60,"spend_cap_usd":5}'
|
|
537
|
+
# -> {"key": "bir_...", "record": {...}} the plaintext appears exactly once
|
|
538
|
+
|
|
539
|
+
curl -sX DELETE localhost:8787/admin/keys/tenant-1 -H "x-api-key: $ADMIN_KEY"
|
|
540
|
+
```
|
|
541
|
+
|
|
542
|
+

|
|
545
|
+
|
|
546
|
+
Minted keys are stored **hashed**, so a leaked state store is not a leaked key, and they
|
|
547
|
+
live in the shared store — one instance honours a key another minted. Keys declared in
|
|
548
|
+
the config file belong to the file: the API will not revoke them.
|
|
549
|
+
|
|
550
|
+
### The spill lane
|
|
551
|
+
|
|
552
|
+
With `batch.enabled: true`, a `batch`-priority request that finds the pool saturated goes
|
|
553
|
+
to the **Message Batches API** instead of waiting. The gateway holds the connection while
|
|
554
|
+
it polls, bounded by that request's own wait budget. A batch that outlives the budget is
|
|
555
|
+
**cancelled upstream** and its id returned in `x-tokenbiryani-batch-id`, so nothing is
|
|
556
|
+
silently abandoned. If submission fails the request falls back to the normal queue — the
|
|
557
|
+
spill lane is an optimisation, never a dependency. Streaming requests never spill.
|
|
558
|
+
|
|
559
|
+
### Account types
|
|
560
|
+
|
|
561
|
+
| `type` | Notes |
|
|
562
|
+
|---|---|
|
|
563
|
+
| `anthropic_api` | Anthropic API keys. The default. |
|
|
564
|
+
| `bedrock` | AWS Bedrock. SigV4-signed; its binary event-stream is decoded back to SSE so the rest of the gateway sees ordinary streaming. Needs `pip install "tokenbiryani[bedrock]"`. |
|
|
565
|
+
| `vertex` | Google Vertex AI. Bearer token from application-default credentials; returns real SSE already. Needs `pip install "tokenbiryani[vertex]"`. |
|
|
566
|
+
| `oauth` | A Claude subscription (Max/Pro). Three token sources, offered in the console's Add-account dialog: this machine's Claude Code login (nothing to configure), a long-lived token from `claude setup-token`, or an OAuth login the gateway runs itself — that last one stays disabled until you supply the provider endpoints, which this project will not guess at. Read [docs/oauth.md](docs/oauth.md) first: a subscription reports rolling-window utilisation rather than per-window budgets, so it keeps headroom routing and failover but has no leases, no admission control and no capacity horizon. |
|
|
567
|
+
|
|
568
|
+

|
|
572
|
+
|
|
573
|
+
All four sit in one pool, so a request can fail over from an API key to Bedrock. Use
|
|
574
|
+
`options.model_map` to translate your callers' model names into each platform's ids.
|
|
575
|
+
|
|
576
|
+
```yaml
|
|
577
|
+
accounts:
|
|
578
|
+
- id: acct-01
|
|
579
|
+
type: anthropic_api
|
|
580
|
+
api_key: ${ANTHROPIC_API_KEY}
|
|
581
|
+
- id: acct-bedrock
|
|
582
|
+
type: bedrock
|
|
583
|
+
cost_tier: 1.2
|
|
584
|
+
options:
|
|
585
|
+
region: us-east-1
|
|
586
|
+
model_map:
|
|
587
|
+
claude-test-1: anthropic.claude-3-5-sonnet-20241022-v2:0
|
|
588
|
+
- id: acct-vertex
|
|
589
|
+
type: vertex
|
|
590
|
+
options:
|
|
591
|
+
project: my-project
|
|
592
|
+
region: us-central1
|
|
593
|
+
```
|
|
594
|
+
|
|
595
|
+
### Request headers
|
|
596
|
+
|
|
597
|
+
| Header | |
|
|
598
|
+
|---|---|
|
|
599
|
+
| `X-TokenBiryani-Session` | pin a conversation to one affinity key instead of the fingerprint |
|
|
600
|
+
| `X-TokenBiryani-Priority` | `interactive` (default) or `batch`. Batch traffic yields the queue to interactive traffic when the pool is saturated |
|
|
601
|
+
| `X-TokenBiryani-Max-Wait` | seconds this request will wait for capacity. A client can shorten its own budget but never extend it past the operator's ceiling |
|
|
602
|
+
|
|
603
|
+
Per-key defaults for the last two live under `keys:` as `priority` and `max_wait_seconds`.
|
|
604
|
+
|
|
605
|
+
### Spend caps
|
|
606
|
+
|
|
607
|
+
Caps come at two scopes. `keys[].spend_cap_usd` bounds everything a key does;
|
|
608
|
+
`session_cap_usd` and `session_max_turns` bound one *conversation* inside that
|
|
609
|
+
allowance. The second exists because the first cannot see a runaway: one agent loop
|
|
610
|
+
resending a large prefix a few hundred times is a whole key's cap with that key's
|
|
611
|
+
name on it, and until it trips there is nothing to look at. `GET /admin/sessions`
|
|
612
|
+
ranks conversations by cost and flags the ones past `sessions.runaway_turns`.
|
|
613
|
+
|
|
614
|
+
Caps are **windowed, not lifetime** (`spend.window_hours`, default 24). A lifetime cap on
|
|
615
|
+
a persistent store would eventually wedge the gateway shut and stay that way.
|
|
616
|
+
|
|
617
|
+
They only survive a restart if the store does. `store.backend: memory` (the default)
|
|
618
|
+
loses affinity and the spend ledger when the process dies — meaning every cap silently
|
|
619
|
+
resets. Use `sqlite` for a real deployment:
|
|
620
|
+
|
|
621
|
+
```yaml
|
|
622
|
+
store:
|
|
623
|
+
backend: sqlite
|
|
624
|
+
path: tokenbiryani.db
|
|
625
|
+
```
|
|
626
|
+
|
|
627
|
+
### Running more than one instance
|
|
628
|
+
|
|
629
|
+
`store.backend: redis` shares affinity, the spend ledger and per-key rate counters
|
|
630
|
+
between processes. Without it two instances each keep their own affinity map — so a
|
|
631
|
+
conversation ping-pongs between them and loses its cache — and each enforces its own
|
|
632
|
+
half of every spend cap.
|
|
633
|
+
|
|
634
|
+
```yaml
|
|
635
|
+
store:
|
|
636
|
+
backend: redis
|
|
637
|
+
url: redis://127.0.0.1:6379/0
|
|
638
|
+
namespace: tokenbiryani
|
|
639
|
+
```
|
|
640
|
+
|
|
641
|
+
Needs the optional dependency: `pip install "tokenbiryani[redis]"`.
|
|
642
|
+
|
|
643
|
+
### Costs
|
|
644
|
+
|
|
645
|
+
Costs are reported, and spend caps enforced, only for models that have a price.
|
|
646
|
+
`pricing: builtin` takes the dated table that ships with this release — the console
|
|
647
|
+
shows its date beside every cost — and naming a model under `pricing:` overrides it.
|
|
648
|
+
|
|
649
|
+
Prices live in a dated data file rather than in code, because the gateway must never
|
|
650
|
+
bill you against a number nobody can attribute. A dated file whose date is on screen
|
|
651
|
+
can be attributed; a dict compiled into a release cannot.
|
|
652
|
+
|
|
653
|
+
### Privacy and security
|
|
654
|
+
|
|
655
|
+
- Prompt bodies are **never logged**. Only accounting: ids, accounts, tokens, latency.
|
|
656
|
+
- Credentials are never logged and are masked in every admin response.
|
|
657
|
+
- Binds to loopback. Refuses to start on a public interface without both
|
|
658
|
+
`server.allow_remote: true` and at least one configured key.
|
|
659
|
+
|
|
660
|
+
---
|
|
661
|
+
|
|
662
|
+
## Documentation
|
|
663
|
+
|
|
664
|
+
Full docs build from `docs/` with `mkdocs serve`. Start with
|
|
665
|
+
[Why is my bill higher?](docs/caching.md) — it is the page that changes how you
|
|
666
|
+
configure this thing.
|
|
667
|
+
|
|
668
|
+
## Status
|
|
669
|
+
|
|
670
|
+
All eight milestones in `PLAN.md` are implemented and tested; see `TODO.md` for the
|
|
671
|
+
table and for what was deliberately left out.
|
|
672
|
+
|
|
673
|
+
Working today: passthrough and streaming, multi-account pooling, the error taxonomy,
|
|
674
|
+
retry and failover, the rate-limit mirror, token estimation and leases, headroom scoring,
|
|
675
|
+
circuit breakers, session affinity and cache accounting, admission control and a bounded
|
|
676
|
+
priority queue, virtual keys with model/pool/rpm/spend scoping,
|
|
677
|
+
structured logs, config hot reload, the admin API, and the CLI. Request priority with a
|
|
678
|
+
per-request wait budget, a batch spill lane, and SQLite-backed persistence for affinity
|
|
679
|
+
and windowed spend, a Redis store for multi-instance deployments, and runtime key
|
|
680
|
+
management behind an admin boundary, plus Bedrock and Vertex adapters and pluggable
|
|
681
|
+
routing strategies, and the operator console. 379 tests including a lease-concurrency
|
|
682
|
+
suite, a reproducible benchmark, and an end-to-end smoke test over real sockets
|
|
683
|
+
(`scripts/smoke.sh`).
|
|
684
|
+
|
|
685
|
+
All eight milestones in `PLAN.md` are built. `docs/UI-DESIGN.md` is the console's design
|
|
686
|
+
brief, and the console follows it.
|
|
687
|
+
|
|
688
|
+
**Credential types.** Anthropic API keys are the supported path. A *subscription*
|
|
689
|
+
account works — routing your own subscription through your own local gateway is the
|
|
690
|
+
ordinary case, and it reports enough (rolling-window utilisation) to route on — but
|
|
691
|
+
pooling several so their limits add up runs against Anthropic's consumer terms. Leases,
|
|
692
|
+
admission control and the capacity horizon need absolute token counts and stay dark for
|
|
693
|
+
those accounts. See [docs/oauth.md](docs/oauth.md).
|
|
694
|
+
|
|
695
|
+
## License
|
|
696
|
+
|
|
697
|
+
Apache-2.0.
|