Skip to main content

tokz

Deterministic context compression with byte offsets, extractive provenance, adaptive budgets, hard preserve rules, ordered batch calls, and agent adapters.

Hosted mode sends the payload to Tokz, where it is never stored or logged. Structural responses contain byte ranges and semantic responses contain extractive text with provenance. Nothing is paraphrased or generated.

pip install tokz

Use the resilient call, not the raw one

import os
from tokz import Tokz, CircuitBreaker, CompressionCache, resilient_compress

tokz = Tokz(api_key=os.environ["TOKZ_API_KEY"])

# One of each per process, not per call — both carry the state that is the point.
breaker = CircuitBreaker()
cache = CompressionCache()

text, compressed = resilient_compress(
    tokz,
    breaker,
    payload,
    cache=cache,
    on_error=lambda info: print("tokz fell back:", info["message"]),
    on_credits_exhausted=lambda cents: alert(f"tokz balance {cents}c"),
)
# `compressed` is False when this is your original payload coming back.

Tokz.compress() raises on failure — it is a plain client, so a fault surfaces rather than hiding. resilient_compress() never raises and never lets a failure reach your LLM call. Reach for the second one unless you have a specific reason not to.

What it does that a try/except does not

  • Bounds an outage. A bare except pays the full timeout on every payload. The breaker opens after five consecutive failures and admits one trial per reset window, so a dead API costs one timeout instead of N.
  • Serves the cache first. The cache is checked before the breaker, so a payload you have already compressed still returns its real result while the API is down — better than falling back to text you have an answer for.
  • Separates billing from outage. HTTP 402 will not succeed on retry and does not mean the API is down, so it routes to on_credits_exhausted and leaves the breaker closed. Tripping it would skip compression for a whole reset window over an empty wallet.
  • Cannot be broken by your logger. on_error is best-effort; a handler that raises will not turn a swallowed compression failure into a failed request.

Async

from tokz import AsyncTokz, CircuitBreaker, aresilient_compress

async with AsyncTokz(api_key=...) as tokz:
    text, compressed = await aresilient_compress(tokz, breaker, payload)

Same contract, same retry policy, same fallback.

Decisions

decide() answers typed questions about text (choice, multilabel, bool, score) with the OpenDecision models. It runs a model on Tokz servers, is billed per request, and is never retried. AsyncTokz has the same methods.

out = tokz.decide(
    "I was charged twice and the app keeps logging me out.",
    {
        "queue": {"type": "choice", "options": ["billing", "technical", "account"]},
        "priority": {"type": "score", "low": 1, "high": 5},
    },
)
r = out["results"][0]
r["queue"]["best"], r["priority"]["score"], out["usage"]["billed_tokens"]

catalog = tokz.list_decision_models()

Firewall

compress_context() preserves trusted policy and task control segments while compressing only declared structural data. The client verifies every returned segment and assembles text locally.

result = tokz.compress_context([
    {"id": "system", "role": "protected", "trust": "trusted", "text": system_prompt},
    {"id": "user", "role": "control", "trust": "untrusted", "text": user_prompt},
    {"id": "tool", "role": "data", "trust": "untrusted", "text": tool_result},
], query="Which job failed?", max_bytes=12_000)

AsyncTokz.compress_context() provides the same contract. Firewall v1 passes prose data through unchanged and prevents data from changing protected selection; it does not claim to control downstream model behavior.

Getting dropped text back

Compression is not a one-way door. Every elision carries its position and length, so a dropped run stays addressable — locally, with no second API call and no key.

from tokz import expand

result = tokz.compress(payload, target_ratio=0.4)
dropped = expand(payload, result["spanMap"], elision=0)

The source hash is verified first, so a span map can never be applied to text it was not built from.

Offsets are UTF-8 bytes

Not string indices. The two agree only for pure ASCII, and this SDK handles the conversion for you — but if you slice a span map yourself, encode first:

src = payload.encode("utf-8")
kept = b"".join(src[s["s"]:s["e"]] for s in span_map["spans"]).decode("utf-8")

Doing it on the str corrupts any payload containing an accent, a CJK character or an emoji, and does it quietly.

When it is not worth using

Compression pays above roughly $0.18 per million input tokens on uncached payload. On cheap models, or on context your prompt cache already holds, the fee exceeds the saving. The estimator at https://app.tokz.dev/savings will tell you which side of that line you are on, including when the answer is no.

MIT

Metadata

Release files for tokz 0.4.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 tokz 0.4.0
File Size Uploaded Provenance Actions
tokz-0.4.0.tar.gz 27.8 kB Without provenance Details for tokz-0.4.0.tar.gz

Built distribution (wheel)

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

Total release size: 53.3 kB

Release files / tokz-0.4.0.tar.gz

Download URL tokz-0.4.0.tar.gz
Size 27.8 kB
Tags Source
SHA-256 checksum
How to use checksums
9a0a3e5c8550a8e352bc674c16d9c03d0458e216df65e1d417e18cfde670180c
BLAKE2b-256 checksum
How to use checksums
cf361b4e645aee2577db4d19453b3d768845b61d1d1a44096a0808062e517773
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.10.11

Release files / tokz-0.4.0-py3-none-any.whl

Download URL tokz-0.4.0-py3-none-any.whl
Size 25.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
84b504e9c9b5ea9109a822df1ac0c6f9e878e2d60818c8120fb9ac6b2ee7b026
BLAKE2b-256 checksum
How to use checksums
c1d3928cffaf6ec2ddc4c745c433e791522f3fc624ee54ad40ed7fbeb6e7fdad
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.10.11

Security for tokz 0.4.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.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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