Metadata-Version: 2.5
Name: meterspw-sdk
Version: 0.3.0
Summary: Meter-SPW-v1.0 — deterministic LLM routing with metered savings (BYOK)
Project-URL: Homepage, https://spw.scitechsolutions.ai
Author-email: "S&T Integrated Solutions, LLC" <support@scitechsolutions.ai>
License: MIT License
        
        Copyright (c) 2026 S&T Integrated Solutions, LLC
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
        https://scitechsolutions.ai
License-File: LICENSE
Keywords: anthropic,byok,cost,llm,openai,router
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Typing :: Typed
Requires-Python: >=3.10
Provides-Extra: async
Requires-Dist: httpx>=0.24; extra == 'async'
Provides-Extra: dev
Requires-Dist: httpx>=0.24; extra == 'dev'
Requires-Dist: mypy>=1.8; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest>=7; extra == 'dev'
Requires-Dist: ruff>=0.5; extra == 'dev'
Description-Content-Type: text/markdown

# meterspw-sdk

Managed Keys accounts require `Idempotency-Key` on relay requests. This SDK
sends a fresh key per method call and preserves it across automatic retries.
A duplicate request on an account with a funding policy returns HTTP 409 with
its original authorization ID (`AlreadyProcessed` here); it does not replay the
answer or call the vendor again. Do not blindly repeat a failed method call: a
new call gets a new key and can incur a charge — and an account WITHOUT a
funding policy is not protected by the key at all, which is why this SDK never
retries once a request may have reached the router (see Errors).
BYOK cost protection retains optimization during bounded grace and returns
402 when grace expires. Legacy accounts retain their existing behavior.
Protected funding currently rejects binary attachments.


Python client for **Meter-SPW** — deterministic LLM routing with metered savings.

Use BYOK or an offered Managed Keys policy. Meter-SPW routes each prompt to the cheapest
model that can answer it, caches what repeats, and meters what it saved.

```bash
pip install meterspw-sdk
```

Zero runtime dependencies — the default transport is `urllib` from the standard
library.

## Use

```python
from meterspw import MeterSpwClient

with MeterSpwClient() as spw:            # key from ROUTER_API_KEY
    out = spw.relay(
        "Summarise this contract in three bullets.",
        model="claude-sonnet-5",
        max_tokens=2000,
    )
    print(out.content)
    print(out.model_used)                # what ACTUALLY answered
    print(out.savings.usd)               # what that saved you — priced against your model at YOUR effort
```

`model` is what you want; `model_used` is what answered. The difference is the
product.

### Attachments

```python
out = spw.relay_multipart(
    "Summarise the attached report.",
    model="claude-sonnet-5",
    max_tokens=2000,
    files=["report.pdf"],
    card="cs-cheapest-a",     # optional — `system`, `temperature`, `effort` and `card` as on relay()
)
```

A path is read from **your** process's filesystem. Pass a user's upload as
`(filename, bytes)` — never a string the user supplied as a path.

### Know where you stand

```python
b = spw.balance()
print(b.usd, b.accrued_micro_usd, b.remaining_usd)
if b.passthrough:
    print("credit exhausted — calls still work, but nothing is being routed")
```

**What happens at zero credit depends on your funding policy.** Read the
figures, not the sentence you remember:

- **No funding policy on the account** (the legacy state): the router serves
  every call in pass-through mode — your model, no routing, no cache, no
  savings fee — and `passthrough` is `True`. Nothing fails, which is exactly
  why it is easy to miss.
- **BYOK with a funding policy:** your providers bill your keys directly;
  Meter's fees come from your credit. Below zero the router keeps optimizing
  for a bounded grace window (the policy's grace seconds and grace limit,
  a limited number of episodes); when it expires or the limit is reached a
  call is refused with `402` (`grace_exhausted`) until you top up.
  `passthrough` is always `False` here.
- **Managed:** vendor usage is paid from your credit; below zero a call is
  refused with `402` (`insufficient_credit`). `passthrough` is `False`.

`remaining_usd` is what you should plan against in every case.

**Three numbers, because two books.** `usd` is the ledger. `accrued` is this
period's fees as the monthly close will settle them — capped and floored, not
a sum of per-request accruals — and they have not been taken yet. `remaining`
is what you should plan against.

### Your receipts

```python
rows = spw.verdicts(window="7d", q="haiku")      # the last 7 days, searched
```

`window` is one of `30m 1h 6h 12h 24h 7d 4w 12m` (a period ending now); `q`
matches the decision, the requested model and the served model. The router
applies both, so the same two values count and export exactly these rows:

```bash
curl -H "Authorization: Bearer $ROUTER_API_KEY" \
  "https://spw.scitechsolutions.ai/v1/verdicts/count?window=7d&q=haiku"
curl -H "Authorization: Bearer $ROUTER_API_KEY" -o verdicts-7d.csv \
  "https://spw.scitechsolutions.ai/v1/verdicts.csv?window=7d&q=haiku"
```

The export is refused, with the count, when more than 200 000 rows match —
narrow the window or the search.

### Long requests

A proxy between you and the router closes a connection that stays silent for
about 100 seconds, and the router is silent until the verified answer exists.
So `relay()` asks for keep-alive delivery: the router answers within a second,
keeps the line warm every 15 seconds while the model works, and delivers the
whole answer at the end — the same result, nothing to change on your side.

