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.

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.3.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.3.0
File Size Uploaded Provenance Actions
tokz-0.3.0.tar.gz 25.2 kB Without provenance Details for tokz-0.3.0.tar.gz

Built distribution (wheel)

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

Total release size: 48.2 kB

Release files / tokz-0.3.0.tar.gz

Download URL tokz-0.3.0.tar.gz
Size 25.2 kB
Tags Source
SHA-256 checksum
How to use checksums
9bb4aceaf8e06e0acfa7119b062aa6f2acc7a9907fd6228ae58c11c5914ce1eb
BLAKE2b-256 checksum
How to use checksums
b266f7ffcbb185a7b01c8c95e99b75c930cd5408736312bf3e2e181241da5dfc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.11

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

Download URL tokz-0.3.0-py3-none-any.whl
Size 23.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0c44bb8517de49e43704acaeae204651154bf65c2740ac6f266c0ffdccbd7abe
BLAKE2b-256 checksum
How to use checksums
ad76480ac5a9abbd624e986ad1740a2ec333d7cd0a0853b612535b32c1e1e31f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.10.11

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