Metadata-Version: 2.4
Name: nightswatch-sdk
Version: 0.2.0
Summary: Transparent LLM usage tracking — OpenAI and Anthropic wrappers that send cost and token metrics to Nightswatch.
Author-email: Nightswatch <support@nightswatch.work>
License-Expression: MIT
Project-URL: Homepage, https://nightswatch.work
Project-URL: Documentation, https://nightswatch.work/docs
Keywords: llm,openai,anthropic,observability,cost-tracking,governance
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
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: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Monitoring
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: openai
Requires-Dist: openai>=1.0.0; extra == "openai"
Provides-Extra: anthropic
Requires-Dist: anthropic>=0.25.0; extra == "anthropic"
Provides-Extra: all
Requires-Dist: openai>=1.0.0; extra == "all"
Requires-Dist: anthropic>=0.25.0; extra == "all"
Dynamic: license-file

# nightswatch-sdk

AI usage monitoring for Python. Drop one wrapper around your LLM client — every call is automatically tracked, risk-classified, and auditable.

```bash
pip install nightswatch-sdk
```

---

## Quick start

```python
import nightswatch
import openai

nightswatch.init(
    api_key="nw_your_key_here",
    default_team="engineering",
    default_service="chat-api",
)

client = nightswatch.wrap(openai.OpenAI())

# Use exactly as before — nothing else changes
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Summarise this ticket."}],
)
```

That's it. The SDK fires a usage event in the background after every LLM call with zero added latency.

---

## Installation

```bash
# Core (OpenAI + Anthropic)
pip install nightswatch-sdk

# With OpenAI
pip install "nightswatch-sdk[openai]"

# With Anthropic
pip install "nightswatch-sdk[anthropic]"

# Everything
pip install "nightswatch-sdk[all]"
```

Requires Python ≥ 3.9.

---

## API reference

### `nightswatch.init()`

Call once at application startup, before any `wrap()` calls.

```python
nightswatch.init(
    api_key: str,
    default_team: str = "unknown",
    default_service: str = "unknown",
    base_url: str = "https://api.nightswatch.work",
)
```

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `api_key` | str | Yes | Your `nw_` API key from the dashboard. Empty means no-op mode — see below |
| `default_team` | str | No | Team or product area label added to every event |
| `default_service` | str | No | Microservice or feature name added to every event |
| `base_url` | str | No | Override for self-hosted deployments |
| `user_id` | str | No | Identity on every event. Defaults to `"sdk-user"` |
| `user_id_getter` | callable | No | Resolved per call for request-scoped identity, e.g. `lambda: flask.g.user.id`. Takes precedence over `user_id` |
| `strict` | bool | No | Raise on a missing key instead of running as a no-op |
| `validate` | bool | No | Make one call at startup to confirm the key works, and log the result |

**No-op mode.** If `api_key` is empty the SDK logs one warning and does nothing:
`wrap()` returns your client untouched and no events are sent. A missing
environment variable in staging should not stop your application from booting.
Pass `strict=True` if you would rather fail loudly.

**Per-user analytics.** Every event carries a `user_id`. Set it once with
`user_id=`, resolve it per request with `user_id_getter=`, or override a single
call with `nightswatch_user_id=`:

```python
client.chat.completions.create(
    model="gpt-4o",
    messages=[...],
    nightswatch_user_id=current_user.id,
    nightswatch_team="billing",
    nightswatch_service="invoice-summariser",
    nightswatch_feature="checkout",
)
```

**Configuration is read when you wrap.** `api_key`, `base_url`, team and service
are copied into the wrapper at `wrap()` time, so calling `init()` again does not
change clients you have already wrapped — re-wrap them. `init()` warns if you do
this, so it will not pass silently.

---

### `nightswatch.wrap()`

Wraps an LLM client and returns a drop-in replacement.

```python
wrapped = nightswatch.wrap(client)
```

| Parameter | Type | Description |
|-----------|------|-------------|
| `client` | OpenAI \| Anthropic | The LLM client to instrument |

**Returns** a wrapped client with the same interface as the original. All existing call sites work without modification: anything the SDK does not instrument is forwarded to the real client unchanged.

**What is tracked**

| Call | Tracked |
|------|---------|
| `chat.completions.create` | yes |
| `images.generate` | yes |
| `audio.transcriptions.create`, `audio.speech.create` | yes |
| `messages.create`, `messages.stream` | yes |
| `chat.completions.parse`, `.stream`, `.with_raw_response` | forwarded, no event |
| `responses.create`, `embeddings.create`, `beta.*` | forwarded, no event |
| `messages.count_tokens` | forwarded, no event |

**Streaming is tracked.** `create(stream=True)` has `stream_options={"include_usage": True}`
injected automatically so the usage chunk arrives, and the event is sent when the
stream closes — tokens and cost are real, not zero.

