Metadata-Version: 2.5
Name: raain-guard
Version: 1.0.0
Summary: Python SDK for RAAIN Guard — embedded B2B intelligence platform
Project-URL: Homepage, https://raainguard.com
Project-URL: Documentation, https://raainguard.com/build/sdks/python
Project-URL: Support, https://raainguard.com/contact
Project-URL: Changelog, https://raainguard.com/build/sdks/python/changelog
Author-email: RAAIN Guard <contact.raaintech@gmail.com>
License: MIT
License-File: LICENSE
Keywords: b2b,guard,intelligence,raain,sdk
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
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.28
Requires-Dist: pydantic<3,>=2.0
Provides-Extra: dev
Requires-Dist: anyio[trio]; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: respx>=0.21; extra == 'dev'
Description-Content-Type: text/markdown

# RAAIN Guard Python SDK

[![pypi](https://img.shields.io/pypi/v/raain-guard)](https://pypi.org/project/raain-guard/) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://raainguard.com/build/sdks/python)

Official Python SDK for [RAAIN Guard](https://raainguard.com) — the B2B
intelligence platform.

---

## Table of contents

- [Installation](#installation)
- [Quickstart](#quickstart)
- [Tenants](#tenants)
- [Where requests go](#where-requests-go)
- [Configuration](#configuration)
- [Capabilities](#capabilities)
- [Sync vs async usage](#sync-vs-async-usage)
- [Error handling](#error-handling)
- [Running the tests](#running-the-tests)

---

## Installation

```bash
pip install raain-guard
```

Requires Python 3.10 or later. The only runtime dependencies are
[httpx](https://www.python-httpx.org/) and [pydantic v2](https://docs.pydantic.dev/).

---

## Quickstart

<!-- generated:quickstart -->
```python
from raain_guard import RAAINGuardClient

# Server-side only: the secret key is read from RAAIN_GUARD_API_KEY.
client = RAAINGuardClient(tenant_id="customer-42")

answer = client.query.ask("Which invoices are overdue?")
print(answer.message)
print(f"answered by {answer.guard}")
```
<!-- /generated:quickstart -->

---

## Tenants

Every query and every ingest is scoped to one **tenant** — your end-customer.
It is required: give the client a default `tenant_id`, or pass one per call to
act for a different customer.

```python
# A default for the client
client = RAAINGuardClient(tenant_id="customer-42")

# Or per call
client.query.ask("…", tenant_id="customer-7")
```

Asking with no tenant raises `ValueError` before any request is sent, rather
than letting the platform answer with a 422 naming a field you never typed.

Your own **project** is not something you send. The platform resolves it from
the API key, so there is no `project_id` parameter anywhere in this SDK.

---

## Where requests go

The platform runs two services, published under a prefix each:

| Prefix           | Serves            |
| ---------------- | ----------------- |
| `/runtime`   | `query`, `alerts`, `findings`, `tenant_tokens` |
| `/ingestion` | `ingest`          |

`base_url` is the host and the SDK adds the prefix. Point a service somewhere
else when you are running it directly on its own port (the dev stack: runtime `:8020`, ingestion `:8011`; the dev gateway at `http://localhost:8000` needs only `base_url`):

```python
client = RAAINGuardClient(
    runtime_url="http://localhost:8020",
    ingestion_url="http://localhost:8011",
)
```

---

## Configuration

### API key

The client reads the key from `RAAIN_GUARD_API_KEY` when `api_key` is not
supplied:

```bash
export RAAIN_GUARD_API_KEY="rg_live_sk_..."
```

```python
client = RAAINGuardClient()  # key read from env
```

If neither is set the constructor raises `AuthenticationError` immediately — no
lazy key lookup.

**A key carries the scopes it was issued with, and nothing more.** Issue one
with only what the surface needs — `query:read` for something that only asks
questions — and it can do only that. Scopes are enforced by the platform on
every request.

**Keys stay on your server.** Browser and app code holds a **tenant token** instead: mint one per end customer with `client.tenant_tokens.create(tenant_id)` and hand it to the page from an endpoint your own session protects. It is bound to that one tenant, carries `query:read`, plus `alerts:read` for that tenant's alert feed when your server asks for it, expires within an hour, and dies with the key that minted it. Publishable keys (`rg_live_pk_`) are retired and refused.

> **A key in client-side code is readable by anyone who can open it**, and a
> key lets its holder choose the tenant. Never ship one; mint tenant tokens.

### Constructor options

| Parameter       | Default                   | Description                                     |
| --------------- | ------------------------- | ----------------------------------------------- |
| `api_key`       | `RAAIN_GUARD_API_KEY` env | Partner API key                                 |
| `base_url`      | `https://api.raainguard.com`  | Host serving the platform                       |
| `runtime_url`   | —                         | Full base URL for guard-runtime                 |
| `ingestion_url` | —                         | Full base URL for guard-ingestion               |
| `tenant_id`     | —                         | Default end-customer for every call              |
| `timeout`       | `30.0`                    | Request timeout in seconds                      |

### Headers sent automatically

| Header                | Value                              |
| --------------------- | ---------------------------------- |
| `X-API-Key`           | Your API key                       |
| `X-RAAIN-API-Version` | `2026-10-11`                       |
| `X-Tenant-Id`         | The tenant this call is acting for |
| `X-RAAIN-SDK`         | `python/<this version>`            |

---

## Capabilities

### Ingest

Ingest a document's text so a guard can reason over it. The content is chunked,
embedded and stored against the end-customer.

```python
job = client.ingest.document(
    bundle="finance",
    guard="cash",
    doc_id="stmt-2026-01",
    content=statement_text,
)
```

`doc_id` is your own identifier: re-ingesting the same id replaces the previous
content rather than duplicating it.

Upload files instead:

```python
job = client.ingest.upload(
    "finance",
    "cash",
    ["reports/january.csv", "reports/february.csv"],
)
```

Sizes, counts and accepted extensions are enforced by the platform and
published — read them rather than hard-coding them, because they are
configuration and the server rejects anything over its own ceiling regardless of
what a client believes:

```python
limits = client.ingest.limits()
print(limits.max_files, limits.allowed_extensions)
```

To check a CSV before sending it — which record types it reaches, missing
required columns, headers nothing reads — with the project's column mapping
applied and nothing written:

```python
report = client.ingest.validate("inventory", "stock_accuracy", csv_text)
if not report.writable:
    print(report.skipped_targets, report.unmapped_headers)
```

And to see what is in flight:

```python
page = client.ingest.status(bundle="finance", page=1, page_size=20)
```

A batch of documents in one request, as NDJSON (Enterprise). Each line gets its own result, so one
refused line does not fail the rest:

```python
from raain_guard import StreamDocument

results = client.ingest.stream("finance", [
    StreamDocument(guard="cash", doc_id="txn-001", content=text_1),
    StreamDocument(guard="cash", doc_id="txn-002", content=text_2),
])
refused = [r for r in results if not r.accepted]
```

Async variants: `adocument`, `aupload`, `astream`, `alimits`.

### Query

```python
# Non-streaming (sync)
answer = client.query.ask("Which invoices are overdue?")
print(answer.message, answer.bundle, answer.guard)

# Address a guard directly, bypassing intent classification
answer = client.query.ask(
    "What should we reorder?",
    bundle_hint="inventory",
    guard="reorder",
)

# Continue a conversation
follow_up = client.query.ask("Which of those is largest?", session_id=answer.session_id)

# Streaming (sync) — yields the answer text as it arrives, and ends with the answer.
# Use ask() when you need the structured result (guard, grounded, finding_id).
for chunk in client.query.stream("What changed this week?"):
    print(chunk, end="", flush=True)
```

Pair `guard` with `bundle_hint` when the guard name appears in more than one
bundle — `accuracy`, `compliance`, `fraud`, `analytics` and `automation` all do.

Async variants: `aask`, `astream`.

The response carries more than the fields this SDK models — confidence
metadata, metric trajectories, cross-domain signals. Those
are documented in the platform docs and reachable on the model, which permits
extra fields rather than rejecting an answer it does not fully mirror.

### Alerts

The end-customer's prioritized proactive alert feed, generated per request from
the findings your enabled guards have produced and ranked by impact and
severity.

```python
feed = client.alerts.feed(max_alerts=10)

for alert in feed.alerts:
    print(alert.severity, alert.title, alert.total_impact_amount, alert.impact_currency)
```

`max_alerts` caps the feed at 1–100. The Free plan is capped further
server-side, so a feed may be shorter than you asked for.

There is no cursor and nothing to acknowledge: the feed is computed, not a
stored list you page through and mark off.

`total_impact_amount` is a decimal-safe **string**, and `impact_currency` is its
ISO-4217 currency code — the tenant's currency.

Async variant: `afeed`.

### Findings

Read one finding with the evidence it was reasoned from — the id comes from a
query result, an alert's `finding_ids`, or a `finding.created` webhook — and
close the loop on it: what a person decided, then what happened.

```python
finding = client.findings.get(feed.alerts[0].finding_ids[0])
print(finding.severity, finding.impact_amount, finding.evidence)

# Server-side only: both need `feedback:write`, which a tenant token lacks.
decided = client.findings.record_decision(
    finding.finding_id, user_id="u-17", decision="acted", action_taken="Held the payment"
)
client.findings.record_outcome(
    finding.finding_id,
    decision_id=decided.decision_id,
    outcome="confirmed",
    observation_window_days=30,
    actual_impact_amount=Decimal("3450.00"),
)
```

`get` needs `query:read`, so it works under a tenant token, which always reads
its own tenant; `tenant_id=` restricts a secret-key read to one tenant. A
missing finding raises `NotFoundError`. Decisions are `acted`, `dismissed`,
`escalated` or `deferred`; outcomes are `confirmed`, `false_positive`,
`avoided`, `worsened` or `inconclusive`. Both are append-only. Amounts are
decimal-safe strings; pass a `Decimal` or a string, never a float.

Async variants: `aget`, `arecord_decision`, `arecord_outcome`.

### Webhooks

Verify HMAC-SHA256 signatures on incoming deliveries. A pure cryptographic
utility — no HTTP requests are made.

```python
import json
import os

from raain_guard import RAAINGuardClient

client = RAAINGuardClient()

# In your webhook handler (framework-agnostic):
raw_body: bytes = request.body                       # raw bytes, do NOT decode
signature: str = request.headers["X-Webhook-Signature"]
secret: str = os.environ["RAAIN_GUARD_WEBHOOK_SECRET"]

if not client.webhooks.verify(raw_body, signature, secret):
    return 400, "Invalid signature"

event = json.loads(raw_body)
print(event["event_type"])  # "query.completed"
```

The `X-Webhook-Signature` header format is `sha256=<hex_digest>`, computed over
the raw body exactly as delivered — a re-serialized JSON object almost never
reproduces the bytes that were signed.

Delivered events are `query.completed`, `safety.violation` and `fraud.alert`.

---

## Sync vs async usage

The same `RAAINGuardClient` supports both. The underlying HTTP clients are
created lazily and held for the lifetime of the instance.

### Sync

```python
from raain_guard import RAAINGuardClient

# As a plain object (lives until garbage-collected)
client = RAAINGuardClient(api_key="rg_live_sk_...", tenant_id="customer-42")
answer = client.query.ask("What is our cash runway?")

# As a context manager (recommended — ensures connection cleanup)
with RAAINGuardClient(tenant_id="customer-42") as client:
    answer = client.query.ask("What is our cash runway?")
```

### Async

```python
import asyncio

from raain_guard import RAAINGuardClient


async def main() -> None:
    async with RAAINGuardClient(tenant_id="customer-42") as client:
        job = await client.ingest.adocument("finance", "cash", "stmt-1", text)
        answer = await client.query.aask("What is the cash balance?")
        print(answer.message)


asyncio.run(main())
```

All async methods are prefixed with `a` — `aask`, `adocument`, `afeed`.

---

## Error handling

All SDK exceptions inherit from `RAAINGuardError`.

```python
import time

from raain_guard import (
    RAAINGuardClient,
    RAAINGuardError,
    AuthenticationError,
    PermissionError,
    NotFoundError,
    InvalidRequestError,
    RateLimitError,
    APIError,
    NetworkError,
)

client = RAAINGuardClient(tenant_id="customer-42")

try:
    answer = client.query.ask("...")

except AuthenticationError:
    # API key missing or rejected (HTTP 401)
    print("Check your RAAIN_GUARD_API_KEY")

except PermissionError:
    # The key does not carry the scope this call needs (HTTP 403)
    print("Insufficient scope")

except NotFoundError:
    # HTTP 404
    print("Resource not found")

except InvalidRequestError as exc:
    # The platform rejected the request (HTTP 400 or 422). `errors` carries
    # the per-field detail, and the message names the offending field.
    print(exc)
    for err in exc.errors:
        print(f"  {err}")

except RateLimitError as exc:
    # HTTP 429
    print(f"Rate limited — retry after {exc.retry_after}s")
    time.sleep(exc.retry_after)

except APIError:
    # HTTP 5xx
    print("RAAIN Guard server error — try again later")

except NetworkError:
    # Connection-level failure
    print("Could not reach the platform — check connectivity")

except RAAINGuardError:
    raise
```

Every exception exposes `.status_code` (`None` for `NetworkError`, and for an
`AuthenticationError` raised before any request).

Asking or ingesting without a tenant raises `ValueError` rather than
`RAAINGuardError`: it is a mistake in the call, caught before anything is sent.

---

## Running the tests

```bash
pip install -e ".[dev]"
pytest
```

The suite uses [respx](https://lundberg.github.io/respx/) to mock the httpx
transport — no real network calls are made. `tests/test_contract.py` checks this
SDK against `raain-guard-sdk/CONTRACT.json`, which is generated from the
platform's own OpenAPI, so a path or field that drifts from what the platform
serves fails the build.

---

## Documentation and support

<!-- generated:links -->
| | |
| --- | --- |
| Guide for this SDK | [raainguard.com/build/sdks/python](https://raainguard.com/build/sdks/python) |
| API reference | [raainguard.com/sdk-reference/python](https://raainguard.com/sdk-reference/python/index.html) |
| Changelog | [raainguard.com/build/sdks/python/changelog](https://raainguard.com/build/sdks/python/changelog) |
| This package on its registry | [pypi.org/project/raain-guard/](https://pypi.org/project/raain-guard/) |
| HTTP API reference | [api.raainguard.com/reference/](https://api.raainguard.com/reference/) |
| Bugs and questions | [raainguard.com/contact](https://raainguard.com/contact) |
<!-- /generated:links -->

This package is on SDK train **1.0**. Every RAAIN Guard SDK on the same `MAJOR.MINOR` train has the
same capabilities and pins the same API version, in every language; the patch number is this
package's own fixes. A breaking change is a new major train and is listed first in the changelog.
The platform supports the current and the previous train.

## License

MIT — see the `LICENSE` file in this package for details.
