# Python SDK

> The Curva Python SDK reference (pip install curva-ai): clients, methods, async usage, question types, results and errors.

Source: https://docs.tarkova.com/curva/reference/python-sdk/

```bash
pip install curva-ai
```

The `curva` package uses only the Python standard library (Python 3.9+). Platform wheels also
ship the `curva` server binary.

```python

from curva import Curva, Choice, Score, Noul, Multi, CurvaError
```

## Clients

### `curva.local()`

```python
curva.local(model=None, db=None, *, startup_timeout=15.0, **client_options) -> LocalCurva
```

Starts `curva serve` on a free `127.0.0.1` port and returns a client bound to it. The server stops
when Python exits, when you call `close()`, or at the end of a `with` block.

- `model`: the server's default model.
- `db`: SQLite file for decisions, feedback and calibrators (default `~/.curva/curva.db`).
- The server inherits this process's environment (`OPENROUTER_API_KEY`, `CURVA_RPM`, ...).
- `client_options` go to `Curva` (`timeout`, `max_retries`, `api_key`).

### `Curva`

```python
Curva(base_url=None, api_key=None, *, model=None, timeout=30.0, max_retries=3,
      retry_statuses=(429, 5xx), headers=None)
```

A client for a running server. Reads `CURVA_BASE_URL` (default `http://localhost:7777`) and
`CURVA_API_KEY` when not given. 429, 5xx and dropped connections are retried up to
`max_retries` times, honouring `Retry-After`. `headers` are sent with every request. Also usable
as `with Curva() as client:`.

## Methods

### `decide`

```python
client.decide(state, questions=None, *, model=None, mode=None, debias=None, think=False, project=None,
              council=None, cascade=None, escalate_below=None, race=None, explain=False, config=None,
              privacy=None, images=None, assets=None, fallback=None, deadline_ms=None, learn=False,
              learned=False, ask=None, call=None, node=None, brief=False, sources=None, triggers=None) -> Decision
```

