Skip to content

Research team: a lead agent and specialist subagents

View as Markdown

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:

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

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.

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:

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

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.

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:

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

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.

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:

A run on the graph scale: the director agent delegating to its ops-manager subagent, with step 0's details in the drawerA run on the graph scale: the director agent delegating to its ops-manager subagent, with step 0's details in the drawer
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.
  • 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.
FeatureWhat it does hereGuide
weft.Subagentmakes each specialist a tool with one prompt argumentDelegate to another agent
weft.Timeout on a subagentbounds the whole child runSet per-tool policy
weft.Parallelismruns the step’s delegations side by sideWhat happens in one step?
weft.Nested eventscarry each child’s stream inside the lead’sStream a run’s events
weft.Output, OutputOfthe lead’s typed BriefGet structured output from a run
StepRecord.SubagentUsageeach child’s usage, already in res.UsageWhat does a run return?
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)
}
}

View cookbook/researchteam/main.go on GitHub

View on GitHub · run it from docs-site/examples:

Terminal window
go run ./cookbook/researchteam
go test ./cookbook/researchteam
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.

  • 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)

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