---
title: 'Research team: a lead agent and specialist subagents'
description: Build a lead agent that delegates to a researcher, an analyst and a writer with weft.Subagent, runs independent delegations in parallel, submits a typed brief and rolls every child's usage into its own.
url: https://weftgo.dev/docs/examples/research-team/
type: how-to
sources:
  - weft/core/subagent.go:166-183 (childRunID, <parent>/<step>/<call>), 279-305 (Subagent godoc, SUBAGENT_FAILED, SUBAGENT_PENDING, SUBAGENT_CYCLE)
  - weft/core/run.go:682-686 (StepRecord.SubagentUsage, already in RunResult.Usage)
  - weft/core/events.go:169-181 (Nested)
  - 'weft/core/loop.go:849, 1102-1116 (guard: the lead''s UsageLimit is checked at its continuation point, after the step''s delegations return)'
  - 'scratch proof (weft v0.17.0, docs a8 fix): a lead with UsageLimit{OutputTokens 6} and one delegation to a child scripted for 7 model calls; the child made all 7, then the lead failed ErrUsageLimit (input 80/0, output 40/6)'
  - weft/core/agent.go:226 (Parallelism)
  - weft/core/output.go:45 (Output), 159 (OutputOf)
  - weft/obsdb/db.go:633 (RunDetail.Children)
  - 'weft/AGENTS.md:276-277 (block 7: a scripted model costs an exact 0, badged scripted)'
  - 'weft/AGENTS.md:54-60 (block 1c), 714-726 (rule 13: child runs are tools)'
  - weft/README.md (Delegating to another agent)
  - weft/example_test.go:600 (ExampleSubagent)
  - weft/core/wefttest/model.go:32-37 (scripted turns report 10 input and 5 output tokens)
  - 'weft-arena/internal/suites/realworld.go: rwResearchTeam, rwDeepDelegation (inspiration only)'
  - docs-site/examples/cookbook/researchteam/main.go, main_test.go TestResearchTeam, TestUsageRollsUp, TestChildRunIDsChain
---

# Research team: a lead agent and specialist subagents

A research team is a lead agent whose tools are other agents. [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) turns each specialist into a tool the lead calls with one `prompt`; the child runs on that prompt alone, its events arrive in the lead's stream as [`weft.Nested`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Nested), and its usage is added to the lead's `res.Usage`. With [`weft.Parallelism`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Parallelism) the lead's independent delegations in one step run side by side.

The lead in `cookbook/researchteam/main.go`:

```go title="cookbook/researchteam/main.go"
lead := weft.New(model,
	weft.Name("lead"),
	weft.Instructions("You lead a research team. The researcher finds facts, the analyst computes, "+
		"the writer drafts prose. Delegate independent tasks in the same step. Finish by submitting the brief."),
	weft.Output[Brief](),
	weft.Parallelism(3), // the step's delegations run side by side
	weft.MaxSteps(10),
	weft.Subagent("researcher", "Finds facts: revenue figures and their sources.", researcher,
		weft.Timeout(2*time.Minute)), // bounds the whole child run
	weft.Subagent("analyst", "Computes numbers such as percentage growth.", analyst,
		weft.Timeout(2*time.Minute)),
	weft.Subagent("writer", "Drafts short executive prose.", writer,
		weft.Timeout(2*time.Minute)),
)
```

[cookbook/researchteam/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/researchteam/main.go)

## How it works

The shape comes from the weft-arena scenarios `rw.research-team` and `rw.deep-delegation`. The question is whether Q3 revenue growth is healthy. The researcher has a search tool and finds the two quarters' revenue. The analyst has a calculator and computes the growth. The writer has no tools and drafts two sentences. The lead decides who does what and submits a typed `Brief`.

