# Subagent

Let a model hand a self-contained task to a smaller, cheaper model, and pay for the worker on its own meter.

1. [What it does](#1-what-it-does).
2. [Name it in `tools`](#2-name-it-in-tools).
3. [Shape the worker](#3-shape-the-worker).
4. [Read what it bills on](#4-read-what-it-bills-on).

This page is one helper. The list of helpers, and how the charge adds up, sit in [Helpers](/docs/helpers).

## 1. What it does

Your model hands a task to a worker model: summarise this changelog, extract these fields, look this up. The worker sees only the task your model writes for it, never the conversation, and its outcome comes back as the helper's result. When your model calls the helper, it passes a `task_name` and a `task_description`, which must hold everything the worker needs.

| | |
|---|---|
| Type | `opendunes:subagent` |
| Routes | `/v1/chat/completions`, `/v1/responses` and `/v1/messages` |
| A step | one task |
| Steps | at most 30 a request |
| Bills on | the worker model's tokens, and its own helper calls on their meters, in DA, beside your model's |

## 2. Name it in `tools`

Souk Bot compares what three mobile operators offer. Sonnet plans and hands the lookups to a smaller worker that may search the web itself. The sample allows three tasks and prints the answer and the charge.

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

API_KEY = os.environ["OPENDUNES_API_KEY"]
ADDRESS = "https://opendunes.com/v1/chat/completions"
MODEL = "anthropic/claude-sonnet-4.5"
WORKER = "anthropic/claude-haiku-4.5"
PROMPT = "Compare the offers of the three mobile operators in Algeria."

body = {
    "model": MODEL,
    "messages": [{"role": "user", "content": PROMPT}],
    "tools": [
        {
            "type": "opendunes:subagent",
            "parameters": {
                "model": WORKER,
                "tools": [{"type": "opendunes:web_search"}],
            },
        }
    ],
    "max_tool_calls": 3,
}
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:
    answer = json.load(response)

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

```javascript
const API_KEY = process.env.OPENDUNES_API_KEY;
const ADDRESS = "https://opendunes.com/v1/chat/completions";
const MODEL = "anthropic/claude-sonnet-4.5";
const WORKER = "anthropic/claude-haiku-4.5";
const PROMPT = "Compare the offers of the three mobile operators in Algeria.";

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 }],
    tools: [
      {
        type: "opendunes:subagent",
        parameters: {
          model: WORKER,
          tools: [{ type: "opendunes:web_search" }],
        },
      },
    ],
    max_tool_calls: 3,
  }),
});
const answer = await response.json();

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

```go
package main

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

const (
	address = "https://opendunes.com/v1/chat/completions"
	model   = "anthropic/claude-sonnet-4.5"
	worker  = "anthropic/claude-haiku-4.5"
	prompt  = "Compare the offers of the three mobile operators in Algeria."
)

func main() {
	apiKey := os.Getenv("OPENDUNES_API_KEY")
	body, err := json.Marshal(map[string]any{
		"model": model,
		"messages": []map[string]string{
			{"role": "user", "content": prompt},
		},
		"tools": []map[string]any{
			{
				"type": "opendunes:subagent",
				"parameters": map[string]any{
					"model": worker,
					"tools": []map[string]string{
						{"type": "opendunes:web_search"},
					},
				},
			},
		},
		"max_tool_calls": 3,
	})
	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 {
		Choices []struct {
			Message struct {
				Content string `json:"content"`
			} `json:"message"`
		} `json:"choices"`
		Usage struct {
			Cost json.Number `json:"cost"`
		} `json:"usage"`
	}
	if err := json.NewDecoder(res.Body).Decode(&answer); err != nil {
		panic(err)
	}
	fmt.Println(answer.Choices[0].Message.Content)
	fmt.Println(answer.Usage.Cost)
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/chat/completions"
MODEL="anthropic/claude-sonnet-4.5"
WORKER="anthropic/claude-haiku-4.5"
PROMPT="Compare the offers of the three mobile operators in Algeria."

curl "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"$MODEL"'",
    "messages": [
      {
        "role": "user",
        "content": "'"$PROMPT"'"
      }
    ],
    "tools": [
      {
        "type": "opendunes:subagent",
        "parameters": {
          "model": "'"$WORKER"'",
          "tools": [
            {
              "type": "opendunes:web_search"
            }
          ]
        }
      }
    ],
    "max_tool_calls": 3
  }'
```

The answer is a `200`. Name the helper by its type, `opendunes:subagent`; any other spelling of the type is a `400`.

## 3. Shape the worker

Put these in the helper's `parameters`.

| Parameter | Does |
|---|---|
| `model` | the worker; left out, the request's own model |
| `name` | names this worker; several `opendunes:subagent` entries, each named, offer a choice, and at most one may go unnamed |
| `tools` | helpers the worker may use itself, such as `opendunes:web_search`; your own functions are refused here with a `400` |
| `instructions` | the worker's system instructions |
| `max_tool_calls` | the worker's own helper steps, from 1 to 25 |
| `max_completion_tokens` · `reasoning` · `temperature` | passed to the worker's call |

The request's `max_tool_calls` and the worker's are two limits: the first counts tasks handed over, the second counts the steps inside one task.

## 4. Read what it bills on

One charge, in DA, from your balance, the moment the answer ends: your model's tokens, the worker's tokens at the worker model's own price, and the worker's own helper calls, each on its meter. `usage.cost` carries the whole of it. The worker model's page in [Models](/models) gives its token rates.

The helper runs another model, so it has a spend cap. Before the model starts, OpenDunes holds money from your wallet for the words and the answer, and writes the cap into the request.

| Your request | The hold |
|---|---|
| names no `stop_server_tools_when` | writes two conditions: the step count, 30 or your `max_tool_calls`, and a `max_cost` equal to half of what the wallet has left after the answer's hold; the helper stops at whichever comes first |
| names `stop_server_tools_when` with a `max_cost` | holds that cap whole; when the wallet cannot pay it, the answer is a `402` that says what the request needs |
| names `stop_server_tools_when` without a `max_cost` | keeps your conditions and adds the cap |

A cap is a condition on the request:

```json
{
  "stop_server_tools_when": [
    { "type": "step_count_is", "step_count": 3 },
    { "type": "max_cost", "max_cost_in_dollars": 0.1 }
  ]
}
```

When the steps or the cap run out, the model answers with what it has gathered.

<div class="dont">
<p>Don't hand a worker a task that needs the conversation. It never sees the conversation, and your model pays to write a long task when a short one would do.</p>
</div>

<div class="do">
<p>Hand over self-contained lookups and extractions, and set the worker's <code>max_tool_calls</code> so one task cannot run long.</p>
</div>
