# Python SDK

> The elefork package.

```sh
pip install elefork            # SDK and CLI, no dependencies
pip install 'elefork[mcp,sql]' # plus the MCP server and SQL helpers
```

```python
from elefork import Client, ApiError, OperationFailed
c = Client(url=None, token=None, timeout=60.0, retries=None, *, retry_budget=60.0, max_retry_after=60.0)
# url/token default to ELEFORK_URL / ELEFORK_TOKEN
```

Every mutating call sends an `Idempotency-Key`. GETs and calls with an `Idempotency-Key` are retried on connection errors, 500/502/503/504 and 409 `request_in_progress`; 429 only when the server sends `Retry-After`. Other errors, such as 501 `not_implemented`, raise at once. `Retry-After` is honored (capped at `max_retry_after` seconds). Retries stop once `retry_budget` seconds have passed since the first failure; `retries`, if set, also caps their number. Calls that start an [operation](/docs/concepts/operations/) wait for it by default (`wait=True`) and raise `OperationFailed` if it fails. Pass `wait=False` to get the operation back immediately.

## Projects and templates

| Method | Returns |
|---|---|
| `list_templates()` | `list[dict]` |
| `create_project(name, default_size=None, *, template=None, default_branch=True, wait=True)` | project; `default_branch_id` is its running `main` branch (none with `default_branch=False`) |
| `list_projects()`, `get_project(id)`, `project_by_name(name_or_id)` | project(s) |

## Branches

| Method | Notes |
|---|---|
| `create_branches(project, *, template=None, checkpoint=None, parent=None, name=None, count=1, ttl_seconds=None, size=None, durability=None, pause_policy=None, wait=True)` | Exactly one of `template`, `checkpoint`, `parent` (or `parent` + `checkpoint`). `pause_policy`: `"idle"` (default) or `"never"`. Returns the branches once running. |
| `update_branch(id, *, pause_policy=None)`, `set_pause_policy(id, policy)` | Change a branch's settings; returns the branch. |
| `create_branch(project, **kw)` | `create_branches` with `count=1`; returns one branch. |
| `get_branch(id)`, `list_branches(project)` | |
| `delete_branch(id, wait=True)` | |
| `pause(id)`, `wake(id)` | `wake` returns `None` if already running. |
| `reset(id, checkpoint)` | Returns the operation; `result["generation"]` is the new generation. |

## Checkpoints

| Method | Notes |
|---|---|
| `checkpoint(branch_id, name="")` | Returns the checkpoint once `ready`. |
| `list_checkpoints(branch_id)` | |

## Connecting

| Method | Notes |
|---|---|
| `credentials(branch_id, role="postgres", database="postgres", ttl_seconds=3600)` | Gateway credentials; use `["uri"]` with any libpq-based driver. |
| `revoke_credentials(branch_id)` | Invalidates all tokens issued so far. |

## Data and monitoring

These go through the control plane, so they need no driver. SQL runs as `role` through the gateway, like any client.

| Method | Notes |
|---|---|
| `sql(branch_id, sql, database="postgres", role="postgres", max_rows=None)` | `{results: [{columns, rows, command_tag, row_count, truncated}], duration_ms, error?}`; values are Postgres text, `None` is NULL; a Postgres error is returned in `error`. The script runs as one transaction: after an error, the statements listed in `results` were rolled back (except ones before an explicit `COMMIT`; `elefork.client.sql_persisted(run)` tells which). Never retried. |
| `databases(branch_id)`, `schema(branch_id, database="postgres")` | Database names; schemas with tables, columns and primary keys |
| `rows(branch_id, table, schema="public", limit=100, offset=0, order_by=None, desc=False)` | One page plus `total` |
| `metrics(branch_id, range="1h")` | Sampled Postgres metrics (`15m`, `1h`, `6h`, `1d`); `gaps` are paused periods |
| `activity(branch_id)` | Live client sessions; does not wake a paused branch |

## Datasets, tasks and episodes

See [Scored evaluations](/docs/guides/evaluations/).

| Method | Notes |
|---|---|
| `upload_dataset(project, name, data, fmt="sql", table=None)` | `data` is bytes: a plain-format `pg_dump`, or CSV with a header (`fmt="csv"`, `table` required). |
| `build_dataset(id, base_template, wait=True)` | Builds an org template named after the dataset; raises `ApiError` if the build fails. |
| `list_datasets(project)`, `get_dataset(id)` | |
| `create_task(project, name, template, rules, *, allow=None, role="owner", seed=0, wait=True)` | A new version each call; returns once the baseline is ready. |
| `list_tasks(project)`, `get_task(id)` | |
| `start_episodes(task_id, count=1, size=None, ttl_seconds=None, wait=True)` | Items with `episode`, `branch`, `operation`; branches are running on return. |
| `start_episode(task_id, **kw)` | One item. |
| `seal_episode(id, wait=True)` | Returns the episode once `scored`, `tampered` or `failed`. |
| `get_episode(id)`, `list_episodes(task_id)` | |

## Operations and errors

| Method / class | Notes |
|---|---|
| `get_operation(id, wait=0)`, `wait_operation(op_or_id, timeout=120)` | |
| `ApiError` | `.status`, `.code`, `.message` |
| `OperationFailed` | `.operation` (the failed operation) |