`timeout` bounds **silence** on the line, not the whole call. A long answer is
bounded by the router's own request limit (the operator's
`ROUTER_REQUEST_TIMEOUT_SECS`), not by this number.

Over raw HTTP, send the header yourself and read the last `data:` line:

```bash
curl -N -X POST https://spw.scitechsolutions.ai/v1/relay \
  -H "Authorization: Bearer $ROUTER_API_KEY" \
  -H "Accept: text/event-stream" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Summarise this contract in three bullets.", "model": "claude-sonnet-5", "max_tokens": 2000}'
# -N is optional: curl prints each line as it arrives instead of all at the end.
```

```
: keep-alive          ← every 15 s while the model works
event: result
data: {"decision": "relayed", "model_used": "…", "content": "…", "verdict_id": "…", "latency_ms": 1840, …}
```

An `event: error` line with `{"status": 502, "error": "…"}` takes the place
of `result` if the router fails late. `/v1/relay-multipart` takes the same
header. Without it the reply is one JSON body — and a call longer than about
100 seconds dies at the proxy.

## Using OpenAI-compatible clients

The router also speaks the OpenAI Chat Completions wire, so an OpenAI SDK or
an agent framework needs only the base URL and your Meter API key:

```python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["ROUTER_API_KEY"],          # your Meter key — never a literal in source
    base_url="https://spw.scitechsolutions.ai/v1",
    max_retries=0,                                 # see below: a retry here is a second vendor call
)
r = client.chat.completions.create(
    model="claude-haiku-4-5",
    messages=[{"role": "user", "content": "What is 2 + 2?"}],
    max_tokens=64,
    extra_body={"meter": {"card": "cs-cheapest-a"}},   # optional: a catalog card for this call
)
print(r.choices[0].message.content, r.model)          # r.model is the model that answered
```

**Set `max_retries=0`.** The OpenAI SDK retries on connection errors, timeouts,
408/409/429 and every 5xx — and sends no `Idempotency-Key`. On this door a
request that reached the router and failed late (a 500 after the vendor
answered, a timeout) is re-sent as a NEW request, which is a second vendor call
on your key with no duplicate check. Keep its retries off and repeat a call
only after checking your receipts; or send a key yourself per logical call —
`extra_headers={"Idempotency-Key": my_uuid}` — which the router honours on
accounts with a funding policy.

What it serves today: `system`/`developer` instructions, conversation history
resent per request (nothing is stored), function tools (`tools`,
`tool_choice`, the assistant `tool_calls` / `tool` turns of the loop) on the
model families measured to take them, `GET /v1/models`, OpenAI's error
envelope. It is BYOK only. Streaming is off on the router by the owner's
decision (safety over a fast first token: an answer is checked, then sent),
so `stream: true` is refused with a `400`; if it is ever switched on, a
stream is heartbeats then `chat.completion.chunk` frames delivered after the
answer is complete, never token by token. Every unserved
parameter is refused by name, never silently ignored. The response carries
`x-verdict-id` (your dispute handle) and `x-meter-requested-model`.

## Errors

| Exception | When | Retry? |
|---|---|---|
| `AuthError` | 401/403 — key wrong or revoked | no |
| `RateLimited` | 429 | yes, honours `Retry-After` |
| `UploadCapacityFull` | 503 — shed before any vendor call | yes, honours `Retry-After` |
| `Exhausted` | 502 — the router spent every lever | **no** |
| `AlreadyProcessed` | 409 — this call's `Idempotency-Key` was seen before; nothing ran again | **no** — the first attempt is on your receipts |
| `ApiError` (any other 5xx: 500, 504, …) | the router answered a request it ran | **no** — the call may have run |
| `TransportError` | no usable answer | only when the request provably never left: a refused connection, a DNS miss, a TLS handshake failure. A timeout, a reset or a cut after it was sent is **not** retried — the call may have run |

**A retry is a second vendor call unless the first one never happened.** The
router honours the `Idempotency-Key` only for accounts with a funding policy,
so a request that reached it and failed late — a 500 after the vendor
answered, a 504 while the vendor call may still complete, a read timeout — is
surfaced once, and its message says the call may have run. Check
`verdicts()` before repeating it; a repeat is a new call with a new key.

`Exhausted` is not retryable on purpose. The router already climbed the model
ladder, repaired and re-called before answering — each of those attempts billed
**your** provider key. Asking again spends the same levers for the same failure.
The message names what it tried.

Retries use exponential backoff with deterministic jitter and a wall-clock
budget, and never extend past your own deadline. Configure with `RetryPolicy`.

## Configuration

| | |
|---|---|
| `ROUTER_API_KEY` | your Meter-SPW key (or pass `api_key=`) |
| `ROUTER_BASE_URL` | defaults to `https://spw.scitechsolutions.ai` |

The SDK never sees a provider key. Those are stored once in the dashboard and
used by the router on your behalf — the only credential here spends credit, not
inference.

## Support

support@scitechsolutions.ai — quote `RelayResult.verdict_id` or the
`request_id` from an error and we can find the exact call.

---

© S&T Integrated Solutions, LLC — MIT licensed.
