Metadata-Version: 2.4
Name: tokentifyai-usagemeter
Version: 0.3.4
Summary: Out-of-band AI API usage metering SDK
Author: Tokentify
License-Expression: MIT
Project-URL: Homepage, https://github.com/tokentifyai/tokentify-sdk-python
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.8
Description-Content-Type: text/markdown
Requires-Dist: httpx>=0.24.0
Requires-Dist: requests>=2.28.0
Requires-Dist: python-dotenv>=1.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"

# Tokentify UsageMeter (Python)

Out-of-band AI API usage metering for Python. After setup, use **httpx** for provider calls; the SDK captures usage automatically.

## Install

```bash
pip install tokentifyai-usagemeter
```

Optional virtual environment:

```bash
python3 -m venv .venv
source .venv/bin/activate   # Windows: .venv\Scripts\activate
pip install tokentifyai-usagemeter
```

## Setup

### 1. Environment (API key is global)

Copy `.env.example` to `.env`. The **API key lives only in `.env`** (or your deployment environment)—never in `init()` code.

```bash
cp .env.example .env
```

```bash
# .env — required
USAGEMETER_API_KEY=your_ingest_api_key
USAGEMETER_BUCKET=your_bucket_name
```

### 2. Initialize

```python
import os
import tokentifyai_usagemeter as um

# USAGEMETER_API_KEY from .env; USAGEMETER_BUCKET from argument
um.load_env()
um.setup(os.environ["USAGEMETER_BUCKET"])

# USAGEMETER_API_KEY and USAGEMETER_BUCKET both from .env
um.setup()

# Production (skip health checks after first successful setup)
um.load_env()
um.init(
    os.environ["USAGEMETER_BUCKET"],
    verify_connection=False,
    verify_api_key=False,
)
```

| Function | When to use |
|----------|-------------|
| `setup()` / `setup(USAGEMETER_BUCKET value)` | First run; verifies collector + `USAGEMETER_API_KEY` from `.env` |
| `init()` / `init(USAGEMETER_BUCKET value)` | Same; control `verify_connection` / `verify_api_key` |

**Init parameters** (API key is not accepted):

| Parameter | Source |
|-----------|--------|
| `bucket` | Argument (value of `USAGEMETER_BUCKET`) or `USAGEMETER_BUCKET` in `.env` |
| `app_name` | Argument or `USAGEMETER_APP_NAME` in `.env` |
| `environment` | Argument or `USAGEMETER_ENVIRONMENT` in `.env` (default `production`) |
| `load_env_file` | Default `True` — loads `.env` before reading env vars |
| `verify_connection` | Default `False` (`True` in `setup`) |
| `verify_api_key` | Default `True` |

```python
# Not supported — will raise TypeError:
# um.init(os.environ["USAGEMETER_BUCKET"], api_key="secret")
```

Call `init()` / `setup()` **before** creating httpx clients.

## Agent tool tracking (v0.3.4)

After your app executes a tool (any provider / agent framework), call
`track_tool()` once. See **[INTEGRATION.md](./INTEGRATION.md)** for a full loop
example.

