Research team: a lead agent and specialist subagents
A research team is a lead agent whose tools are other agents. weft.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, and its usage is added to the lead’s res.Usage. With weft.Parallelism the lead’s independent delegations in one step run side by side.
The lead in 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)),)How it works
Section titled “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 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
Section titled “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:
run := lead.Stream(ctx, weft.Prompt("Is our Q3 revenue growth healthy? Submit a brief."))children := map[string]string{} // delegating call id → child run idfor 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 producedif err != nil { return nil, err}b, err := weft.OutputOf[Brief](res) // the last valid submit_output callif err != nil { return nil, err}weft.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 shows the smallest delegation: one child, one answer, and the total usage.
Roll up the usage
Section titled “Roll up the usage”A child’s usage is yours (rule 13). 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:
var own, delegated weft.Usagefor _, 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())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
Section titled “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 the run tree draws each delegation as a child row under its step, and the graph scale draws the delegation tree:


- Each child run is listed under its parent with
?all=1in 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. - 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
Section titled “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 |
weft.Timeout on a subagent | bounds the whole child run | Set per-tool policy |
weft.Parallelism | runs the step’s delegations side by side | What happens in one step? |
weft.Nested events | carry each child’s stream inside the lead’s | Stream a run’s events |
weft.Output, OutputOf | the lead’s typed Brief | Get structured output from a run |
StepRecord.SubagentUsage | each child’s usage, already in res.Usage | What does a run return? |
The program
Section titled “The program”// 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) }}View on GitHub · run it from docs-site/examples:
go run ./cookbook/researchteamgo test ./cookbook/researchteamd1 → child run <lead>/0/d1d2 → child run <lead>/0/d2d3 → child run <lead>/1/d3brief: {Headline:Q3 growth is healthy Points:[Revenue $4.2M, up 20% Churn down to 3%] GrowthPercent:20 Confidence:85}step 0: researcher, analyststep 1: writerstep 2: submit_outputusage: own 45 + delegated 75 = total 120recorded 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
Section titled “Best practices & gotchas”- Write the prompt for a stranger. The child sees only the
promptargument, 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 aUsageLimiton 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 atoutput 40/6. Give each child agent its ownUsageLimitandMaxSteps. (Source: AGENTS.md rule 13,weft/core/run.go:682-686,weft/core/loop.go:849, 1102-1116) - Do not add
SubagentUsagetores.Usageagain. It is already included;StepRecord.Usageis the step’s own model call only. (Source:weft/core/run.go:682-686) - Give each child its own
MaxSteps. A delegation’sTimeoutbounds its wall time; the child’s step budget bounds its model calls. (Source:weft/core/subagent.go:294-298) - A
thread/poolchild is different. It is a session, and its usage lands in the parent session’sUsage.Delegated, not on the run’sres.Usage. (Source: AGENTS.md rule 13)
See also
Section titled “See also”- Delegate to another agent (subagents): every Subagent option and failure shape
- Run bounded child sessions with a pool: delegation that outlives one run
- Agent patterns and where they attach in weft
- Read a run in Studio
Symbols used: weft.Subagent · weft.Nested · weft.RunStart · weft.Parallelism · weft.Timeout · weft.MaxSteps · weft.Output · weft.OutputOf · weft.GenerateAs · Agent.Stream · Run.Events · Run.Wait · weft.StepRecord · weft.Usage · Usage.Add · Usage.Total · weft.UsageLimit · weft.Errorf · otel.Install · otel.LocalDB · obsdb.RunDetail · wefttest.Script