| Argument | Meaning |
|---|---|
| `state` | Any JSON-serialisable value |
| `questions` | `{key: question}`: `Choice`, `Score`, `Noul` or `Multi` objects, or plain dicts in the HTTP shape (needed for [`when`](/curva/guides/conditional/)) |
| `model` | A model id, or a list tried in order (fallback chain) |
| `mode` | `"auto"` (default), `"logprobs"` or `"verbal"` |
| `debias` | Ask in both option orders and average (server default `True`) |
| `project` | Calibration namespace |
| `council` / `cascade` / `race` | Multi-model plans; use at most one. `escalate_below` goes with `cascade` |
| `explain` | Add per-field attribution to every answer |
| `config` | A pinned config such as `"curva-1.0.0"` |
| `privacy` | `"strict"` to use only providers that neither store nor train on data |
| `fallback` | `{key: answer}` for every question, returned instead of raising [when no model can answer](/curva/guides/multi-model/#when-no-model-can-answer) |
| `ask` | A built-in set (`"check"`, `"guard"`, `"emotion"`, ...) in place of `questions`, or the path of an [ask file](/curva/guides/ask-files/) (`"rules.md"`), whose text is sent; plain words are turned into a file once and saved next to your script |
| `triggers` | `{name: trigger}`: actions to fire when the answers hold, posted to `webhook`, `slack`, `teams`, `discord` or `telegram`; the fired ones are in `d.actions`. See [Actions](/curva/guides/actions/) |
| `images`, `assets`, `sources` | Pictures, recordings and video (`Asset.image`, `Asset.audio`, `Asset.video`), and a [library](/curva/guides/library/) collection to answer from |
| `deadline_ms`, `learn`, `learned`, `call`, `node`, `brief`, `think` | As in [`POST /v1/decide`](/curva/reference/http-api/#request-fields) |

`system_one` is an alias of `decide`.

### `route`

```python
client.route(prompt, models, *, default=None, min_confidence=None, **decide_options) -> Route
```

Picks which of your models should answer `prompt` ([guide](/curva/guides/routing/)). `models` maps
each model name to what it is good at. The `Route` has `model`, `confidence`, `probabilities`,
`defaulted` (true when it is your `default`: Curva was below `min_confidence`, or no model
answered) and `decision` (use `decision.id` with question `"route"` for feedback).

### `check`

```python
client.check(action, policy, *, context=None, min_confidence=0.8, **decide_options) -> Check
```

Says whether `policy` allows `action` ([guide](/curva/guides/agents/#check-an-action-before-the-agent-takes-it)).
Only `action` is judged. `context` is optional background, such as the conversation so far or who
is asking (any JSON): it can show that a condition the policy sets for this action is met (an
approval that was given, the amount), but other requests it mentions are not judged and do not
change the verdict. Pass the conversation there, not inside `action`:

```python
client.check({"tool": "cancel_plan"}, "Refunds above $200 need a manager's approval. Cancelling a plan is always allowed.",
             context=[{"caller": "Please cancel my plan and refund me 500 dollars."}])
```

The `Check` has `verdict` (`"allow"`, `"block"`, or `"review"` when Curva is below `min_confidence`
or no model answered), `allowed` (true only for a confident allow), `confidence` and `decision`.
It never raises for a failed model.

### `guard`

```python
client.guard(text, **decide_options) -> Decision
```

Screens a text with the `guardrails` recipe ([guide](/curva/guides/agents/#screen-text-before-it-reaches-the-agent)):
answers `prompt_injection`, `personal_data`, `toxicity` and `verdict`. An unsure verdict is
`"review"`; when no model answers the decision has `fallback == True`.

### `feedback`

```python
client.feedback(decision_id, question, label) -> dict
```

Records the true answer: an option key (Choice), a level index (Score) or `True`/`False` (Noul).

### `calibration`

```python
client.calibration(question, project=None) -> dict
```

Held-out before/after accuracy, ECE, Brier and reliability bins for a question.

### `audit`

```python
client.audit(project=None, before=None, limit=100) -> dict
```

Logged decisions, newest first: `{"entries": [...], "next_before": id or None}`. Pass
`next_before` back as `before` for the next page.

### `drift`

```python
client.drift(question, project=None, weeks=8) -> dict
```

The question's weekly answer mix and confidence, with a drift flag on the latest week. See
[Drift](/curva/guides/drift/).

### `health`, `models`

`client.health()` returns `{"status", "version"}`; `client.models()` lists the pinned configs.

### `watch`

```python
curva.watch(source, ask=None, *, questions=None, on=None, state=None, fps=5, client=None, **start) -> Iterator[Event]
```

Live video against `/v1/watch`. `source` is a file, a URL (`rtsp://`, `http(s)://`), a camera
index (`0` for the webcam; these three need ffmpeg) or an iterable of JPEG/PNG/WebP frames, each
optionally `(frame, readings)`. Yields an `Event` (a dict) for every decision, action,
`confirmed`/`retracted` check, error and the final receipt; `str(event)` reads as a sentence.
`on={"name": fn}` runs `fn(action)`; other keywords (`triggers`, `fallback`, `deadline_ms`,
`stream`, `max_quiet_s`, `model`, `speculative`) go into the `start` message. When the connection
drops, the SDK opens the stream again and yields a `connection_error` event: frame numbers start
again at 1, and the final receipt counts only the frames sent after it. See
[Watch live video](/curva/guides/watch/).

### `verify_webhook`

```python
verify_webhook(body, signature, secret, idempotency_key, tolerance=300) -> bool
```

True when `signature` (the `x-curva-signature` header, `t=<unix seconds>,v1=<hex>`) is the
HMAC-SHA256 of `<t>.<idempotency_key>.<raw body>` under the project's webhook secret, and `t` is at
most `tolerance` seconds from now. `idempotency_key` is the `x-curva-idempotency-key` header. Check
it before parsing the body. See
[Actions](/curva/guides/actions/#your-own-webhook).

### `curva.integrations.tools` and `guarded`

```python
tools(questions=None, *, name="case", policy=None, client=None, **options) -> list[Callable[..., str]]
guarded(policy=None, *, approved=None, deadline_ms=10000, client=None, **options) -> decorator
```

`tools()` returns plain typed functions an agent framework registers as tools: `decide_<name>`
(only with `questions`), `check_action` and `screen_text`. Each takes text and returns JSON text;
a Curva error comes back as `{"error": ...}`. `guarded()` wraps a tool, sync or async, so every
call is checked against `policy` first and runs only on "allow"; on "block" or "review" it returns
one sentence for the agent. `approved` is `True` or a function of the call's arguments: the user's
own approval in your app. `deadline_ms` caps the check (default 10 s; None waits up to the client
timeout); a missed deadline does not run the tool. See
[Agent frameworks](/curva/guides/agent-frameworks/).

## Async

`AsyncCurva` takes the same arguments as `Curva` and has the same methods, awaitable:

```python
from curva import AsyncCurva

async with AsyncCurva() as client:
    d = await client.decide(state, questions)
    decisions = await client.decide_many([(state_a, questions), (state_b, questions)])
```

`decide_many` runs several decisions, at most `concurrency` (default 8) at once, and keeps the
input order; `return_exceptions=True` puts each failure in its slot instead of raising. It runs the blocking client in worker threads,
which suits up to a few hundred concurrent calls.

## Questions

```python
Choice(instructions, options=None, *, criteria=None, escape=None, min_confidence=None, examples=None)
Score(instructions, levels=None, *, criteria=None, min_confidence=None, examples=None)
Noul(instructions, examples=None, *, criteria=None)
Multi(instructions, options, *, threshold=0.5)
question.when(**fields)      # ask only when the state (or an "@key" answer) matches
question.rule(answer, **if)  # answer instantly when the conditions hold
question.depends(*keys)      # answer after `keys`, seeing their answers
```

- `options`: `{key: description}` or a list of keys. Order is kept.
- `escape`: add `none_of_these` (default on when `options` is given).
- `min_confidence`: answers below it get `abstain=True`.
- `examples`: up to 10 `(state, label)` pairs.
- `think=True` (any question): reason before answering, in a call of its own. See
  [Workflows in one call](/curva/guides/dependencies/) for `.depends()`.
- `criteria=`: the compatible style. `Choice(..., criteria={...})` (descriptions may be `None` or
  JSON, and there is no escape option unless `escape=True`), `Score(..., criteria=[...])`,
  `Noul(..., criteria={"true": ..., "false": ...})`.

## Results

### `Decision`

| Attribute | Meaning |
|---|---|
| `id` | `dec_…`, used for feedback |
| `model`, `mode`, `project`, `config` | How the decision was made |
| `latency_ms`, `cost_usd`, `cached` | Model time, cost, and whether it came from the cache |
| `wall_ms` | How long the decision really took on the server, waiting included |
| `lessons` | With `learn=True`: how many examples from your feedback the model was shown |
| `request_id` | The response's `x-request-id`, for matching server logs |
| `usage` | Token usage, when the server reports it |
| `answers` | `{key: Answer}`; also `d["key"]` |
| `fallback`, `error` | `fallback` is true when no model answered and the answers are your `fallback=` values; `error` then says why |
| `actions` | The triggers that fired: `[{"name", "id", "because"}]`, empty when none did |
| `receipt` | The signed receipt; check it with `verify_receipt(d.receipt, keys, decision=d)` |
| `choices`, `scores`, `nouls` | Answers grouped by type |

### `Answer`

Only the fields for the question's type are set; the rest are `None`.

| Attribute | Set for |
|---|---|
| `choice` | Choice: the chosen option key |
| `probabilities` | Choice (per key), Score (per level), Multi (per option) |
| `confidence` | Choice and Score: probability of the most likely answer |
| `score` | Score: expected level, 0 = lowest |
| `noul` | Noul: P(yes) |
| `selected` | Multi: options at or above the threshold |
| `abstain` | When `min_confidence` was set |
| `calibrated` | True when a calibrator adjusted the probabilities |
| `agreement` | Council: share of members agreeing with the council |
| `answered_by` | Cascade: the model that gave the final answer |
| `explain` | `explain=True`: probability drop without each state field |
| `stage` | With `.depends()`: the stage (0-based) that answered it |

## Errors

Anything that isn't retried raises `CurvaError`, with `status`, `type` and `message` matching the
[HTTP error](/curva/reference/http-api/#errors). Subclasses let you catch specific cases:

| Class | Status |
|---|---|
| `AuthError` | 401 |
| `InvalidRequestError` | 400, 422 |
| `NotFoundError` | 404 |
| `RateLimitError` | 429 (has `retry_after`) |
| `ModelError` | 502, 504 |

```python
from curva import CurvaError

try:
    client.decide(state, questions)
except CurvaError as e:
    print(e.status, e.type, e.message)
```
