cendor-tokenguard
Stop runaway LLM bills, and get per-feature / per-user cost attribution for free. One decorator, one context manager. No dashboard, no account, no infra.
Cap a runaway loop before it overspends — and see which feature or user spent the rest.
·
pip install cendor-tokenguard
Using an AI coding assistant? npx @cendor/init (TS) / uvx cendor-init (Python) wires it up — or point it at cendor.ai/docs/for-ai-assistants.
from cendor.core import instrument
from cendor.tokenguard import budget, track, report
client = instrument(openai_client) # wrap once; tokenguard subscribes, never patches
@budget(usd=0.50, on_exceed="downgrade", downgrade={"gpt-4o": "gpt-4o-mini"})
def answer(q: str) -> str:
with track(feature="support_bot", user_id="alice"): # ambient attribution, zero bookkeeping
resp = client.chat.completions.create(model="gpt-4o", messages=[{"role": "user", "content": q}])
return resp.choices[0].message.content
for row in report(group_by=["feature", "user_id"]): # where did the money go?
print(row["tags"], row["usd"], row["calls"])
Highlights
- Pre-flight circuit breaker —
on_exceed="block"raises before an over-budget call runs;"downgrade"reroutes to a cheaper model pre-flight;"clamp"caps one call server-side via the provider's own token ceiling (next bullet);"break"cuts a running stream mid-flight (see Streaming timing);"truncate"degrades;"raise"stops a runaway loop; or call your own function. - Reasoning models, handled — you can't predict a thinking model's hidden reasoning pre-flight, so
on_exceed="clamp"injects the provider's own token ceiling (max_completion_tokens/max_tokens) sized to the remaining budget — the call is capped server-side instead of overspending.report()breaks outreasoning_tokens, and the cumulative gate enforces on exact usage (which already includes reasoning). Seedocs/tokenguard.md→ Reasoning models. - Decorator and context manager — budgets nest (an inner downgrade never masks an outer hard cap); config is validated at creation (a typo'd
on_exceedor a map-lessdowngradeis aValueError, never a silent no-op). - Cost attribution, free —
track(feature=…, user_id=…)tags ambient spend viacontextvars(sync + async);report(group_by=[…])shows where the money went, reasoning tokens included. - Cost as a test assertion —
report().assert_under(usd=0.05, feature="search"). - Pre-flight projection —
estimate(model, messages)prices a call without making it. - Spend reaches your backend on its own (1.6.0) — with OpenTelemetry installed and a provider configured by your app, every priced row is also written to
gen_ai.client.token.usage/.cost.usdcounters through an internal additive tap, dimensioned bymodel+ yourtrack(...)tags. Nouse_sinkline needed;CENDOR_TELEMETRY=offdisables it. Your sink slot stays yours — the tap never displaces it, and it stands down if your own sink already is anOTelSink. - Durable + bounded — pluggable
use_sink(tokenguard.sinks.SQLiteSink / OTelSink); FIFO-bounded in-memory buffer (configure(max_records=…),dropped()). For long runs, wrap a durable sink insinks.QueueSink(SQLiteSink(path))so its I/O runs on a background thread and adds no per-call latency —flush()/close()guarantee durability at shutdown. - No silent USD blind spots — a call whose model isn't in the price table records
$0, so a USD cap can't bite. tokenguard warns once per model (UnpricedModelWarning) and counts these inunpriced_calls()/report()'sunpriced_calls;configure(on_unpriced="raise")makeson_exceed="block"reject them. A token cap is unaffected — tokens are counted regardless of price. - Thread-safe, with one caveat — the spend buffer and
SQLiteSinkare lock-guarded for concurrent emits, but budgets/tags areContextVar-based:asynciotasks inherit them, a plainthreading.Threaddoes not (carry them withcontextvars.copy_context()).
Streaming timing — post-flight raise/truncate fire when a stream is consumed, not when it's launched (the call is accounted once the chunk iterator drains). A loop that launches many streams before draining them can overspend — drain each stream before the next, or use a pre-flight mode (block/downgrade/clamp), which is unaffected. For a single stream that would blow past the cap mid-generation, on_exceed="break" is the breaker built for exactly this: it recounts the stream as it arrives and cuts it the instant its running output estimate crosses the remaining budget — you keep the partial output already yielded, and the provider still bills to the cut (it stops the meter, it does not un-bill).
Wrap-around — it rides the call you already make. Offline and standalone — bundled prices, no account.
See docs/tokenguard.md · CHANGELOG. Part of the Cendor stack — github.com/cendorhq/cendor-libs. Powered by PowerAI Labs. Apache-2.0; provided "as is", without warranty — use at your own risk (LICENSE §7–8).
Metadata
Release files for cendor-tokenguard 1.8.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| cendor_tokenguard-1.8.0.tar.gz | 57.9 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| cendor_tokenguard-1.8.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 93.0 kB
Release files / cendor_tokenguard-1.8.0.tar.gz
| Download URL | cendor_tokenguard-1.8.0.tar.gz |
|---|---|
| Size | 57.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
93d362030e9890ce52c97c9f8fb7e843e896b0612bc8fff5877803a1a674d2df
|
|
BLAKE2b-256 checksum How to use checksums |
497c4a326f7ddd5ba52f7bd355e43818a4adf00caaeaaf87ce78009c2c8c7c36
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Aug 1, 2026.
Transparency logRelease files / cendor_tokenguard-1.8.0-py3-none-any.whl
| Download URL | cendor_tokenguard-1.8.0-py3-none-any.whl |
|---|---|
| Size | 35.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
94ce702676cb00a946e7933afd2b8e4d22c6419f7dad58465a659b894bbc2682
|
|
BLAKE2b-256 checksum How to use checksums |
969bd43cd62cbd6954bad30dcf08f0c077484009fb0adc43f4d5fd0f51b281c7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Aug 1, 2026.
Transparency log