# Typed answers

`POST /v1/systemone` sends a case and your typed questions to a System One model, and answers
each question, under the name you gave it, with a score.

## Request

Send it with an API key. The route takes the same case, questions and answers as
[Decisions](/docs/reference/decisions), on the same meter, and a model's bare name as well as its
`lab/model` ID. A chat library cannot call it: send it with any HTTP client. The
[Classification](/docs/classification) guide walks through a first call.

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.

| Field | Needed | You send |
|---|---|---|
| `model` | yes | a System One model, `lab/model`, or its bare name, such as `jev-1.13` for `typesafe/jev-1.13` |
| `state` | yes | the case to judge: a string, an object or a list |
| `questions` | yes | one or more questions, each under a name you choose |
| `provider` | no | which providers may serve it: `only` and `order` name them, `sort` ranks them by `price`, `throughput` or `latency`, and `max_price` caps the price the router may pick, in DA |
| `session_id` | no | your own id grouping related requests, never sent to the model |
| `user` | no | your own id for the person behind the request, never sent to the model |
| `trace` | no | your own tracing fields, never sent to the model |

Each question:

| Field | Needed | You send |
|---|---|---|
| `type` | yes | `noul` for yes or no, `choice` for one of your criteria, `score` for a place on your scale |
| `instructions` | yes | the question, in words |
| `criteria` | yes for `choice` and `score` | `noul`: what `true` and `false` mean · `choice`: one entry per option, keyed by its name · `score`: the levels of your scale, lowest first |

```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.13"
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.13";
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.13"
	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 float64 `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.13"
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."
        }
      }
    }
  }'
```

## Response

One answer per question, under the name you gave it. The type you sent decides its fields: a
`choice` never carries a `score`, and a `score` never carries a `choice`.

| Field | Holds |
|---|---|
| `id` | the receipt handle, read back with `GET /v1/generation` |
| `model` | the model that served it, `lab/model` with its dated version |
| `provider` | the provider that served it |
| `answers` | one answer per question, keyed by the names you sent |
| `type` | the question's type, as you sent it |
| `noul` | on a `noul` answer: the probability of yes, from 0 to 1 |
| `choice` | on a `choice` answer: the criterion the model picked, the one with the most weight |
| `score` | on a `score` answer: your scale's weighted position, each level's place times its probability, added up |
| `probabilities` | on a `choice` or a `score` answer: one entry per criterion or level, keyed by its name or its place from 0; they add up to 1 |
| `confidence` | on a `choice` or a `score` answer: how sure the model is of that pick or that position; its own reading, not the winning probability |
| `legend` | on a `score` answer: each place spelled back out as your level |
| `usage` | what was counted, and the charge |
| `input_tokens` | the case and every question, instruction and criterion, counted together |
| `output_tokens` | the answer's tokens, reported and never charged |
| `cost` | the charge, in DA |

Two headers ride the answer: `X-Generation-Id`, the receipt handle, and `X-Balance-Available`,
your balance after this charge, in µDA.

## What it cost

Charged in DA from your balance the moment the answer ends: the tokens you sent,
`usage.input_tokens`, at the model's input rate. `usage.output_tokens` is reported and never
charged. `usage.cost` carries the charge; the model's rate is on the model's page.

Nothing is charged when the provider fails before it answers, or when a question is refused.

## Errors

`error.code` carries the status, and `error.message` 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` |
| 403 | the key is kept to other models or other addresses, a guardrail's budget is spent, or a guardrail or a filter blocked the request |
| 404 | `model` is not a System One or classification model on sale |
| 408 · 504 | the provider did not answer in time |
| 413 | the body is too large |
| 429 | the provider is limiting its rate; `Retry-After` says how many seconds to wait |
| 500 | an unexpected error |
| 502 | the model is down, or answered with nothing usable |
| 503 | no provider meets the `provider` routing you asked for |
