Metadata-Version: 2.5
Name: raain-guard
Version: 1.0.1
Summary: Official Python SDK for RAAIN Guard, the embedded decision-intelligence platform for business software.
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 Tech Pvt. Ltd." <support.raaintech@gmail.com>
License: MIT
License-File: LICENSE
Keywords: api-client,decision-intelligence,raain,raain-guard,raaintech,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: Programming Language :: Python :: 3.14
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

![RAAIN Guard](https://raainguard.com/brand/product/raain-guard-logo-128.png)

[![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 embedded decision-intelligence platform
for business software. Your product sends questions and documents through the SDK; domain guards answer with
findings grounded in each of your customers' own data.

## Requirements

<!-- generated:requirements -->
Python 3.10 or later. Its only runtime dependencies are httpx and pydantic v2.
<!-- /generated:requirements -->

## Installation

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

## 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 -->

The secret key is read from `RAAIN_GUARD_API_KEY`. Keep it on your server: never in a browser bundle, an app or
source control.

## Authentication

Every request is authenticated with an API key, which the SDK sends in the `X-API-Key` header. Keys look like
`rg_live_sk_…` or `rg_test_sk_…`. The SDK reads `RAAIN_GUARD_API_KEY` from the environment, or you pass it:

```python
client = RAAINGuardClient(api_key=os.environ["RAAIN_GUARD_API_KEY"])
```

With neither, the constructor raises `AuthenticationError` immediately.

**A key carries the scopes it was issued with, and nothing more.** Issue one with only what the integration needs
(`query:read` for something that only asks questions); the platform enforces scopes on every request.

**Keys stay on your server.** Code that runs where a user can open it holds a **tenant token** instead: mint one per
end customer with [`client.tenant_tokens.create`](#tenant-tokens) and hand it to the page from an endpoint your own
session protects. A key in browser or app code is readable by anyone who can open it, and a key lets its holder
choose the tenant.

> `rg_test_sk_…` is an ordinary key that reads and writes the data of the project that issued it. It is **not** a
> sandbox. To keep test data away from real customers, issue the key on a project you use only for testing.

## Tenants

Every query and every ingest is scoped to one **tenant**, your end-customer. Give the client a default, or pass one
per call to act for a different customer. Calling without either raises `ValueError` before anything is sent,
rather than letting the platform answer with a 422 naming a field you never typed.

```python
client = RAAINGuardClient(tenant_id="customer-42")                         # a default for the client
client.query.ask("Which invoices are overdue?", tenant_id="customer-7")    # or per call
```

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

## Configuration

### Options

`RAAINGuardClient(...)`

| Option | Default | Description |
| --- | --- | --- |
| `api_key` | `RAAIN_GUARD_API_KEY` | The API key |
| `tenant_id` | none | The default end-customer for every call |
| `base_url` | `https://api.raainguard.com` | The host serving the platform |
| `runtime_url`, `ingestion_url` | none | A service's own URL, when it is not served behind `base_url` |
| `timeout` | `30.0` | Request timeout in seconds |

### Where requests go

The platform runs two services under one host, a path prefix each: `/runtime` serves query, templates, alerts,
findings, output validation and tenant tokens; `/ingestion` serves ingest. `base_url` is the host and the SDK adds
the prefix. Set a service's own URL only when that service is not served behind the base host, as in a self-hosted
installation that exposes each service at its own address:

```python
client = RAAINGuardClient(
    runtime_url="https://guard-runtime.example.internal",
    ingestion_url="https://guard-ingestion.example.internal",
)
```

### Headers sent automatically

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

## Usage

Every call, in this language. Each has an `a`-prefixed async twin (`aask`, `adocument`, `afeed`):

<!-- generated:capabilities -->
| Capability | Call | Needs |
| --- | --- | --- |
| Ask a question | `client.query.ask(question)` | Tenant token or secret key |
| Stream an answer as it is generated | `client.query.stream(question)` | Tenant token or secret key |
| List the ready-made questions | `client.templates.list()` | Tenant token or secret key |
| Read the alert feed | `client.alerts.feed(max_alerts=10)` | Tenant token or secret key |
| Read a finding with its evidence | `client.findings.get(finding_id)` | Tenant token or secret key |
| Read a finding's lifecycle | `client.findings.lifecycle(finding_id)` | Tenant token or secret key |
| Record what a person decided | `client.findings.record_decision(finding_id, user_id=..., decision=...)` | Secret key, on your server |
| Record what happened afterwards | `client.findings.record_outcome(finding_id, decision_id=..., outcome=..., observation_window_days=...)` | Secret key, on your server |
| Validate text or a document your product generated | `client.outputs.validate(text=...)` | Tenant token or secret key |
| Ingest one document's text | `client.ingest.document(bundle, guard, doc_id, content)` | Secret key, on your server |
| Upload files | `client.ingest.upload(bundle, guard, paths)` | Secret key, on your server |
| Check a CSV before ingesting it | `client.ingest.validate(bundle, guard, content)` | Secret key, on your server |
| Ingest a batch of documents in one request | `client.ingest.stream(bundle, documents)` | Secret key, on your server |
| Read what ingestion accepts | `client.ingest.limits()` | Secret key, on your server |
| List ingestion jobs | `client.ingest.status()` | Secret key, on your server |
| Read one ingestion job | `client.ingest.job(job_id)` | Secret key, on your server |
| Read the records a job stored | `client.ingest.records(job_id)` | Secret key, on your server |
| Replay an ingestion job | `client.ingest.replay(job_id)` | Secret key, on your server |
| Erase one tenant's data | `client.ingest.purge_tenant(tenant_id)` | Secret key, on your server |
| Mint a tenant token for browser or app code | `client.tenant_tokens.create(tenant_id)` | Secret key, on your server |
| Verify a webhook delivery's signature | `client.webhooks.verify(payload, signature, secret)` | Webhook signing secret, on your server |
<!-- /generated:capabilities -->

Results are typed models; amounts are decimal-safe strings.

### Query

Ask a natural-language question. The runtime classifies its intent, routes it to a bundle and guard, retrieves the
end-customer's own records, and answers.

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

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

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

# Stream the answer as it is generated; ask() returns 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). The result carries more than the fields shown: confidence metadata,
metric trajectories and cross-domain signals are reachable on the model, which permits extra fields rather than
rejecting an answer it does not fully mirror.

### Ready-made questions

The platform ships ready-made questions (templates) that render a question from typed parameters. List what your
project can use, then pass one to `ask`:

```python
from raain_guard import Templates

available = client.templates.list()
cash = client.query.ask(Templates.CASH_POSITION, parameters={"horizon_days": 14})
```

### 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 to 100, and the Free plan is capped further server-side. There is no cursor and
nothing to acknowledge: the feed is computed, not a stored list. `total_impact_amount` is a decimal-safe string,
and `impact_currency` is its ISO-4217 code, the tenant's currency.

### Findings

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

```python
from decimal import Decimal

finding = client.findings.get(feed.alerts[0].finding_ids[0])
lifecycle = client.findings.lifecycle(finding.finding_id)
print(finding.severity, finding.impact_amount, len(lifecycle.decisions))

# Server-side only: both need `feedback:write`, which a tenant token does not carry.
decided = client.findings.record_decision(
    finding.finding_id, user_id="u-17", decision="acted", action_taken="Held the duplicate 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"),
)
```

Decisions are `acted`, `dismissed`, `escalated` or `deferred`; outcomes are `confirmed`, `false_positive`,
`avoided`, `worsened` or `inconclusive`. Both are append-only, and outcomes calibrate confidence for later findings
of the same kind. A missing finding raises `NotFoundError`.

### Output validation

Check text or a document your own product generated before you show it. Deterministic checks always run, plus the
policies you select, and nothing you send is stored.

```python
check = client.outputs.validate(
    text=answer.message,
    policies=[{"id": "prohibited_terms", "params": {"terms": ["guarantee"]}}],
)
if check.decision != "allow":
    print(check.decision, check.findings)
```

`decision` is `allow`, `redact` (show `redacted_text`), `review` or `block`.

### Ingest

Send a tenant's documents and records in. Content is chunked, embedded and stored against the end-customer, and
becomes retrievable by the guard you name. Ingestion is asynchronous: what comes back is the job doing the work.

```python
from raain_guard import StreamDocument

job = client.ingest.document("finance", "cash", "stmt-2026-01", statement_text)
print(job.job_id, job.status)

# Files, as multipart
client.ingest.upload("finance", "cash", ["reports/january.csv", "reports/february.csv"])

# A batch as NDJSON (Enterprise): one result per line, so one refused line does not fail the rest
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),
])

# Check a CSV before sending it; nothing is written
report = client.ingest.validate("inventory", "stock_accuracy", csv_text)
if not report.writable:
    print(report.skipped_targets, report.unmapped_headers)

# What the platform accepts, and what is in flight
limits = client.ingest.limits()
jobs = client.ingest.status(bundle="finance", page=1, page_size=20)
one = client.ingest.job(job.job_id)
records = client.ingest.records(job.job_id)
client.ingest.replay(job.job_id)
client.ingest.purge_tenant("customer-42")   # erases everything stored for that tenant
```

`doc_id` is your own identifier: re-ingesting the same id replaces the previous content. Read `limits` rather than
hard-coding file counts, sizes or extensions: the server rejects anything over its own ceiling.

### Tenant tokens

A tenant token is a short-lived credential for browser and app code: bound to one tenant, carrying `query:read`
(plus `alerts:read` when you ask for it), expiring within an hour. Mint one on your server for the signed-in user's
tenant and return it from an endpoint your own session protects.

```python
minted = client.tenant_tokens.create("customer-42", scopes=["query:read", "alerts:read"])
print(minted.token, minted.expires_at)
```

### Webhooks

Verify that a delivery came from RAAIN Guard before acting on it. Pass the **raw** request body: a re-serialized
JSON object almost never reproduces the bytes that were signed.

```python
import json
import os


def handle_webhook(raw_body: bytes, signature: str) -> int:
    if not client.webhooks.verify(raw_body, signature, os.environ["RAAIN_GUARD_WEBHOOK_SECRET"]):
        return 400
    event = json.loads(raw_body)
    print(event["event_type"])
    return 200
```

The signature is in the `X-Webhook-Signature` header as `sha256=<hex>`. Delivered events are `query.completed`,
`safety.violation`, `fraud.alert`, `finding.created` and `ingestion.completed`.

## Error handling

Every error inherits from `RAAINGuardError`, and exposes `.status_code` (`None` for `NetworkError`).

```python
from raain_guard import AuthenticationError, InvalidRequestError, NetworkError, RateLimitError

try:
    client.query.ask("Which invoices are overdue?")
except RateLimitError as exc:
    print(f"Retry after {exc.retry_after}s")
except InvalidRequestError as exc:
    print(exc, exc.errors)            # names the field the platform rejected
except AuthenticationError:
    print("Check your API key")
except NetworkError:
    print("Could not reach the platform")
```

| Error | HTTP status | When |
| --- | --- | --- |
| `AuthenticationError` | 401 | The key is missing, invalid or revoked |
| `PermissionError` | 403 | The key or token lacks the scope this call needs |
| `NotFoundError` | 404 | The finding, job or resource does not exist |
| `InvalidRequestError` | 400, 422 | The request is wrong; `errors` carries the per-field detail |
| `RateLimitError` | 429 | Rate limited; `retry_after` is the wait in seconds |
| `APIError` | 5xx | The platform failed |
| `NetworkError` | none | The platform could not be reached or the request timed out |

`PermissionError` is the SDK's own class, not the built-in. A call without a tenant raises `ValueError`: it is a
mistake in the call, caught before anything is sent.

## Testing your integration

The SDK sends its requests with [httpx](https://www.python-httpx.org/), so [respx](https://lundberg.github.io/respx/)
mocks it. No request leaves the process:

```python
import httpx
import respx

from raain_guard import RAAINGuardClient


@respx.mock
def test_overdue_invoices() -> None:
    respx.post("https://api.raainguard.com/runtime/v1/query").mock(
        return_value=httpx.Response(200, json={"message": "Two invoices are overdue.", "bundle": "invoicing", "guard": "accuracy"})
    )
    client = RAAINGuardClient(api_key="rg_test_sk_unit", tenant_id="customer-42")
    assert client.query.ask("Which invoices are overdue?").guard == "accuracy"
```

Or point `base_url` at a local stub server. A `rg_test_sk_…` key talks to the real platform and writes real data;
use a project of its own for tests.

## Platform notes

**Sync and async.** One `RAAINGuardClient` serves both. Its HTTP clients are created on first use and held for the
life of the instance, so use it as a context manager to release connections:

```python
import asyncio

from raain_guard import RAAINGuardClient


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


asyncio.run(main())
```

## 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) |
| Technical support | [support.raaintech@gmail.com](mailto:support.raaintech@gmail.com) |
<!-- /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.
