Metadata-Version: 2.5
Name: prinvox
Version: 0.1.0
Summary: Official PrinVox Margin Guard SDK: report AI usage events (OpenAI, Anthropic, Google Gemini) from your Python server.
Project-URL: Homepage, https://www.prinvox.com
Project-URL: Documentation, https://www.prinvox.com/en/docs
License: MIT
License-File: LICENSE
Keywords: ai,anthropic,cost,gemini,gross-margin,llm,margin-guard,openai,prinvox,usage
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.27
Description-Content-Type: text/markdown

# prinvox (Python SDK)

Official Python SDK for **PrinVox Margin Guard**. It reports your AI usage (OpenAI, Anthropic, Google Gemini) to PrinVox so you see revenue, AI cost and gross margin per customer, plan and feature.

> **Version 0.1.0.** The SDK is a thin wrapper over the PrinVox ingestion HTTP API, documented at [prinvox.com/en/docs](https://www.prinvox.com/en/docs), which you can also call directly.

```bash
pip install prinvox
```

Python **3.10+**. One dependency: [`httpx`](https://www.python-httpx.org/). Synchronous API: `track` blocks (network I/O, retries), so never call it directly on an asyncio event loop — use a worker thread or a background task (see FastAPI below). An async client is a planned follow-up.

## What it needs — and what it never needs

The SDK uses **one secret: your PrinVox ingestion key** (`mgik_…`, created under *Margin Guard → Connections*, one per provider). It sends usage **metadata** (model, token counts, your customer and feature labels).

PrinVox does **not** need, and the SDK never touches, your OpenAI, Anthropic or Google (Gemini) API key. You keep calling those providers with their own SDKs and then report what they told you. Prices live on the server: the SDK contains none.

**Server-side only.** Never put `PRINVOX_INGESTION_KEY` in browser code, a frontend bundle or a mobile app.

## Quick start

```python
import os
from prinvox import PrinVox

client = PrinVox(api_key=os.environ["PRINVOX_INGESTION_KEY"])

result = client.track(
    provider="openai",
    model="gpt-4.1",
    event_id=response.id,        # idempotency key, see below
    feature_key="assistant",
    customer_ref="cus_123",
    input_tokens=1000,
    output_tokens=500,
)
print(result.status)  # "processed" or "duplicate"
```

`track` takes keyword arguments only, returns a `TrackResult` or raises a [`PrinVoxError`](#errors).

### OpenAI

```python
from openai import OpenAI
from prinvox import PrinVox

openai_client = OpenAI()  # your own key, PrinVox never sees it
prinvox = PrinVox(api_key=os.environ["PRINVOX_INGESTION_KEY_OPENAI"])
MODEL = "gpt-4.1-mini"  # send the alias you requested, not a dated snapshot name

response = openai_client.responses.create(model=MODEL, input="Summarize: ...")

try:
    prinvox.track(
        provider="openai",
        model=MODEL,
        event_id=response.id,
        feature_key="summarize",
        customer_ref=app_customer_id,
        input_tokens=response.usage.input_tokens if response.usage else None,
        output_tokens=response.usage.output_tokens if response.usage else None,
    )
except Exception:
    pass  # telemetry must never break your product (log it if you like)
```

### Anthropic

```python
import anthropic

claude = anthropic.Anthropic()  # your own key
message = claude.messages.create(model="claude-haiku-4-5", max_tokens=512, messages=[{"role": "user", "content": question}])

prinvox.track(  # a PrinVox client created with the ingestion key for Anthropic
    provider="anthropic",
    model="claude-haiku-4-5",
    event_id=message.id,
    feature_key="support-answer",
    customer_ref=app_customer_id,
    input_tokens=message.usage.input_tokens,
    output_tokens=message.usage.output_tokens,
)
```

### Google Gemini

The canonical provider value is `google_gemini` (a bare `google` is refused). Thinking tokens are billed as output, so add them. The 2.5 Flash family bills audio input higher, so say how much of the prompt was audio — `0` for text-only calls. **Without `input_audio_tokens` the cost of those models is stored as UNKNOWN** (never silently priced as text), and the report shows that figure as incomplete.

```python
import uuid
from google import genai

gemini = genai.Client()  # your own key
response = gemini.models.generate_content(model="gemini-2.5-flash", contents=prompt)
u = response.usage_metadata
audio = sum((d.token_count or 0) for d in (u.prompt_tokens_details or []) if str(d.modality).endswith("AUDIO"))

prinvox.track(  # a PrinVox client created with the ingestion key for Google Gemini
    provider="google_gemini",
    model="gemini-2.5-flash",
    event_id=response.response_id or str(uuid.uuid4()),
    feature_key="ai-chat",
    customer_ref=app_customer_id,
    input_tokens=u.prompt_token_count,
    input_audio_tokens=audio,
    output_tokens=(u.candidates_token_count or 0) + (u.thoughts_token_count or 0),
)
```

### FastAPI (server-side)

`track` is synchronous. Run it as a background task so it runs after the response and in a worker thread, never on the event loop.

```python
import os
from fastapi import BackgroundTasks, FastAPI
from prinvox import PrinVox

app = FastAPI()
prinvox = PrinVox(api_key=os.environ["PRINVOX_INGESTION_KEY_OPENAI"])  # read from the server's environment only


def report(response_id: str, customer_id: str, usage) -> None:
    try:
        prinvox.track(
            provider="openai", model="gpt-4.1-mini", event_id=response_id, feature_key="chat", customer_ref=customer_id,
            input_tokens=usage.input_tokens, output_tokens=usage.output_tokens,
        )
    except Exception:
        pass  # never fail the user's request over telemetry


@app.post("/chat")
def chat(prompt: str, customer_id: str, background: BackgroundTasks):
    response = openai_client.responses.create(model="gpt-4.1-mini", input=prompt)
    background.add_task(report, response.id, customer_id, response.usage)
    return {"text": response.output_text}
```

## Event fields

| Argument | Required | Notes |
|---|---|---|
| `provider` | yes | `"openai"`, `"anthropic"`, `"google_gemini"` (other strings are passed through). The server accepts the Gemini aliases `gemini`, `google-ai`, `google_ai`; a bare `google` is refused. |
| `model` | yes | The exact alias you requested. An unpriced model is **stored with an unknown cost**, never an invented price. |
| `event_id` | yes | Unique per provider request. **This is the idempotency key** (sent as `provider_request_id`). |
| `feature_key` | yes | Your name for the AI feature. |
| `input_tokens`, `output_tokens` | no | Omit them if the provider reported no usage — the cost is then unknown, not zero. |
| `input_audio_tokens` | Gemini 2.5 Flash family | A subset of `input_tokens`; `0` if none. |
| `customer_ref` | no | Your own id for the end customer (`external_customer_id`). Without it the cost is *Unattributed*. |
| `stripe_customer_id` | no | The `cus_…` id in your connected Stripe account — the only link between usage and Stripe revenue. |
| `timestamp` | no | A `datetime` (naive means UTC) or an ISO 8601 string. Defaults to now. Reports show the trailing 30 days by default. |

There is no `metadata` field: the ingestion API does not store one.

## Idempotency and retries

`event_id` makes every call safe to repeat: the same `event_id` for the same provider is stored once and answered `duplicate`. The SDK therefore retries **only** transient failures — network errors, timeouts and 500/502/503/504 — up to `max_retries` (default 2, max 5) with bounded, jittered exponential backoff, always re-sending the identical body. It never retries 4xx, and never retries 429 (`Retry-After` is 60 s, far longer than a telemetry call should wait): you get a `PrinVoxRateLimitError` with `retry_after` and can resend later **with the same `event_id`**. `max_retries=0` disables retries.

There is no automatic `event_id`: a random id would defeat idempotency across your own retries. Use the provider's response id.

## Errors

`track` raises `PrinVoxError` or a subclass — never anything carrying your key, the Authorization header or the event body:

| Class | `code` | When |
|---|---|---|
| `PrinVoxValidationError` | `invalid_event`, `invalid_options` | Rejected locally; nothing was sent. |
| `PrinVoxValidationError` | `invalid_request` | The server refused it (400 `invalid_body` / `provider_mismatch`, 413, …). See `api_error`. |
| `PrinVoxAuthenticationError` | `authentication`, `forbidden` | 401 (wrong, missing or replaced key) / 403. |
| `PrinVoxError` | `payment_required` | 402 — the free evaluation ended. |
| `PrinVoxError` | `quota_exceeded` | 429 `trial_event_limit` — the evaluation's event quota is used up. Final: subscribe instead of resending. |
| `PrinVoxRateLimitError` | `rate_limited` | 429 throttle — see `retry_after`; resend later with the same `event_id`. |
| `PrinVoxError` | `server_error` | 5xx after retries. |
| `PrinVoxConnectionError` | `network`, `timeout` | No answer. |
| `PrinVoxError` | `invalid_response` | An answer the SDK cannot interpret (including an unexpected 2xx such as 202/204 from a proxy). The event may be stored; resending the same `event_id` is safe. |

Attributes: `code`, `message`, `status_code`, `api_error`, `retry_after`, `request_id`; `to_dict()` is safe to log.

## Options

```python
PrinVox(
    api_key,                 # required
    base_url=None,           # default https://www.prinvox.com — point it at a Preview environment to test
    timeout=None,            # seconds for connecting and for each read, default 10
    max_retries=2,
    retry_delay=0.25,        # backoff base in seconds
    http_client=None,        # your own httpx.Client (proxies, tests); you keep ownership of it
)
```

`base_url` must be `https` (plain `http` only for `localhost`). To try the SDK without touching production data, use a Preview deployment's URL together with that environment's own ingestion key. The client holds a connection pool: reuse one instance, or use it as a context manager (`with PrinVox(...) as client:`). Its `repr()` redacts the key and it cannot be pickled or copied.

## Development

```bash
python -m venv .venv && . .venv/bin/activate
pip install -e . pytest ruff mypy build
pytest && ruff check . && mypy && python -m build
```

## Versioning

The ingestion API has no version prefix today; the SDK wraps it as it is. New optional fields will be added without breaking existing calls.

## License

The PrinVox SDK is licensed under the MIT License. This license applies to this SDK package only and does not license the PrinVox SaaS platform or other proprietary PrinVox source code.
