# Delegate to subagents

Let one model plan the job and hand each routine part to a worker that sees only its own task.

1. [Pick the planner and the worker](#1-pick-the-planner-and-the-worker).
2. [Give the planner a delegate tool](#2-give-the-planner-a-delegate-tool).
3. [Write each task so it stands alone](#3-write-each-task-so-it-stands-alone).
4. [Run the tasks side by side](#4-run-the-tasks-side-by-side).
5. [Read what the job cost](#5-read-what-the-job-cost).

## 1. Pick the planner and the worker

The planner reads the whole job, splits it, and writes the final answer. The worker does one part at a time, from a task written for it, and never sees the rest. The routine parts are where most of the words are written, so they go to the smaller model.

| Seat | Does | Model in this recipe |
|---|---|---|
| planner | splits the job, hands out the parts, writes the answer | `anthropic/claude-sonnet-4.5` |
| worker | does one part: a summary, an extraction, a draft | `anthropic/claude-haiku-4.5` |

The samples below put `anthropic/claude-sonnet-4.5` in both seats, so they run as they stand. Set `WORKER` to the worker's model ID, from the table or from [Models](/docs/models).

## 2. Give the planner a delegate tool

The worker is a tool in the planner's `tools`, like any function of yours ([Tools and function calling](/docs/tools)). The planner calls `delegate` with a `task_name` and a `task_description`. Your code sends the description to the worker's model, in a request of its own, and returns the worker's answer as the call's result.

Nadia runs a marketing agency in Oran. Every Sunday, her agent reads the week's client briefs, has each one summarised, and writes the weekly report.

```python
import json
import os
from concurrent.futures import ThreadPoolExecutor
from openai import OpenAI

API_KEY = os.environ["OPENDUNES_API_KEY"]
BASE_URL = "https://opendunes.com/v1"
MODEL = "anthropic/claude-sonnet-4.5"
WORKER = "anthropic/claude-sonnet-4.5"
PLANNER_BRIEF = (
    "You plan the job and write the final answer. Hand each routine part "
    "to delegate, one call per part, all at once. The worker sees only "
    "task_description: put in it everything the part needs."
)
WORKER_BRIEF = "Do the task exactly as described. Return only the result."
BRIEFS = [
    "Sahel Dates wants twelve Instagram posts for Ramadan, in Arabic.",
    "Oran Auto moved the launch of its used-car page to May.",
    "Tassili Travel asks for a brochure in French and English.",
]
MAX_STEPS = 6

client = OpenAI(base_url=BASE_URL, api_key=API_KEY)
spent = {"planner": 0.0, "worker": 0.0}


def delegate(call):
    args = json.loads(call.function.arguments)
    result = {"status": "ok", "task_name": args["task_name"]}
    try:
        reply = client.chat.completions.create(
            model=WORKER,
            max_tokens=500,
            messages=[
                {"role": "system", "content": WORKER_BRIEF},
                {"role": "user", "content": args["task_description"]},
            ],
        )
    except Exception as error:
        result.update(status="error", error=str(error))
        return call.id, result, 0.0
    result["outcome"] = reply.choices[0].message.content
    return call.id, result, reply.usage.cost


delegate_tool = {
    "type": "function",
    "function": {
        "name": "delegate",
        "description": "Hand one routine task to a worker model.",
        "parameters": {
            "type": "object",
            "properties": {
                "task_name": {"type": "string"},
                "task_description": {"type": "string"},
            },
            "required": ["task_name", "task_description"],
        },
    },
}

job = "Write the client report for this week.\n\n" + "\n".join(BRIEFS)
messages = [
    {"role": "system", "content": PLANNER_BRIEF},
    {"role": "user", "content": job},
]

for step in range(MAX_STEPS):
    reply = client.chat.completions.create(
        model=MODEL,
        messages=messages,
        tools=[delegate_tool],
    )
    spent["planner"] += reply.usage.cost
    message = reply.choices[0].message
    if not message.tool_calls:
        break
    messages.append(message)
    with ThreadPoolExecutor() as pool:
        done = list(pool.map(delegate, message.tool_calls))
    for call_id, result, cost in done:
        spent["worker"] += cost
        messages.append(
            {
                "role": "tool",
                "tool_call_id": call_id,
                "content": json.dumps(result),
            }
        )

print(message.content)
print(spent)
```

```javascript
import OpenAI from "openai";

const API_KEY = process.env.OPENDUNES_API_KEY;
const BASE_URL = "https://opendunes.com/v1";
const MODEL = "anthropic/claude-sonnet-4.5";
const WORKER = "anthropic/claude-sonnet-4.5";
const PLANNER_BRIEF =
  "You plan the job and write the final answer. Hand each routine part " +
  "to delegate, one call per part, all at once. The worker sees only " +
  "task_description: put in it everything the part needs.";
const WORKER_BRIEF =
  "Do the task exactly as described. Return only the result.";
const BRIEFS = [
  "Sahel Dates wants twelve Instagram posts for Ramadan, in Arabic.",
  "Oran Auto moved the launch of its used-car page to May.",
  "Tassili Travel asks for a brochure in French and English.",
];
const MAX_STEPS = 6;

const client = new OpenAI({ baseURL: BASE_URL, apiKey: API_KEY });
const spent = { planner: 0, worker: 0 };

async function delegate(call) {
  const args = JSON.parse(call.function.arguments);
  const result = { status: "ok", task_name: args.task_name };
  try {
    const reply = await client.chat.completions.create({
      model: WORKER,
      max_tokens: 500,
      messages: [
        { role: "system", content: WORKER_BRIEF },
        { role: "user", content: args.task_description },
      ],
    });
    result.outcome = reply.choices[0].message.content;
    spent.worker += reply.usage.cost;
  } catch (error) {
    Object.assign(result, { status: "error", error: String(error) });
  }
  const content = JSON.stringify(result);
  return { role: "tool", tool_call_id: call.id, content };
}

const delegateTool = {
  type: "function",
  function: {
    name: "delegate",
    description: "Hand one routine task to a worker model.",
    parameters: {
      type: "object",
      properties: {
        task_name: { type: "string" },
        task_description: { type: "string" },
      },
      required: ["task_name", "task_description"],
    },
  },
};

const job = "Write the client report for this week.\n\n" + BRIEFS.join("\n");
const messages = [
  { role: "system", content: PLANNER_BRIEF },
  { role: "user", content: job },
];
let message;

for (let step = 0; step < MAX_STEPS; step++) {
  const reply = await client.chat.completions.create({
    model: MODEL,
    messages,
    tools: [delegateTool],
  });
  spent.planner += reply.usage.cost;
  message = reply.choices[0].message;
  if (!message.tool_calls?.length) break;
  messages.push(message);
  messages.push(...(await Promise.all(message.tool_calls.map(delegate))));
}

console.log(message.content);
console.log(spent);
```

```go
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"
	"strconv"
	"strings"
	"sync"

	"github.com/openai/openai-go/v3"
	"github.com/openai/openai-go/v3/option"
)

const (
	baseURL      = "https://opendunes.com/v1"
	model        = "anthropic/claude-sonnet-4.5"
	worker       = "anthropic/claude-sonnet-4.5"
	plannerBrief = "You plan the job and write the final answer. Hand " +
		"each routine part to delegate, one call per part, all at once. " +
		"The worker sees only task_description: put in it everything " +
		"the part needs."
	workerBrief = "Do the task exactly as described. Return only the result."
	maxSteps    = 6
)

type outcome struct {
	result string
	cost   float64
}

func main() {
	apiKey := os.Getenv("OPENDUNES_API_KEY")
	briefs := []string{
		"Sahel Dates wants twelve Instagram posts for Ramadan, in Arabic.",
		"Oran Auto moved the launch of its used-car page to May.",
		"Tassili Travel asks for a brochure in French and English.",
	}

	client := openai.NewClient(
		option.WithBaseURL(baseURL),
		option.WithAPIKey(apiKey),
	)
	spent := map[string]float64{"planner": 0, "worker": 0}

	delegate := func(arguments string) outcome {
		var args struct {
			TaskName        string `json:"task_name"`
			TaskDescription string `json:"task_description"`
		}
		json.Unmarshal([]byte(arguments), &args)
		params := openai.ChatCompletionNewParams{
			Model:     worker,
			MaxTokens: openai.Int(500),
			Messages: []openai.ChatCompletionMessageParamUnion{
				openai.SystemMessage(workerBrief),
				openai.UserMessage(args.TaskDescription),
			},
		}
		result := map[string]string{"task_name": args.TaskName}
		cost := 0.0
		reply, err := client.Chat.Completions.New(context.TODO(), params)
		if err != nil {
			result["status"] = "error"
			result["error"] = err.Error()
		} else {
			result["status"] = "ok"
			result["outcome"] = reply.Choices[0].Message.Content
			cost = charge(reply)
		}
		out, _ := json.Marshal(result)
		return outcome{string(out), cost}
	}

	text := map[string]any{"type": "string"}
	delegateTool := openai.ChatCompletionFunctionTool(
		openai.FunctionDefinitionParam{
			Name: "delegate",
			Description: openai.String(
				"Hand one routine task to a worker model."),
			Parameters: openai.FunctionParameters{
				"type": "object",
				"properties": map[string]any{
					"task_name":        text,
					"task_description": text,
				},
				"required": []string{"task_name", "task_description"},
			},
		},
	)

	job := "Write the client report for this week.\n\n" +
		strings.Join(briefs, "\n")
	params := openai.ChatCompletionNewParams{
		Model: model,
		Messages: []openai.ChatCompletionMessageParamUnion{
			openai.SystemMessage(plannerBrief),
			openai.UserMessage(job),
		},
		Tools: []openai.ChatCompletionToolUnionParam{delegateTool},
	}

	var message openai.ChatCompletionMessage
	for step := 0; step < maxSteps; step++ {
		reply, err := client.Chat.Completions.New(context.TODO(), params)
		if err != nil {
			panic(err)
		}
		spent["planner"] += charge(reply)
		message = reply.Choices[0].Message
		if len(message.ToolCalls) == 0 {
			break
		}
		params.Messages = append(params.Messages, message.ToParam())

		done := make([]outcome, len(message.ToolCalls))
		var wait sync.WaitGroup
		for i, call := range message.ToolCalls {
			wait.Add(1)
			go func() {
				defer wait.Done()
				done[i] = delegate(call.Function.Arguments)
			}()
		}
		wait.Wait()

		for i, call := range message.ToolCalls {
			spent["worker"] += done[i].cost
			result := openai.ToolMessage(done[i].result, call.ID)
			params.Messages = append(params.Messages, result)
		}
	}

	fmt.Println(message.Content)
	fmt.Println(spent)
}

func charge(reply *openai.ChatCompletion) float64 {
	cost := reply.Usage.JSON.ExtraFields["cost"].Raw()
	value, _ := strconv.ParseFloat(cost, 64)
	return value
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/chat/completions"
MODEL="anthropic/claude-sonnet-4.5"
PLANNER_BRIEF="You plan the job and write the final answer. Hand each \
routine part to delegate, one call per part, all at once. The worker \
sees only task_description: put in it everything the part needs."
JOB="Write the client report for this week. \
Sahel Dates wants twelve Instagram posts for Ramadan, in Arabic. \
Oran Auto moved the launch of its used-car page to May. \
Tassili Travel asks for a brochure in French and English."

curl "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"$MODEL"'",
    "messages": [
      {
        "role": "system",
        "content": "'"$PLANNER_BRIEF"'"
      },
      {
        "role": "user",
        "content": "'"$JOB"'"
      }
    ],
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "delegate",
          "description": "Hand one routine task to a worker model.",
          "parameters": {
            "type": "object",
            "properties": {
              "task_name": {
                "type": "string"
              },
              "task_description": {
                "type": "string"
              }
            },
            "required": ["task_name", "task_description"]
          }
        }
      }
    ]
  }'
```

The cURL sample is the planner's first turn: its answer carries the `delegate` calls your code runs.

<div class="good-to-know">
<p>The same split can run in one request, with the subagent helper, <code>opendunes:subagent</code>: OpenDunes runs the worker for the planner, and you write no loop. <a href="/docs/helpers">Helpers</a> shows how. The loop above is the version you own: you see every task, and the worker can use your own functions.</p>
</div>

## 3. Write each task so it stands alone

The worker reads its brief and the `task_description`, and nothing else. It has no conversation, no job, no other task. This is the request `delegate` sends, with the worker's model in place.

```json
{
  "model": "anthropic/claude-haiku-4.5",
  "max_tokens": 500,
  "messages": [
    {
      "role": "system",
      "content": "Do the task exactly as described. Return only the result."
    },
    {
      "role": "user",
      "content": "Two lines, for a report: Oran Auto moved its launch to May."
    }
  ]
}
```

| A `task_description` holds | Example |
|---|---|
| what to do | two lines, for a report |
| everything it works on | the brief itself, pasted in |
| the shape of the result | two lines |

<div class="dont">
<p>Don't write "summarise the brief above". The worker has no "above": it answers from nothing, or makes the brief up.</p>
</div>

<div class="do">
<p>Say in the planner's brief that the worker sees only <code>task_description</code>, and paste every input the part needs into it.</p>
</div>

## 4. Run the tasks side by side

The planner can ask for several calls in one message. The tasks do not wait on each other, so the samples run them at once: a pool of threads in Python, `Promise.all` in JavaScript, a goroutine per call in Go. The results go back in the order of the calls, one `tool` message each.

A worker call that fails goes back too, as `{"status": "error", ...}`: the planner reads it, and hands the task out again or works around it.

<div class="watch-out">
<p>Each task is a request of its own. Many at once can meet a 429 when the provider limits its rate: the library waits and sends it again, as <a href="/docs/errors-and-retries">Errors and retries</a> shows.</p>
</div>

## 5. Read what the job cost

Each request is charged on its own, at its model's rates, and `usage.cost` on each answer carries its charge in DA. The samples keep two sums: `planner`, every turn of the planner, and `worker`, every task. `max_tokens` on the worker's request caps each task's answer. *Activity*, in the app, lists each request under its model.

The other way round, a worker that asks a stronger model: [Review by a stronger model](/docs/cookbook/review-by-a-stronger-model).
