Skip to main content

sandhi-gateway

Python binding for Sandhi — the metering layer for AI agents. The Rust core, in-process via PyO3: virtual keys, budgets, and neutral usage-event metering with zero network hop. Keep making your own provider calls; hand the response to Sandhi to meter it.

pip install sandhi-gateway   # import as: import sandhi_gateway

The bare name sandhi on PyPI is an unrelated Sanskrit-linguistics library; this binding is published as sandhi-gateway. The crate and GitHub repo are sandhi.

Source builds require Rust 1.99 or newer for the locked dependency graph. Wheels retain the CPython 3.11+ stable ABI and require the GIL; the dependency upgrade does not certify free-threaded execution. The local coverage harness validates CPython 3.11–3.13.

Usage

import json
import sandhi_gateway as sg

gw = sg.Gateway(sink_path="usage.jsonl")           # events append as JSONL (+ in-memory)
gw.add_virtual_key("vk_alice", subject="alice", group="platform", upstream="anthropic")
gw.set_budget("group:platform", 1_000_000)

# ... you make your own provider call and get the raw response JSON ...
event = gw.meter(
    "vk_alice", "anthropic", "claude-x", response_json,
    session_id="conv_7",
)
# event["tokens_in"], event["cache_read_tokens"], event["subject_id"], ...
print(gw.spent("group:platform"))                  # budget recorded
print(gw.check_budget("group:platform", 5000))     # True/False

# Just parse usage (same Rust parsers as the proxy), no attribution:
sg.parse_usage("openai", response_json)            # {tokens_in, tokens_out, cache_*, reasoning_*}

Typed persistent provider runtime

New integrations should reuse a typed provider handle. Its inputs and outputs are Sandhi's versioned neutral chat documents; provider-native JSON is encoded and decoded in Rust.

runtime = sg.ProviderRuntime()
provider = runtime.provider("openrouter", "openai/gpt-4o", api_key)
request = {
    "schema_version": "1",
    "model": "openai/gpt-4o",
    "messages": [{"role": "user", "content": "hello"}],
}
response = json.loads(await provider.complete_json(json.dumps(request)))

async for event_json in provider.stream_json(json.dumps(request)):
    event = json.loads(event_json)  # response_start, text_delta, tool_call_*, usage, finish

SDK dialects in-process

On the same handle, complete_sdk_json accepts a serialized SDK request and returns the selected dialect's response JSON. stream_sdk_json yields JSON records with event (the optional SSE event name) and data (the SDK payload). Iteration ends at stream EOF. The dialects are openai_chat, openai_responses, anthropic_messages, and gemini_generate_content. Supply Gemini's path model through model=. Use metadata_json= for RequestMetadataV1 and wire_headers_json= for per-call headers.

request = json.dumps({
    "model": "openai/gpt-4o",
    "messages": [{"role": "user", "content": "hello"}],
})
completion = json.loads(await provider.complete_sdk_json("openai_chat", request))

events = provider.stream_sdk_json("openai_chat", request)
try:
    async for event_json in events:
        frame = json.loads(event_json)
finally:
    await events.aclose()

SandhiSdkError carries JSON with status, error (the typed error), and body (the dialect error envelope). An upstream failure after stream setup can arrive as a dialect error event. Meaningful controls depend on the selected model and backend. The handle uses its configured credential. Use the HTTP gateway for virtual-key admission, durable budgets, and requests that depend on gateway-owned native references.

Neutral contract details

At contract minor 12, streaming requests can set include_native_stream: true for Chat, Messages, Responses and Gemini handles. Default is false; other families reject true. Opt-in adds native_frame events alongside canonical events. Render the native frames or the canonical content, and meter canonical usage once. Native frames preserve opaque provider state but do not make it portable across backends.

Minor 13 adds optional cache_intent, for example {"mode":"suppress_gateway"}. Suppression preserves native controls and adds no gateway markers; it cannot turn off provider-internal caching. Direct unconfigured handles accept preserve/suppress and refuse undeclared automatic capabilities before HTTP. Registered gateway backends can declare exact model/lifetime support; the internal compiled plan is excluded from JSON and schema. See the backend guide.

The typed JSON methods carry neutral v1 data. The handle retains its HTTP pool, circuit breaker, retry policy, and timeouts. Invalid documents fail before network I/O; runtime failures raise SandhiProviderError, whose message contains a serialized ProviderErrorV1. runtime.provider() resolves catalog defaults or accepts an explicit protocol and base URL. The provider label does not constrain an explicitly selected protocol:

