# Auto router

Let a router pick the model for each request.

1. [Name the router](#1-name-the-router).
2. [Limit what it picks from](#2-limit-what-it-picks-from).
3. [Read which model answered](#3-read-which-model-answered).

## 1. Name the router

Send `opendunes/auto` as the `model`. The router reads your prompt and picks, from a list of strong current models that OpenDunes keeps, the model best suited to it.

A request that names `auto` is answered by your account's default router. When you have chosen none in the Gateway page of your dashboard, that router is `opendunes/auto`.

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

API_KEY = os.environ["OPENDUNES_API_KEY"]
ADDRESS = "https://opendunes.com/v1/chat/completions"
MODEL = "opendunes/auto"
PROMPT = "Write a one-line welcome for a bakery in Tlemcen."

body = {
    "model": MODEL,
    "messages": [{"role": "user", "content": PROMPT}],
}

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

print(reply["model"])
print(reply["choices"][0]["message"]["content"])
print(reply["usage"]["cost"])
```

```javascript
const API_KEY = process.env.OPENDUNES_API_KEY;
const ADDRESS = "https://opendunes.com/v1/chat/completions";
const MODEL = "opendunes/auto";
const PROMPT = "Write a one-line welcome for a bakery in Tlemcen.";

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

console.log(reply.model);
console.log(reply.choices[0].message.content);
console.log(reply.usage.cost);
```

```go
package main

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

const (
	address = "https://opendunes.com/v1/chat/completions"
	model   = "opendunes/auto"
	prompt  = "Write a one-line welcome for a bakery in Tlemcen."
)

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

	body, err := json.Marshal(map[string]any{
		"model": model,
		"messages": []any{
			map[string]any{"role": "user", "content": prompt},
		},
	})
	if err != nil {
		panic(err)
	}

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

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

	var reply struct {
		Model   string `json:"model"`
		Choices []struct {
			Message struct {
				Content string `json:"content"`
			} `json:"message"`
		} `json:"choices"`
		Usage struct {
			Cost float64 `json:"cost"`
		} `json:"usage"`
	}
	if err := json.NewDecoder(response.Body).Decode(&reply); err != nil {
		panic(err)
	}
	fmt.Println(reply.Model)
	fmt.Println(reply.Choices[0].Message.Content)
	fmt.Println(reply.Usage.Cost)
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/chat/completions"
MODEL="opendunes/auto"
PROMPT="Write a one-line welcome for a bakery in Tlemcen."

curl "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"$MODEL"'",
    "messages": [
      {
        "role": "user",
        "content": "'"$PROMPT"'"
      }
    ]
  }'
```

Routing is free. You pay the model that answers, at its usual price.

<div class="good-to-know">
<p>The router works on the three text routes: chat completions, messages and responses. It reads pictures and files as well as text.</p>
</div>

## 2. Limit what it picks from

Add the `auto-router` plugin to the request to say which models it may choose.

| Field | Holds |
|---|---|
| `allowed_models` | the models it may pick: whole names, or patterns such as `anthropic/*` |
| `excluded_models` | the models it must not pick |
| `cost_tier` | `low`, `medium`, `high`, `xhigh` or `max`: how much quality to buy |

```json
{
  "model": "opendunes/auto",
  "plugins": [
    {
      "id": "auto-router",
      "allowed_models": ["anthropic/*", "google/*"],
      "excluded_models": ["google/gemini-2.5-flash"]
    }
  ],
  "messages": [{ "role": "user", "content": "Summarise this order." }]
}
```

To keep the same limits on every request without touching code, set them in the Gateway page of your dashboard, under Routing. A field your request names wins over the account's.

<div class="watch-out">
<p>Allowed models narrow the router's list and never widen it. A model you allow that is not on the list is not picked.</p>
</div>

## 3. Read which model answered

Every router answer names the model it picked, as `lab/model`, in `model`. Log it: it is the one that was charged, and `usage.cost` is its charge.

| Router | Picks | Takes |
|---|---|---|
| `opendunes/auto` | the model best suited to the prompt, from OpenDunes's list | the three text routes |
| `opendunes/free` | a free model, and the next free one when a source refuses. No charge | chat completions only, for an account holding money, with a limit per minute |
| `typesafe/jev-router` | a model and its reasoning effort, trading quality, speed and cost | the three text routes; `cost_tier` is `low`, `medium` or `high` |
| `nvidia/switchyard` | a cheaper or a stronger model, to lower what the request costs | the three text routes |

<div class="do">
<p>Use <code>opendunes/auto</code> when your prompts vary a lot and you cannot say in advance which model suits each. Use a named model when the same job always needs the same one.</p>
</div>

<div class="dont">
<p>Don't allow only models outside the router's list: the request is refused with a 400. For a list of your own, with fallbacks, name the models yourself: <a href="/docs/fallbacks">Fallbacks</a>.</p>
</div>

## Errors

The body says why. What to do on every status: [Errors and retries](/docs/errors-and-retries).

| Status | Means |
|---|---|
| 400 | `allowed_models` matches no model the router picks from; the message says where to change it |
| 402 | the balance cannot cover the request |
| 403 | the key may not use the router |
| 404 | no such router, or one that is not on sale |
