# System One

Ask typed questions of a case on the `/v1` address; get each answer with a score.

1. [Pick a System One model](#1-pick-a-system-one-model).
2. [Send your questions](#2-send-your-questions).
3. [Read each answer](#3-read-each-answer).

## 1. Pick a System One model

A System One model judges one case against your questions and answers each one under the name you gave it. It takes the same case, questions and answers as [Classification](/docs/classification), on the same meter, at `/v1/systemone` instead of `/alpha/decisions`.

Copy its model ID from its page in *Models*. The ID is `lab/model`, such as `typesafe/jev-1.14`; the bare name, `jev-1.14`, reaches the same model.

<div class="buttons">
<a href="/models?modality=decision" class="button primary">Browse System One models</a>
</div>

## 2. Send your questions

Yacine runs **Souk Bot**, which answers the customers of a clothing shop in Oran. Before a message reaches a person, Souk Bot asks System One two questions about it: is it a defect, and which team owns it. Each question goes under a name Yacine picks: `is_bug` and `team`.

Send the case in `state` and the questions in `questions` to `POST /v1/systemone`.

<div class="watch-out">
<p>A chat library cannot call this route. Send it with any HTTP client, as the samples do.</p>
</div>

```python
import json
import os
import urllib.request

API_KEY = os.environ["OPENDUNES_API_KEY"]
ADDRESS = "https://opendunes.com/v1/systemone"
MODEL = "typesafe/jev-1.14"
TICKET = "Edahabia payment went through. Order still pending since yesterday."

request_body = {
    "model": MODEL,
    "state": {"ticket": TICKET},
    "questions": {
        "is_bug": {
            "type": "noul",
            "instructions": "Is the customer reporting a defect?",
            "criteria": {
                "true": "The customer describes broken behaviour.",
                "false": "The customer is asking a question.",
            },
        },
        "team": {
            "type": "choice",
            "instructions": "Which team owns this ticket?",
            "criteria": {
                "payments": "Checkout, billing or payment processing.",
                "delivery": "Pickup, transit or hand-over.",
            },
        },
    },
}

request = urllib.request.Request(
    ADDRESS,
    data=json.dumps(request_body).encode(),
    headers={
        "Authorization": "Bearer " + API_KEY,
        "Content-Type": "application/json",
    },
)
with urllib.request.urlopen(request) as response:
    answer = json.load(response)

print(answer["answers"]["team"]["choice"], answer["usage"]["cost"])
```

```javascript
const API_KEY = process.env.OPENDUNES_API_KEY;
const ADDRESS = "https://opendunes.com/v1/systemone";
const MODEL = "typesafe/jev-1.14";
const TICKET =
  "Edahabia payment went through. Order still pending since yesterday.";

const response = await fetch(ADDRESS, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: MODEL,
    state: { ticket: TICKET },
    questions: {
      is_bug: {
        type: "noul",
        instructions: "Is the customer reporting a defect?",
        criteria: {
          true: "The customer describes broken behaviour.",
          false: "The customer is asking a question.",
        },
      },
      team: {
        type: "choice",
        instructions: "Which team owns this ticket?",
        criteria: {
          payments: "Checkout, billing or payment processing.",
          delivery: "Pickup, transit or hand-over.",
        },
      },
    },
  }),
});
const answer = await response.json();

console.log(answer.answers.team.choice, answer.usage.cost);
```

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

const (
	address = "https://opendunes.com/v1/systemone"
	model   = "typesafe/jev-1.14"
	ticket  = "Edahabia payment went through. " +
		"Order still pending since yesterday."
)

func main() {
	apiKey := os.Getenv("OPENDUNES_API_KEY")

	body, err := json.Marshal(map[string]any{
		"model": model,
		"state": map[string]string{"ticket": ticket},
		"questions": map[string]any{
			"is_bug": map[string]any{
				"type":         "noul",
				"instructions": "Is the customer reporting a defect?",
				"criteria": map[string]string{
					"true":  "The customer describes broken behaviour.",
					"false": "The customer is asking a question.",
				},
			},
			"team": map[string]any{
				"type":         "choice",
				"instructions": "Which team owns this ticket?",
				"criteria": map[string]string{
					"payments": "Checkout, billing or payment processing.",
					"delivery": "Pickup, transit or hand-over.",
				},
			},
		},
	})
	if err != nil {
		panic(err)
	}

	req, err := http.NewRequest("POST", address, bytes.NewReader(body))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	var answer struct {
		Answers map[string]struct {
			Choice string `json:"choice"`
		} `json:"answers"`
		Usage struct {
			Cost json.Number `json:"cost"`
		} `json:"usage"`
	}
	if err := json.NewDecoder(res.Body).Decode(&answer); err != nil {
		panic(err)
	}
	fmt.Println(answer.Answers["team"].Choice, answer.Usage.Cost)
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/systemone"
MODEL="typesafe/jev-1.14"
TICKET="Edahabia payment went through. Order still pending since yesterday."

curl "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"$MODEL"'",
    "state": {
      "ticket": "'"$TICKET"'"
    },
    "questions": {
      "is_bug": {
        "type": "noul",
        "instructions": "Is the customer reporting a defect?",
        "criteria": {
          "true": "The customer describes broken behaviour.",
          "false": "The customer is asking a question."
        }
      },
      "team": {
        "type": "choice",
        "instructions": "Which team owns this ticket?",
        "criteria": {
          "payments": "Checkout, billing or payment processing.",
          "delivery": "Pickup, transit or hand-over."
        }
      }
    }
  }'
```

| You send | Holds |
|---|---|
| `model` | a System One model: `lab/model`, or its bare name |
| `state` | the case to judge: a string, an object or a list |
| `questions` | one or more questions, each under a name you choose |
| `provider` | optional: which providers may serve it, and the most the router may pay, in DA |

| In each question | Holds |
|---|---|
| `type` | `noul` for yes or no, `choice` for one of your options, `score` for a place on your scale |
| `instructions` | the question, in words |
| `criteria` | what each answer means, in the shape its type needs |

Every field: [Typed answers](/docs/reference/systemone).

## 3. Read each answer

`200`, with one answer per question, under the name it carried: the samples print the team picked for the message.

| Field | Holds |
|---|---|
| `answers` | one answer per question, keyed by your names |
| `noul` | on a `noul` answer: the probability of yes, from 0 to 1 |
| `choice` | on a `choice` answer: the option with the most weight |
| `score` | on a `score` answer: your scale's weighted place |
| `probabilities` | on a `choice` or a `score` answer: one entry per option or level; they add up to 1 |
| `confidence` | on a `choice` or a `score` answer: how sure the model is of its pick or its place, its own reading and not the odds |
| `usage` | `input_tokens`: the tokens sent. `cost`: the charge, in DA |

A `choice` answer never carries a `score`, and a `score` answer never carries a `choice`.

## What it cost

Charged in DA from your balance the moment the answer ends: the tokens you sent, the case and every question counted together, at the model's input rate. The answer's tokens are reported and never charged. `usage.cost` carries the charge; the model's page in *Models* gives the rate.

A provider that fails before it answers, or a question refused, charges nothing.

## Errors

The body says why.

| Status | When |
|---|---|
| 400 | `model`, `state` or `questions` is missing, or a question has no `type`, or no `criteria` where its type needs them |
| 401 | the key is missing, wrong, disabled or expired |
| 402 | your balance is at zero or below, cannot pay the request's hold, or the key's cap is spent; `error.metadata.limit_source` names which, and `deposit_url` or `key_url` says where to lift it. After up to 60 seconds of waiting for money your running requests hold, the 402 carries `Retry-After: 60` |
| 404 | `model` is not a System One or classification model on sale |
| 429 | the API key's own rate limit is reached (`metadata.limit_source` is `key`), or the provider is limiting its rate; `Retry-After` says how many seconds to wait |
| 502 | the model is down, or answered with nothing usable |

What to do on each: [Errors and retries](/docs/errors-and-retries).
