Nivara — Python Metrics Client
==============================

Lightweight client to record LLM/AI usage metrics to the Nivara Metrics API.
Defaults to background delivery with safe timeouts and optional retries; also
supports a simple synchronous call for one‑off usage.

Environment
-----------

```
export NIVARA_API_KEY="ak_live_..."              # required
export NIVARA_BASE_URL="https://api.getnivara.com"   # optional (default)
```

Quickstart
----------

Install locally (editable) once:

```
python3 -m pip install -e .
```

Configure (optional; sensible defaults are used):

```
import nivara

nivara.configure(
  timeout=2.0,
  retries=2,
  mode="background",   # or "sync"
  queue_size=10000,
  debug=False,
)
```

Emit a metric (background):

```
import nivara

nivara.emit(
  metric="llm.request",
  user_identifier="end_user_42",
  input_tokens=512,
  output_tokens=238,
  cached_tokens=64,
  reasoning_tokens=0,
)
```

Notes
-----

- Sends only the supported fields; unknown values are omitted.
- Accepts `ts` as RFC3339 string or `datetime` (converted to `Z`).
- Returns `{"status":"ok","http_status":201}` on success; error responses include `error` and `http_status` when available.

Synchronous one‑shot record
---------------------------

```
from datetime import datetime, timezone
import nivara

nivara.record(
  metric="llm.request",
  ts=datetime.now(timezone.utc),   # optional; server uses now() if omitted
  input_tokens=100,
  output_tokens=20,
)
```

Helpers
-------

- `nivara.from_openai(response, user_identifier=None)` — map OpenAI usage to emit kwargs:

```
resp = client.responses.create(model="gpt-4o-mini", input="hi")
nivara.emit(metric="llm.request", **nivara.from_openai(resp))
```

Lifecycle
---------

- `nivara.flush(timeout=5.0)` — wait for the background queue to drain.
- `nivara.close()` — stop the worker.
- `nivara.stats()` — returns `{ queued, sent, failed, last_error }`.

Example script
--------------

Run a minimal OpenAI demo and record usage:

```
export OPENAI_API_KEY=sk-...
export NIVARA_API_KEY=ak_live_...
python3 -m pip install -e .
python3 examples/openai_demo.py --prompt "hello there"
```

More docs
---------

- docs/index.md — entry point
- docs/getting-started.md — installation and quickstart
- docs/concepts.md — background vs sync, retries, sampling
- docs/api.md — full API reference
- docs/examples.md — copy/paste snippets
- docs/faq.md — common issues

License
-------

Proprietary to Nivara Tech (adjust as needed).
