# Decisions

> Decisions with the SDK and over HTTP, model names, giving feedback on them, TypeSafe clients, cold starts, errors.

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

The decision API is the [TypeSafe API](https://docs.typesafe.ai): `POST /v1/systemone` and `GET /v1/models`. A decision names a continuous model, a model from a custom project, or a base model. A continuous model learns from its decisions.

## Model names

| `model` | The model that answers |
|---|---|
| `tickets` | A continuous model's production version, or its base model before the first version. |
| `tickets:preview` | A continuous model's newest version while it isn't in production (with auto-promote off); otherwise `404 no_preview`. |
| `tickets:v4` | That version, while it is in production or the preview: the name a response's `model` gives. Any other version: `404 version_not_callable`. |
| `router-2` | A model from a [custom project](https://endor.thetokencompany.com/docs/training), while it is in production. |
| `mapika/decider-2b` | A [base model](https://endor.thetokencompany.com/docs/base-models), by its id: `owner/model`. |

The response's `model` names what answered: the version, for example `tickets:v4` (`tickets` while it answers with its base model), the custom project's model, or the base model.

- The name a response gives, for example `tickets:v4`, can be called while that version is in production or the preview. It stops answering once another version replaces it: to follow new versions, call `tickets` (or `tickets:preview`).
- An older version, for example `tickets:v3`, fails with `404 version_not_callable`. Promote it to call it (see [Promote a version](https://endor.thetokencompany.com/docs/continuous-learning#promote-a-version)).
- An archived model from a custom project fails with `409 model_not_in_production`. Promote it first.

> **Continuous models are only available to invited organizations.** To ask for an invitation, email rasmus@thetokencompany.com. Until then, a decision that names a continuous model fails with `403 continuous_learning_not_enabled`. Call a model from a [custom project](https://endor.thetokencompany.com/docs/training) instead.

`GET /v1/models` lists your models that your API key can send as `model`: `<name>` for each continuous model, `<name>:preview` for each one with a preview (with continuous models enabled), and each model from a custom project in production. `GET /v1/base_models` lists the base models.

### Call a base model directly

Any organization can call a base model by its id, without training it first:

```python
res = client.system_one(
    {"body": "I was billed twice."},
    {"urgent": Noul(instructions="Does the customer need an answer today?")},
    model="mapika/decider-2b",
)
```

It costs the base model's price per 1M input tokens, the price on [Base models](https://endor.thetokencompany.com/docs/base-models). A base model called directly doesn't learn from its decisions: create a [continuous model](https://endor.thetokencompany.com/docs/continuous-learning) on it for that, or [train a model](https://endor.thetokencompany.com/docs/training) on it.

## SDK

```python
import endor
from endor import Choice, Noul, Score

client = endor.EndorClient()

res = client.system_one(
    {"body": "I was billed two times for my March invoice."},
    {
        "department": Choice(instructions="Which team must handle `body`?",
                             criteria={"billing": "Payments, refunds", "technical": "Bugs, outages"}),
        "urgent": Noul(instructions="Does the customer need an answer today?"),
        "frustration": Score(instructions="How frustrated is the customer?", criteria=["Calm", "Annoyed", "Angry"]),
    },
    model="tickets",
)

print(res.choices["department"].choice)    # "billing"
print(res.nouls["urgent"].noul)            # probability of yes
print(res.scores["frustration"].score)     # expected level
print(res.usage.input_tokens)              # the billed tokens
```

For typed answers, give a `response_model`:

```python
import endor
from endor import ChoiceAnswer, Noul, NoulAnswer, Choice, SystemOneResponse

class Triage(SystemOneResponse):
    department: ChoiceAnswer
    urgent: NoulAnswer

client = endor.EndorClient()
triage = client.system_one(
    {"body": "I was billed two times."},
    {"department": Choice(instructions="Which team must handle `body`?", criteria={"billing": None, "technical": None}),
     "urgent": Noul(instructions="Does the customer need an answer today?")},
    model="tickets",
    response_model=Triage,
)
print(triage.department.choice, triage.urgent.noul)
```

In async code, use `await client.system_one_async(...)`.

For many rows at once (a backfill, a benchmark), `client.predict` sends them to a model from a custom project (in production or archived) or a base model as one server evaluation, and returns each row's answers, in order, as `res.answers` has them. Up to 50,000 rows and 32 MB per call; the price is the same as one decision per row. See [predict](https://endor.thetokencompany.com/docs/sdk#predict).

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

To keep decisions out of [continuous learning](https://endor.thetokencompany.com/docs/continuous-learning), for example in a benchmark, pass `exclude_from_training=True` to `system_one`, or to `EndorClient` for all its decisions. Over HTTP, send `"exclude_from_training": true` in the body.

## Question types

Each question has a `type` and these fields:

| `type` | `instructions` | `criteria` | Answer |
|---|---|---|---|
| `noul` | Text or JSON | Optional: `{"true": "...", "false": "..."}` | `noul`: the probability of true |
| `choice` | Text or JSON | Required: an **object**, option id to description (or `null`): `{"billing": "Payments", "technical": null}` | `choice`, `probabilities`, `confidence` |
| `score` | Text or JSON | Required: a **list** of level descriptions, low to high, 2 to 10 items: `["Calm", "Annoyed", "Angry"]` | `score` (expected level), `probabilities`, `legend`, `confidence` |

A score's `criteria` are the **levels of one scale**, from the lowest to the highest, not a list of things to check. Each item describes one level. For "How Finnish is this name?", use `["Clearly not Finnish", "Possibly Finnish", "Unmistakably Finnish"]`. The answer `score` is the expected level: `0` is the first item, `n - 1` the last, so a higher `score` means nearer the last item.

`mapika/decider-2b` needs `instructions` on each question; a `noul` can give `criteria` (true and false) instead. The option and level limits of each base model are at `GET /v1/base_models` (`max_options`).

```json
"questions": {
  "urgent":      {"type": "noul", "instructions": "Does the customer need an answer today?"},
  "department":  {"type": "choice", "instructions": "Which team must handle this?",
                  "criteria": {"billing": "Payments, refunds", "technical": "Bugs, outages"}},
  "frustration": {"type": "score", "instructions": "How frustrated is the customer?",
                  "criteria": ["Calm", "Annoyed", "Angry"]}
}
```

## Images

Three base models read images: `autotrust/gev-26b`, `cloudflare/clef-27b` and `cloudflare/clef-flash-9b` (`modalities` in `GET /v1/base_models` includes `image`). Put an image anywhere in the state: as the whole state, as an item of a list, or as a value of an object.

```json
{"type": "image", "media_type": "image/png", "data": "<the file's bytes in base64>"}
```

In the SDK, `endor.Image` builds this object:

```python
import endor
from endor import Choice

client = endor.EndorClient()
res = client.system_one(
    {"screenshot": endor.Image.from_path("checkout.png"), "goal": "Pay for the order"},
    {"button": Choice(instructions="Which button must the user click next?",
                      criteria={"pay": "The green Pay button", "back": "The grey Back button"})},
    model="shop",  # a continuous model on a base model that reads images
)
```

Over HTTP, send the base64 of the file in `data`:

```bash
IMG=$(base64 < checkout.png | tr -d '\n')
curl https://api.endor.thetokencompany.com/v1/systemone \
  -H "Authorization: Bearer $ENDOR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "shop",
       "state": {"screenshot": {"type": "image", "media_type": "image/png", "data": "'"$IMG"'"},
                 "goal": "Pay for the order"},
       "questions": {"pay": {"type": "noul", "instructions": "Is the Pay button visible?"}}}'
```

- Formats: PNG, JPEG and WebP (`image/png`, `image/jpeg`, `image/webp`). Send the bytes in standard base64, without a `data:` prefix. Image URLs aren't accepted yet: an image with a `url`, or any object with `"type": "image"` and no `data`, fails with `422 invalid_input`.
- Limits: 8 images per decision, 5 MB per image (before base64). The 256 KB state limit counts the state without its images. The request body may be 1 MB plus room for 8 images of 5 MB in base64, about 54 MB in all.
- Each question reads every image of the state. The image tokens count as input tokens, so they are billed like text (see [Base models](https://endor.thetokencompany.com/docs/base-models#images) for the tokens per image).
- Endor keeps the images of each decision in its log, until you ask it to delete them (email rasmus@thetokencompany.com). An image that you send again is stored only once. With [zero data retention](https://endor.thetokencompany.com/docs/api#data-retention), Endor stores no images.
- Training data (datums and datasets) cannot contain images yet.

## HTTP

Keep the key in the `ENDOR_API_KEY` environment variable and refer to it, as below. Do not write the key itself into a command or a file.

```bash
curl https://api.endor.thetokencompany.com/v1/systemone \
  -H "Authorization: Bearer $ENDOR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "tickets",
       "state": {"body": "I was billed two times."},
       "questions": {"urgent": {"type": "noul", "instructions": "Does the customer need an answer today?"}}}'
```

```json
{"id": "req_7Hq2LmXo9TbVc4RkWs1N", "model": "tickets:v4", "answers": {"urgent": {"type": "noul", "noul": 0.83}}, "usage": {"input_tokens": 41, "output_tokens": 0}}
```

`id` is the decision's id (also in the `X-Request-Id` header). The first call can take a few minutes while the model starts (see [Cold starts](#cold-starts)).

A response can also carry `warnings`, only when there is something to say. Today there is one: `{"code": "state_truncated", "question": "urgent", "message": "..."}` when the state was longer than the base model reads for that question (`max_question_tokens` in `GET /v1/base_models`) and the base read its start, as clef-27b and clef-flash-9b do. The answer is about that part: put what matters first, or shorten the state. Other base models refuse such a question with `422 context_too_long`.

## Give feedback on decisions

When you know whether a decision was right, you can tell Endor, and your continuous model learns from it. It is optional: a continuous model learns from its decisions alone. Every decision's response has an `id`: send your feedback with it.

For each question someone checked, send one of:

| The decision was | Send |
|---|---|
| Right | `{"correct": true}` |
| Wrong, and you know the right answer | `{"correct": false, "answer": "technical"}` |
| Wrong, and you don't know the right answer | `{"correct": false}` |

In the SDK and the API, feedback is a correction (`client.corrections`, `POST /v1/corrections`):

```python
res = client.system_one(state, questions, model="tickets")
# later, once you know
client.corrections.create(res, {
    "department": {"correct": False, "answer": "technical"},
    "urgent": {"correct": True},
})
```

```bash
curl -X POST https://api.endor.thetokencompany.com/v1/corrections \
  -H "Authorization: Bearer $ENDOR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"request_id": "req_7Hq2LmXo9TbVc4RkWs1N", "questions": {"department": {"correct": false, "answer": "technical"}, "urgent": {"correct": true}}}'
```

**The right answer must be one of the options you asked with, written exactly as you sent it.** For a choice, one of its option names with the same spelling and case (`"billing"`, not `"Billing"`). For a yes/no question (`noul`), `true` or `false`. For a score, the level's number (`0` is the first level). If none of the options fits, say it was wrong without an answer. Anything else is refused with `422 invalid_input`, and the message lists the options.

For a yes/no question, or any question with two options, "wrong" alone is enough: Endor fills in the other answer.

### More

- Sending feedback on the same decision again replaces it. Questions you leave out are no longer corrected.
- `client.corrections.get(res)` reads it, and `client.corrections.delete(res)` withdraws it.
- `client.corrections.batch([...])` sends up to 1,000 at once, for example for decisions you checked earlier. If one fails, none is kept.
- Endor records a decision a moment after it answers. Feedback sent right away can get `404 not_found`: send it again a few seconds later.
- Feedback is free. Every decision takes it, but only continuous models learn from it. Feedback on a decision of a custom project's model is kept, and doesn't change the model: to improve it, train it again.
- If your client doesn't show the response's `id`, the same value is in the `X-Request-Id` header.
- Every field and error: [API reference](https://endor.thetokencompany.com/docs/api#corrections) and [Python SDK](https://endor.thetokencompany.com/docs/sdk#corrections).

## TypeSafe clients

An unchanged TypeSafe client works with Endor:

1. Set its `base_url` to `https://api.endor.thetokencompany.com`.
2. Set its API key to your Endor key.
3. Set `model` to an Endor model id, for example `tickets`.

`GET /v1/models` gives TypeSafe's `name`, `description` and `release_date` for each name that you can send as `model`. It also gives an `endor` object with Endor's details, such as the base model. TypeSafe clients ignore this object. The base models with their prices and limits are at `GET /v1/base_models`.

```python
from typesafe_sdk import TypeSafeClient

client = TypeSafeClient(api_key="edk_...", base_url="https://api.endor.thetokencompany.com", model="tickets")
print([m.name for m in client.models.list().models])  # ["tickets", "router-2"]
```

## Loading

A version or a custom project's model that was not called for a while can take a moment longer on its first decision, usually a second or a few, while Endor loads it. Decisions after it are fast.

## Cold starts

The decision servers of a base model shut down after a period without decisions. The next decision on that base model (a continuous model on it or a model trained on it) starts one again. That decision waits for it, usually 1 to 3 minutes, and then answers normally. Decisions after it are fast again. This mostly affects base models that are rarely used.

- Give the first decision enough time: a client timeout of 5.5 minutes covers a cold start. The SDK (0.4.1 and later) waits that long for a decision by default.
- If a decision server does not answer within 5 minutes, the request fails with `503 warming_up` and a `Retry-After` header. Retry after that many seconds. The server is still starting, so the retry is usually fast.
- To avoid the wait, send one decision a few minutes before you need fast answers.

## Errors

| Status | Code | Cause |
|---|---|---|
| 400 | `invalid_input` | The body isn't valid JSON. The message says where. |
| 402 | `insufficient_balance` | The balance is $0 or less. Add credits. |
| 403 | `continuous_learning_not_enabled` | `model` names a continuous model, and continuous models are only available to invited organizations, which yours isn't yet. Call a model from a [custom project](https://endor.thetokencompany.com/docs/training). |
| 404 | `unknown_model` | No continuous model, model from a custom project or base model has this name. A base model is called as `owner/model`. |
| 404 | `version_not_callable` | `<name>:v3` names a version of a continuous model that is neither in production nor the preview. Promote the version first, or call `<name>`. |
| 404 | `no_preview` | `<name>:preview` while the newest version is in production (usually so with auto-promote on). Call `<name>`. |
| 413 | `payload_too_large` | The request body is too large: 1 MB plus room for 8 images of 5 MB in base64, about 54 MB in all. |
| 409 | `model_not_in_production` | The model is archived. Promote it: `client.custom_models.promote("router-2")`. |
| 409 | `model_not_ready` | The model's save is not done yet. Wait for its `save_checkpoint` future (`.result()`), then try again. |
| 409 | `no_base_model` | The base model is no longer served. `GET /v1/base_models` lists the base models. |
| 409 | `no_base_model` | The base model is no longer served. `GET /v1/base_models` lists the base models. |
| 422 | `invalid_options` | A question does not fit the base model. |
| 422 | `invalid_input` | The request is valid JSON but does not match the schema, or an image is not valid (for example `param` `state.screenshot.data`). `param` gives the field, and the message what to send. |
| 422 | `context_too_long` | A question, with the state, is longer than the base model reads (`max_question_tokens` in `GET /v1/base_models`). Shorten the state or the question. |
| 422 | `unsupported_modality` | The state has an image, but the base model reads only text. `param` gives the image. |
| 429 | `rate_limited` | Too many requests. Wait for `Retry-After`. |
| 503 | `warming_up` | The base model's decision servers are starting after being idle (see [Cold starts](#cold-starts)). Wait for `Retry-After`. |
| 529 | `overloaded` | The decision servers are busy. Try again. |

The SDK retries `429` and `529` automatically.

## 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.
- [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.
- [Python SDK](https://endor.thetokencompany.com/docs/sdk.md): 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.
- [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.
