# Messages

`POST /v1/messages` sends a conversation to a text model in the Anthropic shape and returns its
reply, with what it cost.

## Request

Send it with an API key, as JSON. The request and the answer keep the Anthropic shape, so a
client library already written for it works unchanged. A field this page does not list still
travels to the model as sent. The [Text](/docs/text) guide walks through a first call.

### Messages

| Field | Needed | You send |
|---|---|---|
| `model` | yes | a text model, `lab/model` |
| `system` | no | the instructions that frame the conversation: a string, or a list of text parts |
| `messages` | yes | the turns so far, oldest first: each `{"role": ..., "content": ...}`, with `role` `user`, `assistant` or `system`. `content` is a string, or a list of blocks: text, pictures, documents, and the results of tool calls |
| `max_tokens` | no | the most tokens the reply may hold, thinking included. A limit you name is never lowered: above the model's longest answer it becomes that, and one your balance cannot pay gets a 402. Left out, it is the limit your balance can pay, half of what is left after the input at most, up to the model's longest answer: [Balance and charges](/docs/balance-and-charges#how-a-request-is-charged) |
| `stream` | no | `true` to receive the reply as it is written, as server-sent events |

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

API_KEY = os.environ["OPENDUNES_API_KEY"]
ADDRESS = "https://opendunes.com/v1/messages"
MODEL = "anthropic/claude-sonnet-4.5"
PROMPT = "Explain what a prepaid wallet is, in one sentence."

request = urllib.request.Request(
    ADDRESS,
    data=json.dumps(
        {
            "model": MODEL,
            "max_tokens": 1024,
            "messages": [{"role": "user", "content": PROMPT}],
        }
    ).encode(),
    headers={
        "Authorization": "Bearer " + API_KEY,
        "Content-Type": "application/json",
    },
)
with urllib.request.urlopen(request) as response:
    answer = json.load(response)

print(answer["content"][0]["text"])
print(answer["usage"]["cost"])
```

```javascript
const API_KEY = process.env.OPENDUNES_API_KEY;
const ADDRESS = "https://opendunes.com/v1/messages";
const MODEL = "anthropic/claude-sonnet-4.5";
const PROMPT = "Explain what a prepaid wallet is, in one sentence.";

const response = await fetch(ADDRESS, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: MODEL,
    max_tokens: 1024,
    messages: [{ role: "user", content: PROMPT }],
  }),
});
const answer = await response.json();

console.log(answer.content[0].text);
console.log(answer.usage.cost);
```

```go
package main

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

const (
	address = "https://opendunes.com/v1/messages"
	model   = "anthropic/claude-sonnet-4.5"
	prompt  = "Explain what a prepaid wallet is, in one sentence."
)

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

	body, err := json.Marshal(map[string]any{
		"model":      model,
		"max_tokens": 1024,
		"messages": []map[string]string{
			{"role": "user", "content": prompt},
		},
	})
	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 {
		Content []struct {
			Type string `json:"type"`
			Text string `json:"text"`
		} `json:"content"`
		Usage struct {
			Cost json.Number `json:"cost"`
		} `json:"usage"`
	}
	if err := json.NewDecoder(res.Body).Decode(&answer); err != nil {
		panic(err)
	}

	fmt.Println(answer.Content[0].Text)
	fmt.Println(answer.Usage.Cost)
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/messages"
MODEL="anthropic/claude-sonnet-4.5"

curl "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"$MODEL"'",
    "max_tokens": 1024,
    "messages": [
      {
        "role": "user",
        "content": "Explain what a prepaid wallet is, in one sentence."
      }
    ]
  }'