provider = runtime.provider(
    "my-coding-backend", "my-model", api_key,
    base_url="https://api.z.ai/api/coding/paas/v4",
    protocol="chat_completions",
    endpoint_profile="openai_terminal_chunk_usage",
    max_retries=0,
)

Use anthropic_messages, responses or gemini_generate_content for those wire families. Profiles default to standard; compatible nonstandard Messages endpoints can explicitly select anthropic_implicit_cache. Profiles configure the immediate source and are never request-body parameters. They do not grant subscription or vault authority. See shared endpoint profiles for constraints. For a gateway second hop, use the explicit gateway peer contract; provider profiles describe direct upstream sources. runtime.openai_compat() remains a convenience for custom standard Chat endpoints.

Prepared 0.17.0 buffered calls use the same strict source usage qualification as accounted calls for Chat, Messages, Responses and Gemini, including Codex's constrained SSE aggregation. Missing/invalid counts or malformed known tool fields raise nonretryable output_projection_error; they cannot become final zero usage or empty executable arguments. Native envelopes retain opaque state; portable delivery explicitly refuses unsupported projections. Cohere v2 and Ollama also qualify native physical counts: Cohere billed units are not token totals, and absent cache fields remain unavailable. See buffered qualification.

Canonical streams may emit accounting-only usage events before content or after a numeric usage snapshot. When usage.completeness is "unavailable" and a valid cache_read_observation is present, merge that metadata without adding its counters or replacing the last numeric snapshot/completeness. It is not a second final usage verdict. These events preserve evidence for consumers that stop reading after content; transparent and translated provider wire responses are unchanged.

provider_spec() exposes stable Rust-owned wire facts (canonical slug, aliases, base URL, and model endpoint routing). Static and per-call headers cannot override credentials or other transport-owned framing. Sandhi validates typed request invariants before HTTP; callers still own model selection and policy.

Custom / unknown providers (host escape hatch)

# (a) register a host parser callback for a provider Sandhi doesn't know:
gw.register_parser("myprovider", lambda body: {"tokens_in": 30, "tokens_out": 12,
                                               "cache_creation_tokens": 0, "cache_read_tokens": 0})
gw.meter("vk_alice", "myprovider", "model", response_json)   # uses your callback

# (b) or skip parsing and pass counts directly:
gw.meter_tokens("vk_alice", "myprovider", "model", tokens_in=30, tokens_out=12)

meter() parses the usage at the source (the same cache-split logic as the reverse proxy), attributes it to the virtual key's subject/group, records the budget, emits the neutral usage event (matching usage-event.v1.schema.json), and returns it for local display. Unknown key → KeyError; bad JSON → ValueError.

Usage snapshots (in-process aggregation)

import json

rows = json.loads(gw.usage_snapshot_json("subject"))   # busiest subject first
rows[0]["billable_tokens"]                             # the quantity budgets enforce on
json.loads(gw.usage_snapshot_json("total"))[0]         # one grand-total row
json.loads(gw.usage_snapshot_json("session", 256))     # bound distinct keys to 256

Folds the events recorded so far into usage-aggregate.v1 rows for one dimension — subject (user), group, provider, model, key (virtual_key), session, or total — using the same fold the reverse proxy, the sandhi CLI, and the dashboard read. Neutral units only, never dollars. The optional second argument caps distinct keys (default 1024); everything past it folds into a single "(overflow)" row, so a long-lived process loses per-key detail but never the sum. Unknown dimension → ValueError.

Apache-2.0. See the main README and ADR-0001.

Connect the binding to a Sandhi gateway

Set peer_role="sandhi_gateway_v1" and choose the client protocol explicitly. The gateway selects and authorizes its backend separately; do not copy a backend endpoint_profile or Codex credential/account configuration onto this handle.

provider = runtime.provider(
    "agent-client", "logical-model", virtual_key,
    base_url="https://gateway.example/v1",
    protocol="chat_completions",
    peer_role="sandhi_gateway_v1",
    max_retries=0,
)

Use the root base for Messages, /v1 for Chat/Responses and /v1beta for Gemini. The gateway requires HTTPS or loopback HTTP and Bearer authentication. Typed cache_intent is forwarded for one server-side policy compilation; the client needs no selected-backend capability configuration. Unsupported server policy still refuses before dispatch. Native/portable fidelity checks remain active.

