> ## Documentation Index
> Fetch the complete documentation index at: https://docs.xenovia.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Reference

> Client options, the response object, sessions, model call helpers, errors and the wire format.

The detail behind the [Quickstart](https://docs.xenovia.io/sdk/quickstart.md) and [Hooks](https://docs.xenovia.io/sdk/hooks.md).

## Constructor parameters

| Parameter | Type | Default | Description |
| - | - | - | - |
| `api_key` | `str` | required | The agent's API key (`xe_...`), or a [sub-agent](https://docs.xenovia.io/sdk/hooks.md#sub-agents) key |
| `endpoint` | `str` | `https://runtime.xenovia.io` | Runtime base URL. Set your runtime's ingress URL for a hybrid deployment |
| `timeout` | `int` | `65` | HTTP timeout in seconds. Guardrail checks can take several seconds |
| `unreachable_mode` | `str` | `"block"` | What to return when the runtime cannot be reached (see below) |
| `raise_on_block` | `bool` | `False` | Raise `XenoviaBlockedError` instead of returning a blocked response |
| `auto_session` | `bool` | `False` | Let the runtime create a session on the first call and reuse it |
| `default_env` | `str` | `"prod"` | Environment label sent with each check. Xenovia does not record it |
| `identity_id` | `str` | env `XENOVIA_AGENT_ID` or `"default-agent"` | Label sent with each check. Xenovia does not record it; the key identifies the agent |
| `identity_type` | `str` | `"agent"` | Identity type label. Xenovia does not record it |
| `debug` | `bool` | `False` | Print decision outcomes to stdout |
| `allow_insecure_http` | `bool` | `False` | Allow `http://` to `localhost`, `127.0.0.1`, or `::1` only |

> [!WARNING]
>
> Do not set `agent_role`. The runtime no longer accepts it: every check from a client with `agent_role` set fails with `400` (`agent_role is no longer supported: use a sub-agent key`), raised as `XenoviaExecutionError`. Use a [sub-agent](https://docs.xenovia.io/sdk/hooks.md#sub-agents) key instead. The `agent_depth` field in the request body is accepted but ignored; the runtime reads the depth from the `x-xenovia-agent-depth` header instead, which the SDK does not set.

**`unreachable_mode` values:**

| Mode | Behaviour |
| - | - |
| `"block"` (default) | Return a synthetic `blocked` response (fail closed) |
| `"error"` | Raise `XenoviaUnreachableError` |
| `"allow"` | Return a synthetic `success` response (fail open) |

> [!NOTE]
>
> The `"block"` and `"allow"` fallbacks are produced by the SDK on your machine, not by Xenovia. You can tell them apart from a real decision: `decision["rule_id"]` is `SDK_UNREACHABLE_BLOCK` or `SDK_UNREACHABLE_ALLOW`, `trace_id` is `None`, and no trace appears in the platform.

## `XenoviaResponse`

```python theme={null}
@dataclass(frozen=True)
class XenoviaResponse:
    status:     str          # "success" | "blocked" | "failed"
    result:     Any          # the guarded function's return value (guard only)
    error:      str | None
    decision:   dict         # {"outcome": "allow" | "redact" | "deny" | "error", "escalated": bool}
    trace_id:   str | None   # trace UUID for correlation
    raw:        dict         # the runtime's response body
    payload:    dict | None  # masked values when the outcome is "redact"
    session_id: str | None   # session the runtime used

    def is_success(self) -> bool: ...
    def is_blocked(self) -> bool: ...
    def is_redacted(self) -> bool: ...
    def is_escalated(self) -> bool: ...
    def is_failed(self) -> bool: ...
```

The decision never contains the rule or the reason. Look up `trace_id` in the platform to see which policy or guardrail fired.

## Sessions

The runtime issues the session and returns it in the `X-Xenovia-Session-Id` response header; the SDK reads it into `response.session_id`.

* With `auto_session=True`, the first call lets the runtime create a session, and later calls reuse it. `xenovia.session_id` holds it after the first decision.
* To pass `session_id=` yourself, use a session the runtime already knows: one an earlier SDK call returned, or one your agent endpoint traffic created with `X-Xenovia-Session-Id`. A UUID the runtime has not seen fails with `403` (`unknown session`), and another agent's session fails with `403` (`session ownership mismatch`). Both raise `XenoviaExecutionError`.
* To group SDK checks with model turns, send the model call first with your own `X-Xenovia-Session-Id`, then pass the same ID as `session_id=`.
* Sessions expire after 30 minutes without activity.
* If the runtime returns a different session than the one you sent, the SDK raises `XenoviaExecutionError`.
* `turn=` attaches a check to a turn your agent endpoint traffic started in that session. It needs a session, and a turn the session has not reached fails with `400` (`unknown session turn`). Without `turn=`, each check gets its own trace.
* `next_turn()` only advances a local counter.

Inside a request handled by the [session middleware](#route-model-calls-through-xenovia), `execute()` and every hook send that request's session when you pass no `session_id=`. That session is not stored as the client's automatic session.

## Route model calls through Xenovia

The SDK includes helpers that point an OpenAI-compatible client at the agent endpoint and forward the `X-Xenovia-Session-Id` header of the request your agent is handling. When whatever calls your agent sends that header, the agent's model calls and SDK checks join the caller's session.

```python theme={null}
import os
from fastapi import FastAPI
from openai import OpenAI
from xenovia_sdk import Xenovia, XenoviaASGIMiddleware, openai_client_kwargs

app = FastAPI()
app.add_middleware(XenoviaASGIMiddleware)  # reads X-Xenovia-Session-Id from each request

client = OpenAI(**openai_client_kwargs())  # base_url, api_key, and an httpx client
xenovia = Xenovia(api_key=os.environ["XENOVIA_API_KEY"])
```

| Helper | What it does |
| - | - |
| `XenoviaASGIMiddleware` | ASGI middleware (FastAPI, Starlette, Django ASGI) that reads the request's `X-Xenovia-Session-Id` |
| `XenoviaWSGIMiddleware` | The same for WSGI (Flask, Django): `app.wsgi_app = XenoviaWSGIMiddleware(app.wsgi_app)` |
| `current_session()` | The session header of the request being handled, or `None` |
| `session_scope(value)` | A `with` block that sets the current session, for queue workers, CLIs, and threads you start |
| `openai_client_kwargs(async_=False)` | `{base_url, api_key, http_client}` for `OpenAI`, `AsyncOpenAI` (`async_=True`), or LangChain `ChatOpenAI` |
| `xenovia_http_client()`, `xenovia_async_http_client()` | `httpx` clients that add the current session header to each request |

`openai_client_kwargs()` reads `XENOVIA_RUNTIME_URL` (default `https://runtime.xenovia.io`), `XENOVIA_AGENT_ID`, and `XENOVIA_API_KEY` unless you pass `runtime_url=`, `agent_id=`, or `api_key=`. It builds a new `httpx` client on each call, so create your model client once and reuse it. The session header is added only when a session is set, and its value is forwarded unchanged, so it must be a UUID for the runtime to accept it.

## Error handling

```python theme={null}
from xenovia_sdk import (
    XenoviaBlockedError,
    XenoviaExecutionError,
    XenoviaUnreachableError,
)

strict = Xenovia(api_key=os.environ["XENOVIA_API_KEY"], raise_on_block=True, unreachable_mode="error")

try:
    strict.tool_pre("delete_account", {"account_id": "acct_123"})
except XenoviaBlockedError as e:
    ...  # denied by a policy or guardrail; e.trace_id finds it in Sessions
except XenoviaUnreachableError:
    ...  # runtime unreachable and unreachable_mode="error"
except XenoviaExecutionError:
    ...  # any other non-2xx response, an unexpected body, or a session mismatch
```

A `XenoviaExecutionError` from an HTTP error names the status, the runtime's error text, and the trace ID when there is one. Malformed input raises `ValueError` before any request is sent, for example a `model_pre` message part the SDK cannot read.

## Wire format

```json theme={null}
POST /v1/execute
Authorization: Bearer xe_...

{
  "stage": "tool_call",
  "operation": "payments.transfer",
  "payload": { "arguments": { "amount": 500, "to": "acct_123" } },
  "session_id": "550e8400-e29b-41d4-a716-446655440000",
  "identity": { "type": "agent", "id": "billing-agent" },
  "env": "prod",
  "sdk": { "version": "0.3.0", "language": "python" }
}
```

`session_id` and `turn` are sent only when set. The runtime reads `stage`, `operation`, `payload`, `session_id`, and `turn`; `identity`, `env`, and `sdk` are informational. The response body is `{"status", "decision": {"outcome", "escalated"}, "payload", "trace_id"}`, with the session in the `X-Xenovia-Session-Id` header. A denial is `403` with `status: "blocked"` and no reason.

## Security

* HTTPS is required unless `allow_insecure_http=True`, which is limited to loopback addresses.
* The API key is sent only in the `Authorization` header, never in payloads or logs.
* Debug output prints the operation, decision outcome, and trace ID, not payloads.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.