# Python SDK

> The Python SDK (0.9.0): client, continuous models (client.projects) and versions, custom projects (client.custom_models), datasets, runs, evaluations, futures, data helpers, recipes, errors, CLI.

Part of the Endor docs. Index of every page: https://endor.thetokencompany.com/llms.txt. HTML version: https://endor.thetokencompany.com/docs/sdk.

Install the SDK and set your API key:

```bash
pip install endor
export ENDOR_API_KEY=edk_...
export ENDOR_BASE_URL=https://api.endor.thetokencompany.com
```

The SDK needs Python 3.10 or newer. This page is for SDK 0.9.0 and later. In the SDK, continuous models are projects (`client.projects`) and custom projects are custom models (`client.custom_models`); its CHANGELOG lists what changed from 0.8.0. Source: [github.com/TheTokenCompany/endor-python](https://github.com/TheTokenCompany/endor-python). All methods below are synchronous. Methods that end in `_async` are the same for async code.

## EndorClient

The client is the start point for all calls. Create one client and use it again, also across `asyncio.run()` calls: each event loop gets its own connections.

```python
EndorClient(*, api_key: str | None = None, model: str | None = None, retry: RetryPolicy | None = None,
            timeout: float | None = None, headers: Mapping[str, str] | None = None, base_url: str | None = None,
            capture: bool = True, exclude_from_training: bool = False, gzip: bool = True,
            http_client: httpx.Client | None = None, async_http_client: httpx.AsyncClient | None = None, transport: httpx.BaseTransport | None = None,
            async_transport: httpx.AsyncBaseTransport | None = None, report_latency: bool | None = None)
```

- `api_key`: default `ENDOR_API_KEY`.
- `base_url`: default `ENDOR_BASE_URL`, then `https://api.endor.thetokencompany.com` (production). The API of these docs is `https://api.endor.thetokencompany.com`.
- `model`: the default model for `system_one`, for example `tickets`. Default `ENDOR_DEFAULT_MODEL`.
- `timeout`: seconds for each request. Default 30, and 330 for a decision (0.4.1 and later), so the first decision on a model that has to start is answered.
- `retry`: see [Retries](#retries).
- `headers`: extra headers for each request.
- `capture`: if `True`, `runs.create` sends the run settings and the git commit hash.
- `exclude_from_training`: if `True`, this client's decisions stay out of continuous models' learning by default (benchmarks, evaluations).
- `gzip`: if `True`, the SDK compresses large request bodies.
- `report_latency`: if `True`, the SDK tells Endor how long each request took for you (see [Data that the SDK sends](#data-that-the-sdk-sends)). Default `True`, or `False` when `ENDOR_REPORT_LATENCY=0`.

Use it as a context manager to close the connections at the end:

```python
import endor

with endor.EndorClient() as client:
    print(client.whoami().org_id)
```

### system_one

```python
client.system_one(state: JSONContent, questions: Mapping[str, Question], *, model: str | None = None,
                  retry: RetryPolicy | None = None, timeout: float | None = None,
                  extra_headers: Mapping[str, str] | None = None, extra_body: Mapping[str, Any] | None = None,
                  exclude_from_training: bool | None = None,
                  response_model: type[ResponseT] | None = None) -> SystemOneResponse
```

Sends one decision. See [Decisions](https://endor.thetokencompany.com/docs/decisions).

- `questions`: `Noul`, `Choice` or `Score` objects, or dicts in the [data format](https://endor.thetokencompany.com/docs/data-format).
- `model`: a continuous model's `"<name>"` (its production version), `"<name>:preview"` (its newest version, while that isn't in production: otherwise `404 no_preview`) or the name of a model from a custom project, in production. See [Model names](https://endor.thetokencompany.com/docs/decisions#model-names).
- `exclude_from_training`: keep this decision out of the continuous model's learning (default: the client's setting). It is still answered, billed and logged.
- `response_model`: a subclass of `SystemOneResponse` with one field for each question.
- `state` may contain images on base models that read them: `endor.Image` (see [Images](https://endor.thetokencompany.com/docs/decisions#images)).

Returns `SystemOneResponse`: `.id` (the decision's id, to [give feedback](#corrections) on it), `.model`, `.answers`, `.usage`, and `.nouls`, `.choices`, `.scores` by type. Async: `system_one_async`.

### Image

```python
endor.Image.from_path(path: str | Path) -> Image
endor.Image.from_bytes(data: bytes, media_type: str | None = None) -> Image
endor.Image.from_pil(image: PIL.Image.Image, format: str = "PNG") -> Image
```

An image for a decision's state: a dict `{"type": "image", "media_type": ..., "data": <base64>}`, so you can put it anywhere in the state. `from_path` takes the media type from the file's first bytes (PNG, JPEG or WebP). `from_pil` needs Pillow, which the SDK does not install. The API takes at most 8 images per decision, 5 MB each. Images are for decisions only: training data (datasets, datums, evaluation and prediction rows) is text and JSON.

```python
state = {"photo": endor.Image.from_path("shelf.jpg"), "store": "Helsinki 3"}
```

### predict

```python
client.predict(model: str, rows: Iterable[Any], *, progress: bool = True,
               timeout: float | None = None) -> list[dict[str, Answer]]
```

Answers every question of every row, for many rows at once. It sends the rows without their labels as one server evaluation, waits for it and returns each row's answers in the rows' order, as `system_one(...).answers` has them. Nothing is uploaded and nothing is scored. Endor bills it as decisions.

- `model`: the name of a model from a custom project (in production or archived) or a base model's id (`owner/model`).
- `rows`: up to 50,000 [decision rows](https://endor.thetokencompany.com/docs/data-format) (`{"state", "questions"}`), 32 MB in all.
- `progress`: prints a line every 10 seconds while it runs (`evaluation evl_...: 1,200/10,000 rows (12%) · ~2 min left`).
- `timeout`: the most seconds to wait. After it, `TimeoutError`; the evaluation continues.

Errors: `NotFoundError` (404 `unknown_model`) for an unknown model, the others as for `evaluations.create`, and `OperationFailedError` if the evaluation fails. Async: `predict_async`.

```python
answers = client.predict("router-2", [{"state": t, "questions": questions} for t in new_tickets])
print(answers[0]["dept"].choice)
```

### models.list

```python
client.models.list(*, retry: RetryPolicy | None = None, timeout: float | None = None,
                   extra_headers: Mapping[str, str] | None = None) -> ListModelsResponse
```

Returns all names that you can send as `model` (`GET /v1/models`): `<name>` for each continuous model, `<name>:preview` for each one with a preview, and each model from a custom project in production. Each `ModelMetadata` has `name`, `description`, `release_date` and `endor` (the details). Async: `models.list_async`.

```python
print([m.name for m in client.models.list().models])  # ["tickets", "router-2"]
```

### base_models

```python
client.base_models() -> list[BaseModelInfo]
```

Returns the base models (`GET /v1/base_models`): `id`, `params`, `hf_repo`, `hf_revision`, `contract`, `max_options`, `max_rank`, `price_per_mtok_decide`, `price_per_mtok_decide_continuous_learning` (the price in a continuous model) and `price_per_gpu_hour`. You cannot send a base model id alone as `model`: create a continuous model on it, or train a model on it in a custom project.

### whoami

```python
client.whoami() -> WhoAmI
```

Returns the organization and the key of this client: `org_id`, `key_id`, `user_id`, `continuous_learning` (whether your organization has continuous models), `zero_data_retention` (whether it has [zero data retention](https://endor.thetokencompany.com/docs/api#data-retention)) and `limits`: each limit of the organization by name, with your organization's own values (the docs give the defaults).

```python
limits = client.whoami().limits
print(limits["max_active_runs"], limits["max_production_models_per_org"])  # 25 3 by default
```

### balance

```python
client.balance() -> float | None
```

Returns the prepaid balance of the organization in USD (`GET /v1/balance`): the credits bought or granted, minus the usage so far. At $0 or less, paid calls raise `InsufficientBalanceError`. `None` on a server without billing (a local API). See [Billing & limits](https://endor.thetokencompany.com/docs/billing#balance).

```python
print(f"${client.balance():.2f} left")
```

### usage

```python
client.usage(starting_on: datetime, ending_before: datetime, project: str | None = None) -> list[UsageRow]
```

Returns usage and cost for each hour, 14 days maximum. A datetime without a time zone is UTC. New usage can take a few minutes to show. See [Billing & limits](https://endor.thetokencompany.com/docs/billing).

### delete_training_data

```python
client.delete_training_data() -> TrainingDataDeleted
```

Deletes all of your organization's training data now (`DELETE /v1/training_data`): every dataset, and the stored rows of every evaluation. Each evaluation keeps its results, without `rows_url`; one that is still running fails with `training_data_deleted`. Trained models are kept. It can't be undone. Returns how many were deleted: `datasets`, `evaluations`. See [Data retention](https://endor.thetokencompany.com/docs/api#data-retention).

### close

```python
client.close() -> None
```

Closes the HTTP connections. Async: `aclose`.

## Corrections

`client.corrections` gives feedback on past decisions: whether each was right (SDK 0.9.0 and later). Only continuous models learn from it: feedback on a decision of a custom project's model is kept, and doesn't change the model. A decision is its `SystemOneResponse` or its id (`res.id`). How to use it, with examples: [Give feedback on decisions](https://endor.thetokencompany.com/docs/decisions#give-feedback-on-decisions).

### corrections.create

```python
client.corrections.create(request_id: str | SystemOneResponse, questions: Mapping[str, QuestionCorrection], *,
                          comment: str | None = None) -> CorrectionInfo
```

Gives feedback on one decision. For each question you checked: `{"correct": True}`, `{"correct": False, "answer": ...}` or `{"correct": False}`, with `answer` one of the question's options exactly as the decision asked it. Creating it again replaces it.

```python
res = client.system_one(state, questions, model="tickets")
c = client.corrections.create(res, {"department": {"correct": False, "answer": "technical"}, "urgent": {"correct": True}})
print(c.questions["department"].served, c.questions["department"].answer)  # billing technical
```

Returns `CorrectionInfo`: `request_id`, `project`, `questions` (each `correct`, `answer`, `served`), `comment`, `created_at`. Errors: `NotFoundError` (not an answered decision of your organization; Endor records a decision just after it answers, so the SDK tries a correction again for up to 5 seconds while it finds no decision, then raises); `UnprocessableEntityError` with `param` `questions.<name>` (a question the decision did not ask) or `questions.<name>.answer` (not one of the options, or it contradicts `correct`). Async: `create_async`.

### corrections.batch

```python
client.corrections.batch(items: Iterable[Mapping[str, Any]]) -> list[CorrectionInfo]
```

Corrects up to 1,000 decisions at once, each `{"request_id", "questions", "comment"?}`, for example to backfill decisions you checked earlier. If one item fails, none is kept (`param` names the item: `items[i]...`). Like `create`, it tries again for up to 5 seconds while a decision isn't recorded yet. Async: `batch_async`.

### corrections.get

```python
client.corrections.get(request_id: str | SystemOneResponse) -> CorrectionInfo
```

Returns the decision's correction. Errors: `NotFoundError`, also when it has none. Async: `get_async`.

### corrections.delete

```python
client.corrections.delete(request_id: str | SystemOneResponse) -> None
```

Withdraws the decision's correction. Errors: `NotFoundError`. Async: `delete_async`.

## Continuous models

`client.projects` creates and finds continuous models. Each method returns a `Project`. See [Continuous models](https://endor.thetokencompany.com/docs/continuous-learning).

> **Invited organizations only.** Continuous models are only available to invited organizations (email rasmus@thetokencompany.com to ask); `GET /v1/whoami` returns `"continuous_learning": true` once yours has them. Until then, every method here and every `Project` method raises `PermissionDeniedError` (`403 continuous_learning_not_enabled`). Use [custom projects](#custom-projects) instead.

### projects.create

```python
client.projects.create(name: str, base_model: str, description: str | None = None) -> Project
```

Creates a continuous model on `base_model` (an id from `client.base_models()`), chosen once. Its `"<name>"` answers with the base model until the first version.

- `name`: lowercase letters, digits, `.`, `_`, `-`; 63 characters maximum. Continuous models and the models of custom projects share one list of names in the organization.

```python
project = client.projects.create("tickets", base_model="mapika/decider-2b")
```

Errors: `ConflictError` if a continuous model or a saved model has the name; `LimitReachedError` if the organization has 5 continuous models.

### projects.get

```python
client.projects.get(name: str) -> Project
```

Returns the continuous model. Errors: `NotFoundError`.

### projects.get_or_create

```python
client.projects.get_or_create(name: str, base_model: str, description: str | None = None) -> Project
```

Returns the continuous model, and creates it on `base_model` if it does not exist. Raises `ValueError` if the existing one has another base model.

```python
project = client.projects.get_or_create("tickets", base_model="mapika/decider-2b")
```

### projects.list

```python
client.projects.list(limit: int | None = None, offset: int = 0) -> list[Project]
```

Returns your continuous models, newest first. Without `limit`, it returns all of them.

## Project (continuous model)

A `Project` is one continuous model. Get it from `client.projects`. Attributes: `.name`, `.info_` (`ProjectInfo`), `.ref` (`"tickets"`: the `model` that answers with the production version) and `.preview_ref` (`"tickets:preview"` while it has a preview, else `None`).

```python
res = client.system_one(state, questions, model=project.ref)
```

### info

```python
project.info() -> ProjectInfo
```

Reads the continuous model again and returns it: `name`, `description`, `base_model`, `production` (the production version; `None` before the first, when it answers with the base model), `preview` (the newest version while it isn't in production, else `None`), `auto_promote`, `promoted_at`, `versions` (how many) and `created_at`.

### versions

```python
project.versions() -> list[VersionInfo]
```

Every version, newest first. A version is in production or the preview, never both: `name` (`v1`, `v2`, ...), `base_model`, `production`, `preview`, `accuracy` (in percent) and `loss` (from the check it passed when it was trained), `size_bytes`, `created_at`.

### promote

```python
project.promote(version: str) -> ProjectInfo
```

Puts `version` (`"v3"`) in production: `"<name>"` answers with it from now on. Promoting a version older than the newest is a rollback: it turns auto-promote off, so new versions only reach `"<name>:preview"` until you promote again or call `set_auto_promote(True)`. Promoting the production version changes nothing. Errors: `NotFoundError` for a version the continuous model doesn't have.

```python
project.promote("v3")
print(project.info_.production, project.info_.auto_promote)  # v3 False
```

### set_auto_promote

```python
project.set_auto_promote(on: bool) -> ProjectInfo
```

Turns auto-promote on (the default for a new continuous model: the preview goes to production at once, and each new version after it) or off (the production version stays until you promote one).

### learning

```python
project.learning() -> Learning
```

The continuous model's learning (`GET /v1/projects/{project}/learning`): `status` (`learning`, `training`, `waiting`, `up_to_date`, `out_of_credit` or `limit_reached`), `progress` (0 to 1, the way to the next version), `serving`, `trained_at`, `trainings` (the latest 50, newest first: `decisions`, `labels`, `kept`, `version`, `accuracy` in percent (agreement with a frontier model's answers on `checked` held-back answers) with `low` and `high`, `loss`, `against` with `against_accuracy` and `against_loss`, `worse`, `held`: why a kept version stayed the preview) and `drift` (per question: `changed`, `answer_shift`, `confidence_change`). See [Follow it](https://endor.thetokencompany.com/docs/continuous-learning#follow-it).

```python
learning = project.learning()
print(learning.status, learning.progress, learning.serving)  # learning 0.4 tickets:v2
```

### download

```python
project.download(version: str, path: str | os.PathLike, include_optimizer: bool = False) -> list[DownloadedFile]
```

Writes a version's files into the folder `path`, as [custom_models.download](#custom-models-download) does. A version has no optimizer state, so `include_optimizer=True` raises `DownloadError`.

### update

```python
project.update(*, description: str | None = None) -> ProjectInfo
```

Changes the continuous model's description. Its base model never changes; auto-promote changes with `set_auto_promote`.

### delete

```python
project.delete() -> None
```

Deletes the continuous model and its versions: `"<name>"` stops answering, and its name is free again at once. Endor keeps the files for 30 days, then removes them.

## Custom projects

`client.custom_models` creates custom projects, and lists, promotes, archives and downloads the models they save. See [Custom projects](https://endor.thetokencompany.com/docs/training).

### custom_models.create

```python
client.custom_models.create(name: str, base_model: str | None = None, *, run_name: str | None = None,
                            **run_options) -> Run
```

Starts a new custom project: a run on `base_model` whose `run.save_checkpoint()` saves a model called `name`. `run_name` labels the run itself. `run_options` are those of [runs.create](#runs-create) (`rank`, `from_model`, `total_steps`, `wait`, ...). Close the run when you are done: `with client.custom_models.create(...) as run:`. Errors: `ConflictError` if a saved model or a continuous model has the name.

```python
with client.custom_models.create("router-2", base_model="mapika/decider-2b") as run:
    ...  # train
    run.save_checkpoint().result()  # "router-2", archived
```

### custom_models.promote

```python
client.custom_models.promote(name: str, replace: str | None = None) -> CustomModelInfo
```

Puts the model in production: decisions can call it by name (`model="router-2"`). A model in production stays there. It is deploying until Endor has loaded it onto a GPU, and its first decisions may wait for that; `GET /v1/custom_models/{name}` reports it as `serving` (`deploying`, `live` or `failed`), and the dashboard shows Deploying, then Serving traffic. If loading fails, promote it again to retry. Promoting removes the model's TTL: models in production never expire, and archiving doesn't bring the TTL back. When every production slot is taken, it raises `ProductionFullError`, which names the models in production, unless `replace` names one of them: that model is archived in the same step. Errors: `NotFoundError` for an unknown model, or a `replace` that isn't in production.

```python
client.custom_models.promote("router-3", replace="router-2")
```

### custom_models.archive

```python
client.custom_models.archive(name: str) -> CustomModelInfo
```

Takes the model out of production (`POST /v1/custom_models/{name}/demote`): from then on, decisions refuse it (`ModelNotInProductionError`) and its production slot is free.

### custom_models.list

```python
client.custom_models.list(production: bool | None = None, limit: int | None = None, offset: int = 0) -> list[CustomModelInfo]
```

Returns your saved models: the ones in production first, then the archived ones, newest first. `production=True` or `production=False` keeps only one of the two. `CustomModelInfo` has `name`, `base_model`, `state` (`"production"` or `"archived"`; `"saving"` from `get` while its save runs), `production`, `promoted_at`, `serving` (in production: `"deploying"` until a GPU has loaded it, then `"live"`, or `"failed"`; `None` while archived), `serving_error` (why it failed), `step`, `loss` and `accuracy` (0 to 1: the run's training loss and accuracy at the model's step), `has_optimizer`, `size_bytes`, `training_run_id`, `parent_model`, `expires_at` and `created_at`.

### custom_models.get

```python
client.custom_models.get(name: str) -> CustomModelInfo
```

Returns one saved model. While its `save_checkpoint` runs, it returns the model with `state` `"saving"`; other calls that name it raise `ConflictError` (`409 model_not_ready`) until the save completes. Errors: `NotFoundError`.

### custom_models.set_ttl

```python
client.custom_models.set_ttl(name: str, ttl_seconds: int | None) -> CustomModelInfo
```

Deletes an archived model after `ttl_seconds` (1 hour to 10 years). `None` keeps the model. Models in production never expire: `ModelInProductionError`. Promoting a model removes its TTL; set it again after you archive the model.

### custom_models.download

```python
client.custom_models.download(name: str, path: str | os.PathLike, include_optimizer: bool = False) -> list[DownloadedFile]
```

Writes the model's files into the folder `path`, in production or archived (see [Run a model outside Endor](https://endor.thetokencompany.com/docs/training#run-a-model-outside-endor)): `adapter_model.safetensors`, `adapter_config.json`, `endor_manifest.json`, and `readout.safetensors` if the model has one. `include_optimizer=True` adds `optimizer.pt`, which you need only to resume training; a model saved without optimizer state (`has_optimizer` is `False`) then raises `DownloadError` before anything is written. Each file comes straight from storage over a link that expires after 10 minutes, and is checked against its size and SHA-256. `DownloadedFile` has `name`, `path`, `size_bytes` and `sha256`. The links are never returned or logged. Errors: `DownloadError` if a file fails its check (nothing is left behind for it).

### custom_models.delete

```python
client.custom_models.delete(name: str) -> None
```

Deletes an archived model. Its name is free again at once. Endor keeps the files for 30 days, then removes them. A model in production raises `ModelInProductionError`: archive it first.

## Datasets

`client.datasets` manages your datasets: labeled rows to evaluate your trained models and base models.

### datasets.upload

```python
client.datasets.upload(name: str, rows: Iterable[Any]) -> DatasetInfo
```

Uploads [decision rows](https://endor.thetokencompany.com/docs/data-format), 50,000 maximum and 64 MB of JSON in all: about the size of the rows as a `.jsonl` file. The SDK compresses the upload, but the limit counts the uncompressed size. For more, upload several datasets. You do not need a dataset to train: training calls send their datums (see [The loop](https://endor.thetokencompany.com/docs/training#the-loop)). You cannot change a dataset: upload a new one with a different name. To run a pipeline again, use the dataset that is there (`client.datasets.get(name)`) or catch `ConflictError`.

Returns `DatasetInfo`: `name`, `n_rows`, `n_labelled_questions`, `question_types`. Errors: `ConflictError` if the name exists, `UnprocessableEntityError` (`invalid_row`) if a row is not valid, `PayloadTooLargeError` over 64 MB.

### datasets.list

```python
client.datasets.list() -> list[DatasetInfo]
```

Returns all datasets, newest first.

### datasets.get

```python
client.datasets.get(name: str) -> DatasetInfo
```

Returns one dataset. Errors: `NotFoundError`.

### datasets.rows

```python
client.datasets.rows(name: str, page: int = 500) -> Iterator[DecisionRow]
```

Iterates over the rows. `page` is the number of rows in each request.

### datasets.delete

```python
client.datasets.delete(name: str) -> None
```

Deletes the dataset. Its name is free again at once. Evaluations keep their results.

## Evaluations

`client.evaluations` scores a model from a custom project (in production or archived) or a base model on decision rows, on the server.

### evaluations.create

```python
client.evaluations.create(model: str, dataset: str | None = None, run_id: str | None = None, *,
                          rows: Iterable[Any] | None = None) -> APIFuture[Evaluation]
```

Endor bills it as decisions.

- `model`: the name of a model from a custom project, in production or archived, or a base model's id (`owner/model`) (the untuned base, as a baseline).
- `dataset` or `rows`, one of the two. `rows`: up to 50,000 [decision rows](https://endor.thetokencompany.com/docs/data-format), 32 MB in all. Nothing is stored as a dataset. For more, upload the rows as a dataset (64 MB) and evaluate that, or split them over several calls.
- `run_id`: shows the result on this run's page.

A row with labels is scored on its labeled questions. A row without labels is answered on every question and not scored: its answers are in `rows_url` (`client.predict` reads them for you). `results` has `n` (the scored questions), `overall`, `by_type`, `by_question` (accuracy from 0 to 1) and `rows_url`. While it runs, `rows_done` of `rows_total` shows how far it is. See [Evaluations](https://endor.thetokencompany.com/docs/api#evaluations) for the fields, `selective` included.

```python
ev = client.evaluations.create("router-2", "heldout").result()
print(ev.results["overall"]["accuracy"])
```

Errors: `NotFoundError` (404 `unknown_model`) for an unknown model, or for an unknown dataset; `UnprocessableEntityError` for a bad row.

### evaluations.get

```python
client.evaluations.get(evaluation_id: str) -> Evaluation
```

Returns one evaluation (`GET /v1/evaluations/{id}`): `id`, `model`, `dataset`, `training_run_id`, `source` (`server`, or `client` for `run.log_eval`), `status`, `results`, `rows_total`, `rows_done` (how far it is while it runs), `started_at` and `created_at`. It gives `results` a new `rows_url`. Errors: `NotFoundError`.

### evaluations.list

```python
client.evaluations.list(run_id: str | None = None, model: str | None = None) -> list[Evaluation]
```

Returns your evaluations, newest first. Each call gives each evaluation a new `rows_url`: when a link has expired (after 1 hour), list them again, or read one with `client.evaluations.get(evaluation_id)`.

## Runs

`client.runs` starts and finds training runs. Each method returns a `Run`.

### runs.create

```python
client.runs.create(base_model: str | None = None, *, model: str | None = None, rank: int | None = None,
                   alpha: float | None = None, seed: int | None = None, train_attn: bool | None = None,
                   train_mlp: bool | None = None, train_readout: bool | None = None,
                   from_model: str | None = None, include_optimizer: bool = False, name: str | None = None,
                   tags: list[str] | None = None, config: dict[str, Any] | None = None,
                   user_metadata: dict[str, Any] | None = None, total_steps: int | None = None,
                   wandb: bool | None = None, wait: bool = True, progress: bool = True) -> Run
```

Starts a run on a new GPU, on `base_model`. Give `from_model` (a saved model's name) to continue from its weights instead: the run uses that model's base model, and another `base_model` raises `UnprocessableEntityError`. `client.custom_models.create(name, ...)` is the same call with `model=name`.

- `model`: the model name that `run.save_checkpoint()` saves under when it gets none. It must be free: `ConflictError` if a saved model or a continuous model has it.
- `rank`, `alpha`, `train_attn`, `train_mlp`, `train_readout`: LoRA settings. Defaults: 16, 32, `True`, `True`, `False`. With `from_model`, the run uses the settings of that model.
- `include_optimizer`: with `from_model`, also load the optimizer state and the step.
- `name`: the run's own label.
- `total_steps`: the optimizer steps that you plan. The dashboard then shows a progress bar and an ETA.
- `wandb`: log this run to Weights & Biases (`True`/`False`); `None` logs it when the organization has a W&B connection. See [Weights & Biases](https://endor.thetokencompany.com/docs/training#weights-biases).
- `wait`: if `True`, wait until the GPU is ready: seconds when a GPU for the base model is warm, a few minutes when one has to start. If `False`, return immediately; `run.ready` is the future.
- `progress`: if `True`, print one line to stderr once the wait for a GPU passes 10 seconds (`run run_...: waiting for a GPU (starting a cold one can take a few minutes)…`).

Errors: `ConflictError` (`limit_reached`) when the organization's open runs are at its limit (25 by default; `client.whoami().limits["max_active_runs"]` gives yours); `InsufficientBalanceError`.

### runs.get

```python
client.runs.get(run_id: str) -> Run
```

Returns a run that exists, so that you can continue to send calls to it, for example from a new process after your script stopped. `run.info_` is the run as Endor returned it, for example `run.info_.step` to resume from the right step; `run.info()` (a method) reads it again.

The run you get keeps an open run open, as one from `runs.create` does: it sends a heartbeat every minute from a background thread until you close it. Use it in a `with` block, so that the run is closed at the end:

```python
with client.runs.get(run_id) as run:
    print(run.info_.step)  # continue from here
    ...
```

### runs.list

```python
client.runs.list(tag: str | None = None, limit: int | None = None, offset: int = 0) -> list[Run]
```

Returns your runs, newest first.

## Run

A `Run` trains a custom project's model on a GPU that it shares with other runs of its base model. Get it from `client.custom_models.create` or `client.runs.create`. Use it in a `with` block: the block closes the run at the end, also after an error. Attributes: `.id`, `.model` (the name a save without a name uses), `.info_` (`RunInfo`), `.ready` (a future that completes when the GPU is ready), `.next_seq_id`.

```python
with client.custom_models.create("router-2", base_model="mapika/decider-2b") as run:
    steps = endor.Steps()
    for batch in endor.data.batches(train, 16):
        steps.add(run.forward_backward(batch), run.optim_step(learning_rate=1e-4))
    steps.wait()
```

### forward

```python
run.forward(data: Iterable[Datum], loss_fn: LossFn = "cross_entropy") -> APIFuture[ForwardOutput]
```

Calculates the probabilities and the loss with the current adapter. It does not calculate gradients. `loss_fn` is `"cross_entropy"` or `"brier"`.

Returns `ForwardOutput`: `.probabilities` and `.losses` (one item for each datum), `.loss`, `.accuracy`, `.metrics`. Async: `forward_async`.

### forward_backward

```python
run.forward_backward(data: Iterable[Datum], loss_fn: LossFn = "cross_entropy") -> APIFuture[ForwardOutput]
```

Same as `forward`, and adds the gradients. The next `optim_step` applies them. The SDK splits batches of more than 1,024 datums. Async: `forward_backward_async`.

### run.predict

```python
run.predict(rows: Iterable[Any]) -> APIFuture[list[dict[str, Answer]]]
```

Answers decision rows with the current adapter, without saving a model. Returns one `{question name: answer}` for each row, in order, as `client.system_one` answers them (`NoulAnswer`, `ChoiceAnswer`, `ScoreAnswer`). For a saved model, use [client.predict](#predict).

- `rows`: decision rows in any shape that `endor.data.to_row` accepts. Labels, ids and weights are ignored. 64 questions per row at most; text and JSON states only.
- The answers match a decision on the model saved at this point within the usual difference between training and serving (a few hundredths at most in a probability).
- It does not calculate gradients or change the run. It runs in order with the other calls of the run, and Endor bills it as training GPU time.
- The SDK splits lists of more than 1,024 questions and checks every row before it sends one.

Async: `predict_async`. Requires SDK 0.7.0 or later.

### optim_step

```python
run.optim_step(adam_params: AdamParams | None = None, *, learning_rate: float | None = None) -> APIFuture[OptimStepOutput]
```

Applies the gradients with AdamW and sets them to zero. Give the learning rate at each step.

- `adam_params`: `AdamParams(learning_rate=1e-4, beta1=0.9, beta2=0.95, eps=1e-12, weight_decay=0.0, grad_clip_norm=0.0)`.

Returns `OptimStepOutput`: `step`, `grad_norm`, `learning_rate`. Fails with `no_gradients` if no gradients exist. Async: `optim_step_async`.

### save_checkpoint

```python
run.save_checkpoint(name: str | None = None, *, include_optimizer: bool = False, ttl_seconds: int | None = None,
                    user_metadata: dict[str, Any] | None = None) -> APIFuture[str]
```

Saves the adapter as a new model, **archived** until you promote it (`client.custom_models.promote`). Without `name`, it saves under the run's `model` (the name given to `custom_models.create` or `runs.create(model=...)`). The model exists only after the save completes: call `.result()` before you use it. Until then, evaluations and other calls that name it raise `ConflictError` (`409 model_not_ready`).

Each save is a new model, so each name is saved once. A name that a saved model already has fails at once with `ConflictError` (`409 conflict`; `409 name_taken` when a continuous model has it). The run itself is unaffected, but if your code doesn't catch the error, it leaves the `with` block, which closes the run. For checkpoints during a long run, give each one its own name, for example `run.save_checkpoint(f"router-ckpt-{step}", ttl_seconds=86_400)`, so that old ones expire. A deleted model's name can be used again.

- `include_optimizer`: also save the optimizer state, to resume with `include_optimizer=True`.
- `ttl_seconds`: delete the archived model after this time (3,600 to 315,360,000). `None` keeps it.

Returns the model's name. Async: `save_checkpoint_async`.

### close

```python
run.close(*, wait: bool = False, timeout: float | None = None) -> RunInfo
```

Closes the run. Accepted calls finish, then Endor releases the GPU. Progress that you did not save is lost: the SDK warns once when you close with optimizer steps newer than your last save. With `wait=True`, it waits until the run is `closed`. Async: `close_async`.

Until you close it, the run (from `runs.create`, `custom_models.create` or `runs.get`) sends a heartbeat every minute from a background thread, so it stays open however long you wait between calls. If your process ends without closing the run, Endor closes it an hour later.

### info

```python
run.info() -> RunInfo
```

Reads the run again: `status`, `step`, `next_seq_id`, `lora`, `failure` and the other run fields. Progress: `total_steps` (`None` if unknown), `seconds_per_step` (the median of the last 20 steps), `progress` (0 to 1) and `eta_seconds`. Times: `created_at`, `ready_at` (the GPU was ready) and `closed_at`. W&B: `wandb` and `wandb_url`.

### set_total_steps

```python
run.set_total_steps(total_steps: int | None) -> RunInfo
```

Sets the optimizer steps that you plan, for the dashboard's progress bar and ETA. `None` removes it.

### log

```python
run.log(metrics: dict[str, float], step: int | None = None) -> None
```

Adds your metrics to the run (`run.metrics()`, and Weights & Biases when the run logs to it). Without `step`, it uses the current step of the run.

### metrics

```python
run.metrics(keys: Iterable[str] | None = None, since_step: int | None = None) -> list[MetricPoint]
```

Returns the metric points of the run, automatic and yours.

### log_eval

```python
run.log_eval(model: str, results: dict[str, Any], *, step: int | None = None, name: str = "eval") -> Evaluation
```

Records evaluation results that you calculated, for example with `endor.metrics.decision_metrics`. It is free.

## APIFuture

An `APIFuture` is the result of a slow operation. Training calls and `client.evaluations.create` return one immediately.

### result

```python
future.result(timeout: float | None = None) -> T
```

Waits for the operation and returns its result. Errors: `OperationFailedError` if the operation failed or was cancelled; `TimeoutError` after `timeout` seconds (the operation continues). Async: `await future` or `result_async`.

### done

```python
future.done() -> bool
```

Returns `True` if the result is known.

### cancel

```python
future.cancel() -> None
```

Cancels the operation if it did not start. Async: `cancel_async`.

### info

`future.info` is the last state from the server (`FutureInfo`), or `None` before the first poll.

### gather

```python
endor.gather(*futures: APIFuture[Any], timeout: float | None = None) -> list[Any]
```

Waits for all futures and returns their results in order. Async: `endor.gather_async`.

```python
fb, opt = endor.gather(run.forward_backward(batch), run.optim_step(learning_rate=1e-4))
```

### Steps

```python
endor.Steps(in_flight: int = 2)
steps.add(*futures: APIFuture[Any]) -> list[list[Any]]
steps.wait() -> list[list[Any]]
```

Keeps up to `in_flight` training steps sent before their results are read. Thus the GPU starts the next step immediately and does not wait for your round trip between steps.

- `add` takes the futures of one step and returns the results of the steps that it waited for, oldest first, as `gather` returns them: none for the first step, then the results of the step before.
- `wait` returns the results of all steps that are left. Call it after the loop.
- If a step failed, the `add` or `wait` that reads it raises the error.
- A call that you send between two `add` calls, for example `run.forward`, runs after all steps added before it.
- `in_flight=1` waits for each step. `len(steps)` is the number of steps not read yet.

Async: `add_async`, `wait_async`. Requires SDK 0.7.0 or later.

```python
steps = endor.Steps()
for batch in endor.data.batches(train, 16):
    for out, opt in steps.add(run.forward_backward(batch), run.optim_step(learning_rate=1e-4)):
        print(opt.step, out.loss)
for out, opt in steps.wait():
    print(opt.step, out.loss)
```

## Data helpers

Functions in `endor.data` and `endor.metrics`.

```python
endor.data.load_rows(path: str | Path) -> list[DecisionRow]
endor.data.save_rows(path: str | Path, rows: Iterable[Any]) -> int
endor.data.to_row(obj: Any) -> DecisionRow
endor.data.split(rows: Sequence[T], holdout: float = 0.1, seed: int = 0) -> tuple[list[T], list[T]]
endor.data.rows_to_datums(rows: Iterable[Any]) -> list[Datum]
endor.data.row_to_datums(row: Any) -> list[Datum]
endor.data.label_target(question: Question, label: Label) -> Target
endor.data.batches(items: Sequence[T], size: int, *, shuffle: bool = True, seed: int = 0) -> Iterator[list[T]]
endor.metrics.decision_metrics(probs: Sequence[dict[str, float]], targets: Sequence[Target], bins: int = 10) -> dict[str, Any]
```

- `load_rows` reads `.jsonl` or a `.json` array. It accepts all supported row shapes. `save_rows` writes `.jsonl` and returns the number of rows.
- `split` shuffles with `seed` and returns `(train, held_out)`.
- `rows_to_datums` makes one datum for each labeled question. It skips questions without a label.
- `batches` gives lists of `size` items in a shuffled order. The last list can be shorter.
- `decision_metrics` returns `n`, `accuracy`, `nll`, `brier`, `ece`, `mean_confidence` and `selective`.

## Recipes

`endor.recipes.supervised.train` trains a model in one call: hold out, measure the base model, train, measure, save (archived).

```python
supervised.train(cfg: SupervisedConfig, rows: Sequence[Any], eval_rows: Sequence[Any] | None = None,
                 client: EndorClient | None = None) -> SupervisedResult
```

`SupervisedConfig` fields: `model_name=None` (the saved model's name: unique and free; default `"<name or sft>-<timestamp>"`), `base_model="mapika/decider-2b"`, `rank=16`, `learning_rate=1e-4`, `lr_schedule="linear"`, `warmup_steps=10`, `batch_size=16`, `epochs=1`, `loss_fn="cross_entropy"`, `holdout=0.1`, `eval_every=0`, `eval_base=True`, `seed=0`, `name=None`, `tags=[]`, `replay_rows=None`, `replay_per_batch=0`, `progress=True` (print a progress line), `steps_in_flight=2` (steps sent before the results of the step before are read; `1` waits for each step). The recipe sets the run's `total_steps`. `SupervisedResult` has `run_id`, `model`, `base_metrics`, `history` and `final_metrics`.

With the sample [train.jsonl](https://endor.thetokencompany.com/docs/samples/train.jsonl) from [Custom projects](https://endor.thetokencompany.com/docs/training):

```python
import endor
from endor.recipes.supervised import SupervisedConfig, train

rows = endor.data.load_rows("train.jsonl")
cfg = SupervisedConfig(model_name="sft-1", epochs=3, batch_size=8, warmup_steps=2, holdout=0.2)
result = train(cfg, rows)  # measures mapika/decider-2b, trains on it, measures again, saves the model sft-1
print(result.base_metrics["accuracy"], "->", result.final_metrics["accuracy"])
print(result.model)  # "sft-1", archived: client.custom_models.promote("sft-1") to call it
```

`endor.recipes.distill.distill(cfg, unlabeled_rows, eval_rows, client=None)` labels rows with your teacher and trains on its answers. `cfg` is `DistillConfig(supervised, teacher, budget=1.0, seed=0)`. The teacher is an object with `label(rows)`, which returns one `{question name: label}` for each row.

## Reporting problems

When Endor does something you do not expect, when the docs or an error are unclear, or when your integration works, tell the Endor team. Coding agents are welcome to call this. Every report is read.

```python
import endor

endor.user_report("evaluations.create returned 0 rows for a dataset with 200 rows; expected 200", kind="bug")
endor.user_report("Integrated the tickets continuous model; decisions run in production", kind="works")
```

- `kind`: `"bug"` (the default), `"confusing"` or `"works"`.
- It needs your API key (`ENDOR_API_KEY`), like every call.
- It adds the id of the last failed request (or, for `works`, the last request), the SDK and Python versions, and the last error's status and code. Pass `request_id=` or `context=` to set them. It never sends your API key or request bodies.
- `client.user_report(...)` and `endor.user_report_async(...)` do the same; the CLI has `endor user-report "message" --kind bug`.
- The last line of every `EndorError`'s text says how to report it.

## Errors

All errors are subclasses of `endor.EndorError`. An API error is a subclass of `endor.APIError`, with `.status`, `.code`, `.param`, `.message` and `.request_id`. The last line of `str(error)` says how to [report](#reporting-problems) it.

| Exception | Status and code |
|---|---|
| `BadRequestError` | 400 |
| `AuthenticationError` | 401 |
| `InsufficientBalanceError` | 402 `insufficient_balance` |
| `PermissionDeniedError` | 403, for example `continuous_learning_not_enabled`: a call to a continuous model from an organization that isn't invited to continuous models. Use custom projects. |
| `NotFoundError` | 404 |
| `NoPreviewError` (a `NotFoundError`) | 404 `no_preview`: `"<name>:preview"` while the continuous model has no preview. Call `"<name>"`. |
| `VersionNotCallableError` (a `NotFoundError`) | 404 `version_not_callable`: `"<name>:v3"` names a version of a continuous model that is neither in production nor the preview. Promote it (`project.promote("v3")`) to call it. |
| `ConflictError` | 409, for example `conflict` (the name exists) or `model_not_ready` (the model's `save_checkpoint` is not done yet) |
| `LimitReachedError` (a `ConflictError`) | 409 `limit_reached`: a count limit is reached (`client.whoami().limits`). It is not retried. |
| `ProductionFullError` (a `LimitReachedError`) | 409 `production_full`: every production slot for models from custom projects is taken. Promote with `replace`, or archive one first. |
| `ModelNotInProductionError` (a `ConflictError`) | 409 `model_not_in_production`: a decision named an archived model. Promote it first. |
| `ModelInProductionError` (a `ConflictError`) | 409 `model_in_production`: deleting a model in production, or giving it a TTL. Archive it first. |
| `PayloadTooLargeError` | 413 |
| `UnprocessableEntityError` | 422 |
| `RateLimitError` | 429 |
| `InternalServerError` | 500 |
| `OverloadedError` | 529 |

Other errors:

- `OperationFailedError`: `future.result()` raises it if the operation failed. `.code` is for example `oom`, `no_gradients` or `trainer_lost`.
- `APIConnectionError`, `APITimeoutError`: network errors.
- `DownloadError`: `custom_models.download` or `project.download` could not fetch a file, or the file failed its size or SHA-256 check.
- `ResponseValidationError` (an `APIError`): a successful response does not have the expected shape. Every method raises it, naming the endpoint and the field.

```python
import endor

client = endor.EndorClient()
try:
    client.projects.get("missing")
except endor.NotFoundError as e:
    print(e.code, e.request_id)
```

## Retries

The SDK retries connection errors, timeouts, 408, 429 and 5xx. It uses exponential backoff and `Retry-After`. It does not retry `limit_reached` and `insufficient_balance`. A retry never runs an operation two times: create calls send an `Idempotency-Key`, and training calls send a sequence number.

```python
RetryPolicy(max_retries: int = 2, backoff_initial: float = 0.5, backoff_max: float = 5.0,
            backoff_jitter: float = 0.25, http_statuses: frozenset[int] = {408, 429, 500-599},
            respect_retry_after: bool = True, api_connection_error: bool = True,
            api_timeout_error: bool = True, timeout: float | None = 60.0)
```

`timeout` is the total time for all attempts of one call: 60 seconds by default, 660 for a decision (0.4.1 and later), so a `503 warming_up` is retried. `max_retries=0` turns retries off.

```python
import endor

client = endor.EndorClient(retry=endor.RetryPolicy(max_retries=5, timeout=120))
```

## Data that the SDK sends

Each request has these headers:

- `User-Agent: endor-python/<version> (python <version>; <os>; <cpu>)`, with `; cli` for the `endor` command.
- `X-Endor-SDK: endor-python`, `X-Endor-SDK-Version`, `X-Endor-Runtime` and `X-Endor-SDK-Interface` (`python` or `cli`).
- `X-Endor-SDK-Method` (for example `run.forward_backward`), `X-Endor-SDK-Recipe` (in a recipe), `X-Endor-Client-Request-Id` (the same for all retries of a call) and `X-Endor-Retry-Count` (on retries).
- `X-Endor-Client-Latency: <request id>=<ms>`: how long the previous request took from when the SDK sent it until it read the response, network and connection set-up included. It is sent once, with the next request, and adds no wait. The dashboard shows it next to the time Endor took. Turn it off with `EndorClient(report_latency=False)` or `ENDOR_REPORT_LATENCY=0`.

`runs.create` also sends the run settings. If `capture=True`, it sends your git commit hash and a flag for local changes. It never sends file contents.

For each request, Endor records the request id, the organization, the key, the route, the status, the duration, the time the SDK reported for it and the headers above (200 characters maximum each). Endor also stores the request body and a JSON response body of 256 KB or less. Endor keeps them until you ask it to delete them: email rasmus@thetokencompany.com. With [zero data retention](https://endor.thetokencompany.com/docs/api#data-retention), Endor stores no bodies. Endor never stores the secret API key. You cannot replace the headers above with `headers=`.

## CLI

The `endor` command does all operations except training:

```text
endor whoami
endor base-models
endor projects list | create NAME --base-model BASE | delete NAME
endor projects versions NAME | promote NAME VERSION | auto-promote NAME on|off
endor custom-models list [--production | --archived] | info NAME | promote NAME [--replace NAME] | archive NAME
endor custom-models download NAME [-o DIR] [--include-optimizer] | set-ttl NAME SECONDS|none | delete NAME
endor datasets list | upload NAME FILE | delete NAME
endor runs list | show RUN_ID | close RUN_ID
endor eval MODEL DATASET
endor usage --start 2026-10-01 --end 2026-10-06 [--project P] [--csv]
endor user-report MESSAGE [--kind bug|confusing|works] [--request-id REQ]
```

In `eval`, `MODEL` is the name of a model from a custom project, or a base model's id (`owner/model`). `endor whoami` also shows the balance, `continuous_learning` and the limits. Each command accepts `-f json` (or `--format json`), before or after the command: `endor whoami -f json`.

## Other pages

- [Overview](https://endor.thetokencompany.com/docs/index.md): What Endor does: you train decision models on your labeled data in custom projects with the SDK, Endor runs the GPUs, and you call them by name. Continuous models are for invited organizations.
- [Quickstart](https://endor.thetokencompany.com/docs/quickstart.md): Start here: install the SDK, measure base models on your data, train a model in a custom project, evaluate it, promote it and call it.
- [Core concepts](https://endor.thetokencompany.com/docs/concepts.md): Organizations, continuous models and their production and preview versions, names, base models, custom projects, datasets, runs, evaluations and futures.
- [Custom projects](https://endor.thetokencompany.com/docs/training.md): Custom projects (custom_models in the SDK and API): train a model with the SDK, save, promote to production, call, download; the training loop in detail.
- [Continuous models](https://endor.thetokencompany.com/docs/continuous-learning.md): Continuous models (projects in the SDK and API), only available to invited organizations: create one, call its production version or its preview, auto-promote, promote and roll back versions, feedback, price.
- [Decisions](https://endor.thetokencompany.com/docs/decisions.md): Decisions with the SDK and over HTTP, model names, giving feedback on them, TypeSafe clients, cold starts, errors.
- [Base models](https://endor.thetokencompany.com/docs/base-models.md): The 18 base models: limits, rules, prices and cold starts.
- [Billing & limits](https://endor.thetokencompany.com/docs/billing.md): Prices, the prepaid balance, usage and limits.
- [Data format](https://endor.thetokencompany.com/docs/data-format.md): Decision rows, question types, hard and soft labels, datums and limits: the data for custom projects.
- [API reference](https://endor.thetokencompany.com/docs/api.md): Each /v1 endpoint: method, path, body fields, response fields and errors.
- [Updates](https://endor.thetokencompany.com/docs/updates.md): Changes to the API and SDK, newest first, and when old names and endpoints stop working.
- [Index](https://endor.thetokencompany.com/llms.txt): every page and the API schema.
