Sandhi — the metering layer for AI agents (Python binding of the Rust core). The bare name `sandhi` on PyPI is an unrelated Sanskrit-linguistics library.
Project description
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
sandhion PyPI is an unrelated Sanskrit-linguistics library; this binding is published assandhi-gateway. The crate and GitHub repo aresandhi.
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_*}
Typed persistent provider runtime (0.1.2+)
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 = {"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
The JSON bridge is ABI-stable typed v1 data, not provider-native JSON. The handle retains its HTTP
pool, circuit breaker, retry policy, and timeouts. Invalid documents fail before network I/O;
runtime failures use the serialized ProviderErrorV1 shape in the exception message.
runtime.provider() resolves a known endpoint from Sandhi's catalog;
runtime.openai_compat() is the explicit custom-endpoint escape hatch.
Legacy provider-native transport (0.1.2+)
Sandhi also owns the provider wire layer: endpoint routing, headers, HTTP/SSE, resilience, wire errors, and neutral usage extraction. Callers keep model policy, prompt/tool assembly, and their framework-facing response types.
import asyncio
import json
import sandhi_gateway as sg
async def main():
api_key = "..."
spec = sg.provider_spec("kimi", model="kimi-k3")
body = {"model": "kimi-k3", "messages": [{"role": "user", "content": "hello"}]}
result = await sg.complete(
spec["slug"], "kimi-k3", spec["base_url"], api_key, json.dumps(body),
max_retries=3,
)
# result = {"status": ..., "body": raw_json, "usage": neutral_cache_split}
openrouter_model = "meta-llama/llama-3.3-70b-instruct"
openrouter_body = {**body, "model": openrouter_model}
async for item in sg.stream(
"openrouter", openrouter_model, sg.provider_spec("openrouter")["base_url"], api_key,
json.dumps(openrouter_body), max_retries=3,
headers_json=json.dumps({"HTTP-Referer": "https://example.app", "X-Title": "My App"}),
):
print(item["data"])
# The terminal item carries finalized neutral usage.
asyncio.run(main())
provider_spec() exposes stable Rust-owned wire facts (canonical slug, aliases,
base URL, and model endpoint routing), not a model/capability catalog. Custom
Authorization, Content-Type, and Host values are ignored so callers cannot
override transport-owned headers.
The OpenAI-compatible transport accepts the Chat Completions roles developer,
system, user, assistant, tool, and legacy function. A tool result must
carry its tool_call_id; a legacy function result must carry name. Sandhi
validates these wire invariants before HTTP but deliberately does not rewrite roles:
whether a specific compatible model accepts developer, for example, is caller-owned
model 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.
Apache-2.0. See the main README and ADR-0001.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distributions
Built Distributions
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file sandhi_gateway-0.1.3-cp311-abi3-win_amd64.whl.
File metadata
- Download URL: sandhi_gateway-0.1.3-cp311-abi3-win_amd64.whl
- Upload date:
- Size: 2.3 MB
- Tags: CPython 3.11+, Windows x86-64
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d1228a5cbe27220c18536051c71d4d82a448b88ad10b319702404c9884002028
|
|
| MD5 |
937c579be8534cae3b09283d97a16827
|
|
| BLAKE2b-256 |
bf139da34d5431b3eca0bce756b3c992c0e14f56d2bf184c6bab1f71449bd6a9
|
Provenance
The following attestation bundles were made for sandhi_gateway-0.1.3-cp311-abi3-win_amd64.whl:
Publisher:
release.yml on anvai-labs/sandhi
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
sandhi_gateway-0.1.3-cp311-abi3-win_amd64.whl -
Subject digest:
d1228a5cbe27220c18536051c71d4d82a448b88ad10b319702404c9884002028 - Sigstore transparency entry: 2255234105
- Sigstore integration time:
-
Permalink:
anvai-labs/sandhi@4ace26f3b5af5e90b11301c8077e94f7eab66a1e -
Branch / Tag:
refs/tags/v0.1.3 - Owner: https://github.com/anvai-labs
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@4ace26f3b5af5e90b11301c8077e94f7eab66a1e -
Trigger Event:
push
-
Statement type:
File details
Details for the file sandhi_gateway-0.1.3-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.
File metadata
- Download URL: sandhi_gateway-0.1.3-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
- Upload date:
- Size: 2.7 MB
- Tags: CPython 3.11+, manylinux: glibc 2.17+ x86-64
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1daa862f5e65c6fb9ba8def4b0d8ab0a399f15c8e79966f69ef09efc9658a3cb
|
|
| MD5 |
64d9cba92b010602cb6ebca14d590b5b
|
|
| BLAKE2b-256 |
12ea94ebc4f7f3744d4bacd17dad7d632f4635aab686cff09a2d8851f62b71d5
|
Provenance
The following attestation bundles were made for sandhi_gateway-0.1.3-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl:
Publisher:
release.yml on anvai-labs/sandhi
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
sandhi_gateway-0.1.3-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl -
Subject digest:
1daa862f5e65c6fb9ba8def4b0d8ab0a399f15c8e79966f69ef09efc9658a3cb - Sigstore transparency entry: 2255234099
- Sigstore integration time:
-
Permalink:
anvai-labs/sandhi@4ace26f3b5af5e90b11301c8077e94f7eab66a1e -
Branch / Tag:
refs/tags/v0.1.3 - Owner: https://github.com/anvai-labs
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@4ace26f3b5af5e90b11301c8077e94f7eab66a1e -
Trigger Event:
push
-
Statement type:
File details
Details for the file sandhi_gateway-0.1.3-cp311-abi3-macosx_11_0_arm64.whl.
File metadata
- Download URL: sandhi_gateway-0.1.3-cp311-abi3-macosx_11_0_arm64.whl
- Upload date:
- Size: 2.4 MB
- Tags: CPython 3.11+, macOS 11.0+ ARM64
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
73f56d492eeae267043f3dfa4cb7eb4405e9dd100d74c04ba4d3e8e60f639345
|
|
| MD5 |
09d2cbe5eb43828e3ec9c871ecdde26e
|
|
| BLAKE2b-256 |
b16fb2c6a4b480087fdbe50096dac5def946b640bd601e89f247f4c51d2eefe8
|
Provenance
The following attestation bundles were made for sandhi_gateway-0.1.3-cp311-abi3-macosx_11_0_arm64.whl:
Publisher:
release.yml on anvai-labs/sandhi
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
sandhi_gateway-0.1.3-cp311-abi3-macosx_11_0_arm64.whl -
Subject digest:
73f56d492eeae267043f3dfa4cb7eb4405e9dd100d74c04ba4d3e8e60f639345 - Sigstore transparency entry: 2255234102
- Sigstore integration time:
-
Permalink:
anvai-labs/sandhi@4ace26f3b5af5e90b11301c8077e94f7eab66a1e -
Branch / Tag:
refs/tags/v0.1.3 - Owner: https://github.com/anvai-labs
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@4ace26f3b5af5e90b11301c8077e94f7eab66a1e -
Trigger Event:
push
-
Statement type: