Skip to main content

tokenmaster

Core context-budget metering and decision engine for LLM applications.

tokenmaster answers four questions for any model, provider, and conversation:

  1. How much context has been used, and on what (messages, system prompt, tool schemas, reasoning tokens, cache reads)?
  2. How much usable budget remains, measured against calibrated effective capacity rather than the advertised window?
  3. How many turns remain until exhaustion at the current token velocity?
  4. Should this conversation be compacted or handed off now, and what would that decision cost?

Install

pip install tokenmaster

Quickstart

from tokenmaster import CostModelPolicy, Meter, TaskContext

meter = Meter.for_model("anthropic:claude-sonnet-4-6")

# after each model response, feed it the usage numbers
meter.record({
    "input_tokens": 52_000,
    "cache_read_tokens": 118_000,
    "output_tokens": 1_800,
    "reasoning_tokens": 3_200,
})

state = meter.state()
state.fill_effective   # fraction of usable budget consumed
state.eta_turns        # projected turns to exhaustion (needs 3 turns of data)
state.zone             # green / caution / critical
state.provenance       # where every number came from

# judgment, with the arithmetic attached
rec = meter.advise(TaskContext(expected_remaining_turns=12))
rec.action, rec.urgency        # continue / compact / handoff
rec.rationale.comparison       # the comparison that produced the verdict

# the cost model prices compact vs handoff vs continue, cache economics included
policy = CostModelPolicy.for_profile(meter.profile)
meter.advise(TaskContext(expected_remaining_turns=40), policy=policy)

Models outside the registry

Any model works; the bundled registry is a convenience, not a gate. For an id the snapshot does not know (an OpenRouter route, a local runtime, a private deployment), build a ModelProfile and either pass it straight to Meter or register it once per process:

from tokenmaster import Meter, ModelProfile, default_registry

profile = ModelProfile(
    model_id="openrouter:z-ai/glm-5.2",   # canonical form: provider:model
    provider="openrouter",
    window_nominal=200_000,
)

meter = Meter(profile)   # this meter only

default_registry().register(profile, aliases=["glm-5.2"])
meter = Meter.for_model("z-ai/glm-5.2")   # resolves process-wide now

The part after the colon resolves as a bare name automatically, so the verbatim OpenRouter id works once the profile is registered; extra spellings go in aliases. Later registrations win, which makes the same call the way to override a bundled model's capacities or pricing. Only window_nominal is load-bearing; pricing is optional and feeds the cost-model policy. Without a CalibrationRecord the gauges run against the nominal window and the provenance says so: "nominal (uncalibrated)".

What is in 0.2.0

  • Normalized TurnUsage accounting, with the hidden consumers (reasoning tokens, cache reads and writes, system prompt and tool-schema overhead) as first-class categories and a provenance tag on every number.
  • MeterState gauges: effective versus nominal budget, EWMA token velocity, turns-to-exhaustion with a conservative bound, zone classification.
  • A bundled model registry (15 models with dated, cited pricing), alias and dated-suffix resolution, user overrides, and Meter.for_model for zero-configuration attachment. GPT-5.6 Sol, Terra, and Luna include Standard short- and long-context tiers.
  • Tier-aware usage quotes, conservative request-cost estimates, and limit checks, with cache reads, cache writes, visible output, and reasoning kept exclusive and auditable. Provider charges that require missing dimensions, such as Gemini cache-storage token-hours, are marked unpriced and fail closed instead of being quoted as free.
  • A typed event stream (six event types with exact wire round-trips): the contract that visualizers such as ctxmaster, or your own, build on.
  • Three advisor policies: a threshold baseline that reproduces current practice, a predictive policy that compares conservative ETA against the task horizon, and a cost model that prices continue, compact, and handoff, including the cache break-even horizon k* that compaction must clear before it saves money.
  • A handoff fidelity protocol (probe question answering) that makes "was that continuation prompt any good" measurable, with every LLM touchpoint behind an adapter so the protocol runs fully offline.
  • Conformance vectors under spec/ in the repository: the executable cross-language specification the JavaScript and Rust ports must match.

Not yet included (planned)

Provider usage adapters (Anthropic and OpenAI response normalizers), tokenizer estimators, LLM-backed probe generators and judges, calibrated effective-capacity data (defaults equal the nominal window, and the provenance says so), and async event delivery. The JavaScript and Rust ports mirror the 0.2 pricing and limit APIs and remain conformant against the shared vectors.

Design

The core has zero hard dependencies and never touches the network during ordinary imports or use. The separately invoked tokenmaster-models maintainer command can check/propose/apply official OpenAI registry updates; it is fail-closed and review-oriented. Every quantity carries its provenance; every recommendation ships the arithmetic that produced it; parameters that have not been measured yet are labeled provisional. The full contract lives at docs/core-api.md in the repository: https://github.com/jemsbhai/tokenmaster

The companion package ctxmaster provides the terminal gauge and other visual surfaces on top of the event stream.

License

MIT

Metadata

Release files for tokenmaster 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tokenmaster 0.2.0
File Size Uploaded Provenance
tokenmaster-0.2.0.tar.gz 57.5 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for tokenmaster 0.2.0
File Interpreter ABI Platform
tokenmaster-0.2.0-py3-none-any.whl Python 3 none any Details

Total release size: 102.7 kB

Release files / tokenmaster-0.2.0.tar.gz

Download URL tokenmaster-0.2.0.tar.gz
Size 57.5 kB
Tags Source
SHA-256 checksum
How to use checksums
f562069ec37e1cd5c3abe487d150b69ae824c00c4c510c68cd578c893ab0b70b
BLAKE2b-256 checksum
How to use checksums
c07af14eb0911dcd44997f66fa1a2d3c8f7453f3af3ee4060e83390f30965b05
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.2

Release files / tokenmaster-0.2.0-py3-none-any.whl

Download URL tokenmaster-0.2.0-py3-none-any.whl
Size 45.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e15fbfaef7bb2f3f9cc9e5c82f0bbf300571a00ae4804f5c5ff1cb8ef33f557a
BLAKE2b-256 checksum
How to use checksums
d19ea47beaada601b85dcd2f89c1b821d14e169a61e3ab4df6961422bd04ec51
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.2

Security for tokenmaster 0.2.0

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page