The explicit peer validates the server's counts-convention header before decoding; metadata cannot activate Codex transport or grant backend authority. Its observed wire counts can differ from original source categories after translation, notably Gemini cache writes and inclusive reasoning output. Consult gateway source evidence and receipts for accounting. See the gateway peer contract for protocol bases, conventions, boundaries and synthetic qualification.

Testing the binding

Use an isolated virtual environment with the shared test requirements before running the suite. The asynchronous provider tests require pytest-asyncio; pytest alone cannot execute them.

python -m pip install -r bindings/python/requirements-test.txt
python -m pytest bindings/python/tests/ -q

The CI wheel, ARM interpreter and coverage paths use this same dependency file.

Metadata

Release files for sandhi-gateway 0.23.0

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

Built distributions (wheels)

Table of built distributions (wheels) for sandhi-gateway 0.23.0
File Actions
sandhi_gateway-0.23.0-cp311-abi3-win_amd64.whl CPython 3.11 abi3 Windows x86-64 Details for sandhi_gateway-0.23.0-cp311-abi3-win_amd64.whl
sandhi_gateway-0.23.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl CPython 3.11 abi3 Linux glibc 2.17+ x86-64 Details for sandhi_gateway-0.23.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
sandhi_gateway-0.23.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl CPython 3.11 abi3 Linux glibc 2.17+ ARM64 Details for sandhi_gateway-0.23.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
sandhi_gateway-0.23.0-cp311-abi3-macosx_11_0_arm64.whl CPython 3.11 abi3 macOS 11.0+ ARM64 Details for sandhi_gateway-0.23.0-cp311-abi3-macosx_11_0_arm64.whl

Total release size: 14.6 MB

Release files / sandhi_gateway-0.23.0-cp311-abi3-win_amd64.whl

Download URL sandhi_gateway-0.23.0-cp311-abi3-win_amd64.whl
Size 3.4 MB
Tags CPython 3.11 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
fdcb7af0ce00202ffb92f069da5dff7a6ff1ba3f5686ab8a4f5a6b272280f0f7
BLAKE2b-256 checksum
How to use checksums
00c0fd74177e7a7a13c1d84d457ada9603f93b50ec56f9e2c75ecb74edb8ca36
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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 Nov 21, 2026.

Transparency log

Release files / sandhi_gateway-0.23.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl

Download URL sandhi_gateway-0.23.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Size 3.8 MB
Tags CPython 3.11 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
a153301c064cb0c7467b0c9c4dd85e19094967b23b2c35d7ebbda4456d8f9ec0
BLAKE2b-256 checksum
How to use checksums
bacbb458239fb8505ddcab5cdc3a1a6c9a11ea5022b8032aadbaa8b61a2e8e80
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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 Nov 21, 2026.

Transparency log

Release files / sandhi_gateway-0.23.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl

Download URL sandhi_gateway-0.23.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
Size 3.9 MB
Tags CPython 3.11 Linux glibc 2.17+ ARM64 abi3
SHA-256 checksum
How to use checksums
9f48d762e12135d3f9df4c5b9677291269f76e70bbafbc1c50f656043f277695
BLAKE2b-256 checksum
How to use checksums
3d7b9a4c9ba83f8427590be3803263c25cc231bf9befff01f866c4b19c881dfe
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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 Nov 21, 2026.

Transparency log

Release files / sandhi_gateway-0.23.0-cp311-abi3-macosx_11_0_arm64.whl

Download URL sandhi_gateway-0.23.0-cp311-abi3-macosx_11_0_arm64.whl
Size 3.5 MB
Tags CPython 3.11 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
f2ed96b4394f49c0194df234099542a2c72da5ae377b8eae98262a9b8510b763
BLAKE2b-256 checksum
How to use checksums
a47c647ce238c2110f4120e2efd82ede811928938ba2822c5b8776ac972b673e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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 Nov 21, 2026.

Transparency log

Security for sandhi-gateway 0.23.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.

Full provenance

All 4 files in this release have been uploaded with provenance metadata.

Select from 4 files

Attestation for sandhi_gateway-0.23.0-cp311-abi3-win_amd64.whl

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 Nov 21, 2026.

Transparency log

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.

Release history Release notifications | RSS feed

This release

0.23.0 This release

4 release files Full provenance

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