```

### Sampling

<details>
<summary>Show 4 more fields</summary>

| Field | Needed | You send |
|---|---|---|
| `temperature` | no | higher is more varied, lower more predictable |
| `top_p` | no | 0 to 1: sample only from the likeliest tokens that together reach this share |
| `top_k` | no | sample only from this many likeliest tokens |
| `stop_sequences` | no | strings that end the reply when the model writes one |

</details>

### Tools

<details>
<summary>Show 6 more fields</summary>

| Field | Needed | You send |
|---|---|---|
| `tools` | no | the tools the model may call: each with a `name`, a `description` and an `input_schema`. A helper is named `{"type": "opendunes:<name>"}` and runs while the model answers; the shell, bash and tool search helpers work here |
| `tool_choice` | no | `{"type": "auto"}`, `{"type": "any"}`, `{"type": "none"}`, or one tool by name |
| `max_tool_calls` | no | 1 to 30: the most helper steps one request may take |
| `stop_server_tools_when` | no | conditions that end the helper steps early; when set, it takes over from `max_tool_calls` |
| `plugins` | no | the plugins to run on this request, each with its settings |
| `safeguards` | no | checks the provider runs beside the reply, each named by its `type`, such as `dangerous_tool_use` |

</details>

### Output shape

<details>
<summary>Show 3 more fields</summary>

| Field | Needed | You send |
|---|---|---|
| `thinking` | no | `{"type": "enabled", "budget_tokens": ...}` to let the model think before it answers, within that many tokens; `{"type": "adaptive"}` to let it decide; `{"type": "disabled"}` |
| `output_config` | no | `effort`, from `low` to `max`, and `format` for a reply that follows your JSON Schema |
| `context_management` | no | `edits` that clear old tool results from a long conversation before it is sent |

</details>

### Routing

<details>
<summary>Show 7 more fields</summary>

| Field | Needed | You send |
|---|---|---|
| `models` | no | more models, tried in order when `model` fails or is limited |
| `fallbacks` | no | up to three `{"model": ...}` entries, tried in order when `model` fails or refuses; never with `models` |
| `provider` | no | which providers may serve it: `only`, `ignore`, `order`, `sort` (`price`, `throughput`, `latency` or `exacto`), `allow_fallbacks`, `max_price` in DA per million tokens, and the rest of the provider's own preferences. Your account's privacy settings add `data_collection: "deny"` |
| `route` | no | the older name for choosing between trying models in turn and sorting across them; `provider.sort` replaces it |
| `service_tier` | no | the provider's processing tier, where it offers tiers |
| `speed` | no | `fast` for a quicker reply where the model offers it, at that speed's own rate; `standard` otherwise |
| `cache_control` | no | `{"type": "ephemeral"}` to cache the prompt's longest stable part; on a block, it marks where the cached part ends |

</details>

## Response

`200 OK`, once the reply is written.

| Field | Holds |
|---|---|
| `id` | the receipt handle, read back with `GET /v1/generation` |
| `type` | `message` |
| `role` | `assistant` |
| `model` | the model that answered, `lab/model`; with `models` or `fallbacks`, the one that served |
| `provider` | the lab that served it |
| `content` | the reply, as blocks: `text`, `thinking`, `tool_use`, and a helper's calls and results |
| `stop_reason` | why it ended: `end_turn`, `max_tokens`, `stop_sequence`, `tool_use`, `pause_turn` or `refusal`, among others |
| `stop_sequence` | the stop sequence that ended it, when one did |
| `container` | the sandbox a helper ran in, under your name for it |
| `usage` | what was counted, and the charge |
| `input_tokens` | the fresh tokens sent, outside the cache |
| `cache_read_input_tokens` | the tokens read from the cache |
| `cache_creation_input_tokens` | the tokens written to the cache |
| `output_tokens` | every token produced, thinking and reply |
| `output_tokens_details` | `thinking_tokens`, the thinking inside the output count |
| `server_tool_use` | the helper calls requested and run, and the web searches and fetches |
| `cost` | the charge, in DA |
| `cut_short` | `"wallet"`, when the balance set the reply's limit and `stop_reason` is `max_tokens`; absent otherwise |
| `note` | with `cut_short`: `The balance set this answer's length limit, and the answer ended at it.` |
| `opendunes_metadata` | how the request was routed, when it sent `X-OpenDunes-Metadata: enabled` |

`X-Generation-Id` rides the answer: the receipt handle. `X-Balance-Available` is your balance
after this charge, in µDA.

**With `stream: true`.** The answer is a stream of server-sent events, named as the Anthropic
shape names them: `message_start` opens it with the input count, the blocks arrive piece by
piece, `message_delta` carries the output count and `usage.cost` (and `cut_short` and `note`, when the
balance limited the reply), and `message_stop` ends it. A
stream carries no `X-Balance-Available`: its headers leave before the charge exists, and
`GET /v1/credits`, with a management key, answers the balance after it.

## What it cost

Charged in DA from your balance once the reply is delivered: the tokens the model reports, at
the model's rates, which its model page shows. `usage.cost` carries the charge, and the counts
in `usage` add up to it.

- **Picks the price**: `model`, and `models` or `fallbacks` when a fallback answers, at the
  fallback's own rate; `provider`, where `only` pins one provider and its rate applies, and
  `max_price` sets a ceiling.
- **Moves the count**: `system` and `messages`, every token sent; `max_tokens`, the ceiling on
  what comes back; `thinking`, whose tokens count as output; `cache_control`, a cached part
  counted at the cache-read rate, and at the cache-write rate the first time; `tools`, whose
  definitions are sent on every turn; `output_config`, whose `effort` moves how much the model
  writes.
- **Changes the answer, never the bill**: the Sampling fields, `tool_choice` and `stream`.

A stream cut before `message_stop` is charged from the receipt, moments later, and
`GET /v1/generation` shows it. Where the provider stops the model when you close the stream,
the charge stops there; where it cannot, the model finishes and the whole answer is charged. A
provider error mid-stream charges the tokens produced. Each of
these charges nothing: a reply with no output, an error before any output, a response-cache hit,
a model that is not on sale.

## Errors

The body says why.

| Status | When |
|---|---|
| 400 | `model` or `messages` is missing, a field has the wrong type, a helper is not offered or works on another route only, a sandbox name or a `session_id` is malformed, or the provider refused a field |
| 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; `metadata.limit_source`, beside `error`, names which, and `deposit_url` or `key_url` there 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 model on sale, or a sandbox a helper names is not yours |
| 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 |