Provider APIs expose tool-call data in different places (response content vs
client-side MCP loops; never in billing `usage`). See the
[provider research matrix](https://github.com/infinistackai/tokentify-backend/blob/main/docs/AfterDemo/04-tool-usage-tracking.md#provider-research--where-tool-call-data-lives)
before adding auto-capture.

```python
import tokentifyai_usagemeter as um

um.setup()
um.track_tool(
    trace_id="tr_abc",
    span_id="sp_1",
    tool_name="get_weather",
    tool_input={"city": "Paris"},
    tool_output={"temp_c": 22},
    status="success",
    duration_ms=42,
)
```

## Speech & audio APIs (v0.3.0)

After `setup()`, httpx calls to OpenAI speech endpoints are metered automatically:

| Endpoint | Billable unit | Source |
|----------|---------------|--------|
| `/v1/audio/transcriptions` | seconds | `usage.seconds` in JSON response |
| `/v1/audio/translations` | seconds | same as transcriptions |
| `/v1/audio/speech` | characters | `len(request.input)` |

Create buckets with **tracking mode: custom** and set rates in the Tokentify dashboard.
The SDK sends raw billable quantities in event `metadata` (e.g. `audio_seconds`,
`input_characters`, `total_tokens`) — the collector discovers fields and computes
`cost_usd` server-side. No integrator field-key alignment is required for standard
token and speech signals.

```python
import tokentifyai_usagemeter as um

um.setup()
# Whisper via httpx → auto-emits speech event to speech-to-text bucket

# Manual / non-httpx:
usage = um.track_speech(
    provider="openai",
    model="whisper-1",
    kind="stt",
    billable_unit="seconds",
    billable_quantity=12.5,
    endpoint="audio/transcriptions",
)

# Flat per-request pricing (api_request):
um.track_speech(
    provider="openai",
    model="whisper-1",
    kind="stt",
    billable_unit="request",
    endpoint="audio/transcriptions",
)
```

## Token breakdown (v0.2.0)

The SDK extracts **input**, **output**, **cache read**, and **cache write** tokens
from provider responses. Counts are mirrored into event `metadata` for custom-metrics
field discovery and feed weighted token pricing on the Tokentify collector.

### Automatic (httpx hook)

When you use httpx after `setup()`, usage is captured automatically — including
Anthropic cache fields and OpenAI `prompt_tokens_details.cached_tokens`.

### Manual / out-of-band

Use `track_from_response()` when your app calls the provider directly:

```python
import httpx
import tokentifyai_usagemeter as um

um.setup()

response = httpx.post(
    "https://api.anthropic.com/v1/messages",
    json={"model": "claude-haiku-4-5-20251001", "messages": [...]},
    headers={"x-api-key": "...", "anthropic-version": "2023-06-01"},
)

usage = um.track_from_response(
    {
        "provider": "anthropic",
        "model": "claude-haiku-4-5-20251001",
        "endpoint": "messages",
        "http_status": response.status_code,
        "status": "success" if response.is_success else "error",
    },
    response.text,
)

# Return breakdown to your frontend
return {"reply": assistant_text, "usage": usage.to_dict()}
```

Or pass explicit counts with `track_llm()`:

```python
usage = um.track_llm(
    provider="anthropic",
    model="claude-haiku-4.5",
    input_tokens=1000,
    output_tokens=200,
    cache_read_tokens=500,
    cache_write_tokens=80,
)
```

### `TokenUsage` fields

| Field | Ingest key | Source (Anthropic) | Source (OpenAI) |
|-------|------------|----------------------|-------------------|
| `input_tokens` | `input_tokens` | `usage.input_tokens` | `usage.prompt_tokens` |
| `output_tokens` | `output_tokens` | `usage.output_tokens` | `usage.completion_tokens` |
| `cache_read_tokens` | `cache_read_tokens` | `usage.cache_read_input_tokens` | `usage.prompt_tokens_details.cached_tokens` |
| `cache_write_tokens` | `cache_write_tokens` | `usage.cache_creation_input_tokens` | — |

Vendor alias keys (`prompt_tokens`, `cache_read_input_tokens`, etc.) are accepted
on `track_llm()` and override parsed values on `track_from_response()`.

### 3. Launch (v0.2.0)

`.env` (`USAGEMETER_API_KEY` + `USAGEMETER_BUCKET`):

```bash
USAGEMETER_API_KEY=your_ingest_api_key
USAGEMETER_BUCKET=your_bucket_name
```

`app.py`:

```python
import httpx
import tokentifyai_usagemeter as um

um.setup()  # loads .env; reads USAGEMETER_API_KEY and USAGEMETER_BUCKET

client = httpx.Client()
response = client.post(
    "https://api.openai.com/v1/chat/completions",
    json={"model": "gpt-4o", "messages": [{"role": "user", "content": "hi"}]},
    headers={"Authorization": "Bearer YOUR_OPENAI_KEY"},
)
print(response.status_code)

um.flush()
```

```bash
python app.py
```

### 4. Develop from this repo

```bash
cd tokentify-sdk-python
python -m venv .venv && source .venv/bin/activate
pip install -e .
cp .env.example .env   # set USAGEMETER_API_KEY and USAGEMETER_BUCKET
python -c "import tokentifyai_usagemeter as um; um.setup(); print(um.is_initialized())"
```