A [subagent](https://weftgo.dev/docs/reference/glossary/#subagent) is an ordinary tool, so everything a tool can carry applies to the delegation: `Timeout` bounds the whole child run, `MaxResultBytes` caps its answer, `RequireApproval` gates it. Each child keeps its own model, tools, instructions and `MaxSteps`. The child sees only the prompt the lead writes, never the lead's conversation, so the tool's description is all the lead knows about when to call it.

The lead's script makes two delegations in step 0, one in step 1, and submits in step 2. Under `Parallelism(3)` the researcher and the analyst may run at the same time.

## Delegate

Each child run gets an id derived from the call that owns it: `<lead run>/<step>/<call id>`. Its events reach the lead's stream wrapped in `Nested`, numbered from the lead's own `Seq` counter, so the stream stays totally ordered. Stream the lead, note which child run each delegating call started, and decode the brief:

```go title="cookbook/researchteam/main.go"
run := lead.Stream(ctx, weft.Prompt("Is our Q3 revenue growth healthy? Submit a brief."))
children := map[string]string{} // delegating call id → child run id
for ev, err := range run.Events() {
	if err != nil {
		return nil, err
	}
	if n, ok := ev.(weft.Nested); ok { // a child's event, in the lead's order
		if start, ok := n.Event.(weft.RunStart); ok {
			children[n.CallID] = start.ID
		}
	}
}
res, err := run.Wait() // the same result Events produced
if err != nil {
	return nil, err
}
b, err := weft.OutputOf[Brief](res) // the last valid submit_output call
if err != nil {
	return nil, err
}
```

[cookbook/researchteam/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/researchteam/main.go)

[`weft.OutputOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OutputOf) reads the last valid `submit_output` call from a streamed run, as `GenerateAs` does for `Generate`. A child's `RunStart` through `RunFinish` all arrive between the lead's `ToolStart` and `ToolFinish` for the delegating call.

A child that fails is not a lead failure. The lead's model sees a `SUBAGENT_FAILED` tool error and can try another specialist; a child that ends awaiting approval reads `SUBAGENT_PENDING`. The package example [`ExampleSubagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Subagent) shows the smallest delegation: one child, one answer, and the total usage.

## Roll up the usage

A child's usage is yours ([rule 13](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them)). `res.Usage` already includes every child run, failed ones too. Each step's `StepRecord.Usage` is that step's own model call, and `StepRecord.SubagentUsage` holds each child's usage keyed by the delegating call id:

```go title="cookbook/researchteam/main.go"
var own, delegated weft.Usage
for _, st := range res.Steps {
	own = own.Add(st.Usage) // the lead's own model call
	for _, u := range st.SubagentUsage {
		delegated = delegated.Add(u) // each child run this step started
	}
}
// res.Usage already includes the children: own + delegated.
fmt.Fprintln(w, "usage: own", own.Total(), "+ delegated", delegated.Total(), "= total", res.Usage.Total())
```

[cookbook/researchteam/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/researchteam/main.go)

Each scripted turn reports 10 input and 5 output tokens. The lead's three steps make 45; the researcher's and analyst's two steps each and the writer's one make 75. `weft.UsageLimit` on the lead reads the same total, so one budget counts the whole team. It is checked only between the lead's steps, so it cannot stop a child mid-run; each child's own `MaxSteps` and `UsageLimit` bound one delegation.

## What to look at in Studio

The program records every run with `otel.Install(otel.Local(""))`, and the child runs are linked to the lead: `otel.LocalDB().Run(ctx, res.ID)` lists them on `Children`. On the [run page](https://weftgo.dev/docs/observe/studio/run-page/#the-run-tree) the run tree draws each delegation as a child row under its step, and the graph scale draws the delegation tree:

![A run on the graph scale: the director agent delegating to its ops-manager subagent, with step 0's details in the drawer](https://weftgo.dev/docs/_astro/studio-run-graph.light.DS67UvLU.webp)

*The graph scale for weft-arena's rw.deep-delegation: a director delegating to an ops manager. A research team's lead draws the same way, with its three specialists under steps 0 and 1.*

- Each child run is listed under its parent with `?all=1` in the runs list, and the parent's row counts them (`children_count`).
- With real models, the lead's cost splits into its own and the delegated share; this scripted program shows $0 for both, badged `scripted`. See [See what a run cost](https://weftgo.dev/docs/observe/studio/cost/).
- The two step-0 children can overlap on the waterfall: `Parallelism(3)` lets them run side by side. Scripted children finish in microseconds; with real models they visibly overlap.

## The weft features it combines

| Feature | What it does here | Guide |
|---|---|---|
| `weft.Subagent` | makes each specialist a tool with one `prompt` argument | [Delegate to another agent](https://weftgo.dev/docs/guides/subagents/) |
| `weft.Timeout` on a subagent | bounds the whole child run | [Set per-tool policy](https://weftgo.dev/docs/guides/tool-policy/) |
| `weft.Parallelism` | runs the step's delegations side by side | [What happens in one step?](https://weftgo.dev/docs/concepts/the-loop/) |
| `weft.Nested` events | carry each child's stream inside the lead's | [Stream a run's events](https://weftgo.dev/docs/guides/streaming/) |
| `weft.Output`, `OutputOf` | the lead's typed `Brief` | [Get structured output from a run](https://weftgo.dev/docs/guides/structured-output/) |
| `StepRecord.SubagentUsage` | each child's usage, already in `res.Usage` | [What does a run return?](https://weftgo.dev/docs/concepts/runs/) |

## The program

```go title="cookbook/researchteam/main.go"
// Command researchteam is the recipe "Research team: a lead agent and
// specialist subagents": go run ./cookbook/researchteam. A lead agent
// delegates to a researcher and an analyst in one step, then to a writer,
// and submits a typed Brief. The child runs arrive in the lead's stream
// as weft.Nested events and their usage rolls into the lead's total.
// Every model is scripted with wefttest, so it runs offline; the runs are
// recorded to the local sink ($WEFT_DB, else ./.weft/weft.db).
package main

import (
	"context"
	"fmt"
	"io"
	"maps"
	"os"
	"slices"
	"strings"
	"time"

	"github.com/weftgo/weft"
	"github.com/weftgo/weft/otel"
	"github.com/weftgo/weft/wefttest"
)

// Brief is the lead's structured answer.
type Brief struct {
	Headline      string   `json:"headline" jsonschema:"one line"`
	Points        []string `json:"points" jsonschema:"two to four key points"`
	GrowthPercent float64  `json:"growth_percent" jsonschema:"quarter-over-quarter revenue growth in percent"`
	Confidence    int      `json:"confidence" jsonschema:"0 to 100"`
}

type SearchInput struct {
	Query string `json:"query" jsonschema:"what to search for"`
}

type ChangeInput struct {
	A float64 `json:"a" jsonschema:"the old value"`
	B float64 `json:"b" jsonschema:"the new value"`
}

// specialists builds the three child agents. Each has its own model,
// tools and budget; none sees the lead's transcript, only the prompt the
// lead writes for it.
func specialists() (researcher, analyst, writer *weft.Agent) {
	search := weft.Tool("web_search", "Search the company knowledge base.",
		func(_ context.Context, _ SearchInput) (string, error) {
			return "Finance dashboard: Q2 2026 revenue $3.5M, Q3 2026 revenue $4.2M. Churn fell from 4% to 3%.", nil
		})
	calc := weft.Tool("percent_change", "Compute (b - a) / a * 100.",
		func(_ context.Context, in ChangeInput) (string, error) {
			if in.A == 0 {
				return "", weft.Errorf("DIV_ZERO", "a must not be zero")
			}
			return fmt.Sprintf("%.1f%%", (in.B-in.A)/in.A*100), nil
		})
	researcher = weft.New(wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{ID: "ws1", Name: "web_search", Args: `{"query":"Q2 Q3 2026 revenue"}`}),
		wefttest.Say("Q2 revenue $3.5M, Q3 revenue $4.2M (finance dashboard)."),
	), weft.Name("researcher"), weft.MaxSteps(5), search,
		weft.Instructions("You find facts. Use web_search, then answer with the figures and their source."))
	analyst = weft.New(wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{ID: "pc1", Name: "percent_change", Args: `{"a":3.5,"b":4.2}`}),
		wefttest.Say("Growth from 3.5 to 4.2 is 20.0%."),
	), weft.Name("analyst"), weft.MaxSteps(5), calc,
		weft.Instructions("You do the numbers. Use percent_change and report the result."))
	writer = weft.New(wefttest.Script(
		wefttest.Say("Q3 revenue grew 20% to $4.2M. Growth is healthy and churn is falling."),
	), weft.Name("writer"), weft.MaxSteps(3),
		weft.Instructions("You write crisp executive prose. Answer with exactly two sentences."))
	return researcher, analyst, writer
}

// leadScript is the lead's dialogue: two delegations in one step, one
// more, then the submission.
func leadScript() *wefttest.Model {
	return wefttest.Script(
		wefttest.ToolCalls(
			wefttest.Call{ID: "d1", Name: "researcher", Args: `{"prompt":"Find Q2 and Q3 2026 revenue."}`},
			wefttest.Call{ID: "d2", Name: "analyst", Args: `{"prompt":"Compute the percentage change from 3.5 to 4.2."}`},
		),
		wefttest.ToolCalls(wefttest.Call{ID: "d3", Name: "writer", Args: `{"prompt":"Two sentences: Q3 revenue $4.2M, up 20% from $3.5M."}`}),
		wefttest.ToolCalls(wefttest.Call{ID: "so1", Name: "submit_output",
			Args: `{"headline":"Q3 growth is healthy","points":["Revenue $4.2M, up 20%","Churn down to 3%"],"growth_percent":20,"confidence":85}`}),
	)
}

// newLead builds the lead agent over its specialists.
func newLead(model weft.Model) *weft.Agent {
	researcher, analyst, writer := specialists()
	lead := weft.New(model,
		weft.Name("lead"),
		weft.Instructions("You lead a research team. The researcher finds facts, the analyst computes, "+
			"the writer drafts prose. Delegate independent tasks in the same step. Finish by submitting the brief."),
		weft.Output[Brief](),
		weft.Parallelism(3), // the step's delegations run side by side
		weft.MaxSteps(10),
		weft.Subagent("researcher", "Finds facts: revenue figures and their sources.", researcher,
			weft.Timeout(2*time.Minute)), // bounds the whole child run
		weft.Subagent("analyst", "Computes numbers such as percentage growth.", analyst,
			weft.Timeout(2*time.Minute)),
		weft.Subagent("writer", "Drafts short executive prose.", writer,
			weft.Timeout(2*time.Minute)),
	)
	return lead
}

// brief streams the lead's run, counts each child's events, and decodes
// the submitted Brief.
func brief(ctx context.Context, w io.Writer, lead *weft.Agent) (*weft.RunResult, error) {
	run := lead.Stream(ctx, weft.Prompt("Is our Q3 revenue growth healthy? Submit a brief."))
	children := map[string]string{} // delegating call id → child run id
	for ev, err := range run.Events() {
		if err != nil {
			return nil, err
		}
		if n, ok := ev.(weft.Nested); ok { // a child's event, in the lead's order
			if start, ok := n.Event.(weft.RunStart); ok {
				children[n.CallID] = start.ID
			}
		}
	}
	res, err := run.Wait() // the same result Events produced
	if err != nil {
		return nil, err
	}
	b, err := weft.OutputOf[Brief](res) // the last valid submit_output call
	if err != nil {
		return nil, err
	}
	for _, id := range slices.Sorted(maps.Keys(children)) {
		fmt.Fprintf(w, "%s → child run <lead>%s\n", id, strings.TrimPrefix(children[id], res.ID))
	}
	fmt.Fprintf(w, "brief: %+v\n", b)
	return res, nil
}

// rollup prints how the lead's usage splits into its own model calls and
// its children's runs.
func rollup(w io.Writer, res *weft.RunResult) {
	var own, delegated weft.Usage
	for _, st := range res.Steps {
		own = own.Add(st.Usage) // the lead's own model call
		for _, u := range st.SubagentUsage {
			delegated = delegated.Add(u) // each child run this step started
		}
	}
	// res.Usage already includes the children: own + delegated.
	fmt.Fprintln(w, "usage: own", own.Total(), "+ delegated", delegated.Total(), "= total", res.Usage.Total())
}

func run(ctx context.Context, w io.Writer) error {
	defer otel.Install(otel.Local(""))() // the child runs are recorded too, linked to the lead's

	lead := newLead(leadScript())
	res, err := brief(ctx, w, lead)
	if err != nil {
		return err
	}
	for i, st := range res.Steps {
		var names []string
		for _, c := range st.ToolCalls {
			names = append(names, c.Name)
		}
		fmt.Fprintf(w, "step %d: %s\n", i, strings.Join(names, ", "))
	}
	rollup(w, res)

	detail, err := otel.LocalDB().Run(ctx, res.ID)
	if err != nil {
		return err
	}
	var agents []string
	for _, c := range detail.Children {
		agents = append(agents, c.Agent)
	}
	slices.Sort(agents)
	fmt.Fprintln(w, "recorded children:", strings.Join(agents, ", "))
	return nil
}

func main() {
	if err := run(context.Background(), os.Stdout); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
```

[cookbook/researchteam/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/researchteam/main.go)

[View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/cookbook/researchteam) · run it from `docs-site/examples`:

```sh
go run ./cookbook/researchteam
go test ./cookbook/researchteam
```

```text
d1 → child run <lead>/0/d1
d2 → child run <lead>/0/d2
d3 → child run <lead>/1/d3
brief: {Headline:Q3 growth is healthy Points:[Revenue $4.2M, up 20% Churn down to 3%] GrowthPercent:20 Confidence:85}
step 0: researcher, analyst
step 1: writer
step 2: submit_output
usage: own 45 + delegated 75 = total 120
recorded children: analyst, researcher, writer
```

`<lead>` stands for the lead's run id, which is generated per run. The tests also check that the per-call child usages sum to `res.Usage` and that every child id chains from the lead's.

## Best practices & gotchas

- **Write the prompt for a stranger.** The child sees only the `prompt` argument, never the lead's conversation; its schema says so to the lead's model. (Source: `weft/core/subagent.go:279-284`)
- **Budget the team on the lead, and bound each child.** A child's usage is in the lead's `res.Usage`, so a `UsageLimit` on the lead counts every delegation, failed ones included. It does not cap a child mid-run: the lead checks it only before its next model call, after every delegation of the step has run to its end. A lead limited to 6 output tokens let its child make all 7 model calls, then failed at `output 40/6`. Give each child agent its own `UsageLimit` and `MaxSteps`. (Source: AGENTS.md rule 13, `weft/core/run.go:682-686`, `weft/core/loop.go:849, 1102-1116`)
- **Do not add `SubagentUsage` to `res.Usage` again.** It is already included; `StepRecord.Usage` is the step's own model call only. (Source: `weft/core/run.go:682-686`)
- **Give each child its own `MaxSteps`.** A delegation's `Timeout` bounds its wall time; the child's step budget bounds its model calls. (Source: `weft/core/subagent.go:294-298`)
- **A `thread/pool` child is different.** It is a session, and its usage lands in the parent session's `Usage.Delegated`, not on the run's `res.Usage`. (Source: AGENTS.md rule 13)

## See also

- [Delegate to another agent (subagents)](https://weftgo.dev/docs/guides/subagents/): every Subagent option and failure shape
- [Run bounded child sessions with a pool](https://weftgo.dev/docs/sessions/pools/): delegation that outlives one run
- [Agent patterns and where they attach in weft](https://weftgo.dev/docs/explanation/patterns/)
- [Read a run in Studio](https://weftgo.dev/docs/observe/studio/run-page/)

Symbols used: [`weft.Subagent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Subagent) · [`weft.Nested`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Nested) · [`weft.RunStart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunStart) · [`weft.Parallelism`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Parallelism) · [`weft.Timeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Timeout) · [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) · [`weft.Output`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Output) · [`weft.OutputOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#OutputOf) · [`weft.GenerateAs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#GenerateAs) · [`Agent.Stream`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Stream) · [`Run.Events`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.Events) · [`Run.Wait`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Run.Wait) · [`weft.StepRecord`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StepRecord) · [`weft.Usage`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Usage) · [`Usage.Add`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Usage.Add) · [`Usage.Total`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Usage.Total) · [`weft.UsageLimit`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#UsageLimit) · [`weft.Errorf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Errorf) · [`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install) · [`otel.LocalDB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#LocalDB) · [`obsdb.RunDetail`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#RunDetail) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script)