**Asynchronous clients are not supported yet.** `wrap()` raises `TypeError` for
`AsyncOpenAI`, `AsyncAzureOpenAI` and `AsyncAnthropic`. They are refused rather
than wrapped because the synchronous path would record every async call as zero
tokens and zero cost, which is worse than not recording it. Use a synchronous
client, or send events for async calls over the [REST API](#rest-api-no-sdk).

Forwarded calls behave exactly as they would without the wrapper — they simply
do not produce a usage event, so they will not appear in your dashboard or
count against spend. Send those over the [REST API](#rest-api-no-sdk) if you
need them measured.

One known difference from the real client: `isinstance(wrapped, openai.OpenAI)`
is `False`, because the wrapper composes the client rather than subclassing it.
Code that type-checks the client rather than calling it will need the original,
available as `wrapped.unwrapped`.

Raises `RuntimeError` if called before `init()`.

---

## Provider integrations

### OpenAI

```python
import nightswatch, openai

nightswatch.init(api_key="nw_…", default_team="engineering", default_service="summariser")
client = nightswatch.wrap(openai.OpenAI())

# chat completions
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Explain async/await in Python."}],
)

# embeddings — tracked the same way
embedding = client.embeddings.create(
    model="text-embedding-3-small",
    input="Some text to embed",
)
```

### Anthropic

```python
import nightswatch, anthropic

nightswatch.init(api_key="nw_…", default_team="ml-team", default_service="code-review")
client = nightswatch.wrap(anthropic.Anthropic())

response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Review this diff."}],
)
```

---

## What the SDK captures

Every wrapped call automatically records:

| Field | Source |
|-------|--------|
| `provider` | Detected from client class |
| `model` | From the API call arguments |
| `prompt_tokens` | From the API response usage object |
| `completion_tokens` | From the API response usage object |
| `total_tokens` | From the API response usage object |
| `cost_usd` | Computed from token counts using built-in pricing tables |
| `team` | From `default_team` in `init()` |
| `service` | From `default_service` in `init()` |
| `prompt_hash` | SHA-256 of the raw prompt — the raw text never leaves your infra |

---

## PII handling

The SDK hashes prompts with SHA-256 before sending. Raw prompt content never leaves your infrastructure.

On the server side, any `metadata` you attach is scanned for PII patterns (email, SSN, credit card, phone, IP, PAN, Aadhaar) and redacted to `[REDACTED:TYPE]` before the event is stored in the database. The risk classifier runs on the raw text first, then the redacted version is stored.

**How detection works without sending the text.** The SDK scans the prompt in
your own process before hashing it, and sends only the labels it found:

```json
"metadata": { "pii_types": ["CREDIT_CARD", "EMAIL"] }
```

Never the matched values, never the prompt. The server turns those labels into
the same risk alert and the same compliance tags it would have produced from
the text itself, so a credit card in a prompt still raises `CREDIT_CARD_EXPOSED`
on your Compliance page.

The local scan is regular expressions only, because the SDK has to stay small
enough to install without thinking about it. It finds structured identifiers —
email, SSN, credit card, phone, IP, PAN, Aadhaar, passport, national ID — and
not free-form names. Events sent through the browser extension or over the
ingest API with text in `metadata` are scanned server-side as well, which adds
named-entity recognition on top.

Prompt-injection detection is not implemented on either route.

---

## Sending metadata

Attach arbitrary key-value data to any call. All string values are scanned for PII and redacted before storage.

```python
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": prompt}],
    extra_headers={
        "X-NW-Metadata": json.dumps({
            "ticket_id": "TICK-4821",
            "environment": "production",
        })
    }
)
```

> The SDK wrapper automatically picks up `X-NW-Metadata` headers and includes the values in the event payload.

---

## REST API (no SDK)

If you use a language without an SDK, or need custom control, send events directly:

```bash
curl -X POST https://api.nightswatch.work/v1/ai-usage/events \
  -H "Authorization: Bearer nw_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "provider": "openai",
    "model": "gpt-4o",
    "team": "engineering",
    "user_id": "svc-chat-api",
    "service": "chat-api",
    "prompt_tokens": 800,
    "completion_tokens": 200,
    "total_tokens": 1000,
    "cost_usd": 0.012
  }'
```

**Response**

```json
{
  "event_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "timestamp": "2026-04-11T10:28:00Z",
  "risk_level": "medium",
  "confidence": 0.83,
  "rules_triggered": [
    { "name": "PII_IN_PROMPT", "severity": "medium", "confidence": 0.83 }
  ]
}
```

The `cost_usd` field is optional — when set to `0`, the server auto-computes it from token counts if the model is recognised.

`total_tokens` is also optional: when it is `0` and either token count is set, the
server derives it as `prompt_tokens + completion_tokens`. Send it explicitly when
your provider reports a total that differs from the sum, such as cached or
reasoning tokens.

**Errors**

| Code | Meaning |
|------|---------|
| `401` | Not authenticated: no `Authorization` header, or a key that is not recognised. The response carries `WWW-Authenticate: Bearer` |
| `422` | Validation failed. `detail` is a list of `{type, loc, msg}` — `loc` names the field. The value you sent is not echoed back |
| `429` | Rate limit (60 req/min per key by default), monthly plan event quota, spending cap, or token budget |

`metadata` accepts at most 50 keys and 16 KB serialised; exceeding either returns `422`.

### Batch ingestion

Send up to 1,000 events in one HTTP call:

```bash
curl -X POST https://api.nightswatch.work/v1/ai-usage/events/batch \
  -H "Authorization: Bearer nw_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "events": [
      { "provider": "openai", "model": "gpt-4o", "team": "engineering", "user_id": "svc-chat-api", "total_tokens": 1000, "cost_usd": 0.012 },
      { "provider": "anthropic", "model": "claude-3-5-haiku", "team": "product", "user_id": "svc-summariser", "total_tokens": 500, "cost_usd": 0.0004 }
    ]
  }'
```

---

## Event ingestion behaviour

- **Asynchronous**: events go onto a bounded in-memory queue and are sent by a single background worker after the LLM call returns. Your application never blocks waiting for Nightswatch, and a slow or unreachable endpoint cannot slow down your own requests.
- **Retries**: 3 attempts with exponential backoff (0.1s, 0.2s, 0.4s). A send that fails every attempt is reported through a `WARNING` log naming the HTTP status or network error — your LLM call is never affected.
- **Batching**: events already waiting are sent together, up to 100 per request, to the batch endpoint. A burst of 200 events is two requests rather than two hundred, which is what lets a single delivery worker keep up with a slow endpoint.
- **Backpressure**: the queue holds 1,000 events. If the endpoint cannot keep up, new events are dropped rather than queued without limit, and the count appears in the next failure summary.
- **Quiet failures**: a delivery failure is counted, not logged per event. At most one `WARNING` per minute summarises how many events did not arrive and why, so an outage does not flood your logs at the moment you need to read them.
- **No prompt storage**: only the SHA-256 hash of the prompt is transmitted.

### Short-lived processes

Because delivery happens in the background, a process that exits immediately
after its last LLM call can end before the send completes. The SDK registers an
`atexit` hook that gives the queue **2 seconds** to drain, which covers ordinary
scripts without any code change.

Call `flush()` explicitly where that is not enough — a Lambda handler whose
container may be frozen the moment you return, or a job that must know its
events landed:

```python
import nightswatch

def lambda_handler(event, context):
    result = do_work()
    nightswatch.flush()        # returns True if the queue drained
    return result
```

| Function | Behaviour |
|----------|-----------|
| `nightswatch.flush(timeout=2.0)` | Block until the queue is worked off. Returns `True` if it drained within `timeout`, `False` if events were still pending. |
| `nightswatch.shutdown(timeout=2.0)` | Flush, then stop the worker. It restarts automatically if the SDK is used again. |

Draining is not the same as succeeding: an event that failed every retry has
left the queue and is reported in the `WARNING` log, not through the return
value. `flush()` answers "is anything still waiting", which is the question that
matters before a process exits.

---

## Configuration reference

All configuration is set via `init()`. There is no config file.

| Option | Default | Description |
|--------|---------|-------------|
| `api_key` | — | Required. Get from the Nightswatch dashboard. |
| `default_team` | `"unknown"` | Applied to all events unless overridden per-call |
| `default_service` | `"unknown"` | Applied to all events unless overridden per-call |
| `base_url` | `"https://api.nightswatch.work"` | Override for dev (`"https://api-dev.nightswatch.work"`) or local (`"http://localhost:8000"`) |

---

## Local development

Point the SDK at your local backend:

```python
nightswatch.init(
    api_key="nw_acme_key_123",        # test key from conftest.py
    default_team="engineering",
    base_url="http://localhost:8000",  # local backend
)
```

Start the backend:

```bash
./start.sh   # starts MongoDB, PostgreSQL, and the FastAPI server
```

---

## Troubleshooting

**Events not appearing in the dashboard**

- Check the API key: copy it from **API Keys** in the dashboard and verify it starts with `nw_`.
- Check `base_url`: make sure it does not have a trailing slash.
- The SDK logs failures at `WARNING` level — enable Python logging to see them:
  ```python
  import logging
  logging.basicConfig(level=logging.WARNING)
  ```

**`RuntimeError: nightswatch.init() must be called before wrap()`**

Call `init()` at module import time, before any `wrap()` calls. In FastAPI or Django, put it in your app's startup handler.

**`model not found in pricing table`**

The SDK auto-computes cost only for known models. For unknown models, pass `cost_usd` explicitly. The supported-model list is in the [docs](https://nightswatch.work/docs).

**Events show `cost_usd: 0`**

If neither the SDK nor the caller sets a cost, and the model is not in the pricing table, cost will be `0`. Either pass `cost_usd` explicitly or add the model to the pricing service.

---

## Version history

| Version | Notes |
|---------|-------|
| 0.2.0 | Delivery no longer loses events on exit; batched sends; local PII scanning; drop-in attribute forwarding; async clients refused rather than recorded as free; correct model pricing; `user_id` configurable; a missing API key no longer stops the host application; `py.typed` |
| 0.1.2 | Captures failed LLM calls |
| 0.1.1 | Ingestion failures surfaced via `WARNING` with full error detail; default `base_url` set to `api.nightswatch.work`; Claude 4.x pricing added |
| 0.1.0 | Initial release — OpenAI + Anthropic wrappers, async ingestion, SHA-256 prompt hashing |

---

## License

MIT
