Skip to content

Delegate to another agent (subagents)

View as Markdown

weft.Subagent(name, description, child, opts...) returns a tool whose handler runs another agent. The parent model calls it with one argument, prompt; the child runs on a fresh transcript holding only that prompt, and the tool’s result is the child’s final text. Use it when an orchestrator should hand a self-contained task to a specialist and read its answer.

subagents/main.go gives an orchestrator a researcher:

subagents/main.go
researcher := weft.New(childModel,
weft.Name("researcher"),
weft.Instructions("You research one question and answer briefly."),
deepSearch,
)
orchestrator := weft.New(parentModel,
weft.Name("orchestrator"),
weft.Subagent("research", "Research a topic in depth.", researcher,
weft.Timeout(2*time.Minute), // bounds the child run
),
)

subagents/main.go on GitHub

The tool’s description is all the parent model knows about the child, so write it as you would any tool’s. The package example is ExampleSubagent.

A subagent is an ordinary tool (ADR 0014). Its handler runs the child through the same loop Generate and Stream use, on the parent call’s context. There is no second loop and no graph: it is the orchestrator-worker pattern built from the tool contract.

The child sees nothing of the parent’s conversation, only the prompt the parent model wrote and its own instructions. The prompt argument’s schema says so to the parent model: The task, stated in full: the agent sees only this prompt, not the conversation.

The child’s run is observable from the parent. Its events arrive in the parent’s stream, its usage is added to the parent’s, and Studio draws the delegation as an edge:

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
A run on Studio's graph scale: the director agent delegating to its ops-manager subagent.

Every tool option applies to the delegation:

  • weft.Timeout bounds the child run. At the deadline the result is the ordinary tool "research" timed out after 2m0s, and the child stops at its next context check.
  • weft.MaxResultBytes caps the child’s answer.
  • weft.RequireApproval gates the act of delegating: the call parks, and Approve runs the child.
  • weft.Sequential makes the delegation a barrier, and the parent’s weft.Parallelism bounds concurrent delegations: with the default Parallelism(4), four research calls in one step run their four children at once, and a fifth waits for a slot.
  • The parent’s weft.WrapTools wraps the delegation once; the child’s own seams govern inside it.

A child built with weft.Output returns its last valid submit_output arguments, byte for byte, instead of its text. If it never made a valid submission, the tool’s result is its final text, and no error is raised. Canceling the parent’s context cancels the child.

The child runs on its own agent’s configuration. Its run is built from the delegating call alone: the call’s context, a run id derived from the call, and the prompt argument. A parent’s run options reach the child only when they ride that context:

Parent run optionReaches the child?What the child does
weft.Metadata, and weft.WithMetadata on the contextYesReads the merged pairs with weft.MetadataFromContext.
weft.ParkAllExceptYesApplies the rule to its own tools; a call it parks ends the delegation SUBAGENT_PENDING.
Cancellation and deadline, weft.Timeout on the delegation includedYesStops at its next context check.
weft.Thinking, weft.Instructions, weft.Params, weft.ToolChoiceNoSends its own agent’s defaults.
weft.UseModelNoCalls its own agent’s model.
weft.OnlyToolsNoIs offered all of its own tools.
weft.MaxSteps, weft.Parallelism (lowered)NoKeeps its own agent’s limits.
weft.ParkOnNoRuns the named tools unasked.
weft.Approve, weft.Deny, weft.Resolve, weft.ResolveError, weft.ResumeOfNoDecides nothing of the parent’s. A child that parks ends SUBAGENT_PENDING.
weft.Steering, weft.OnMessagesNoGets no steering source and no transcript observer.
weft.RunID, weft.Prompt, weft.MessagesNoGets the id <parent>/<step>/<callID> and a transcript holding only the prompt argument.

No error is raised. A parent run with Thinking(ThinkHigh), Instructions("run sys"), Params{Temperature: 0.9}, UseModel(alt), OnlyTools, MaxSteps(2) and ParkOn sent all of these on its own two model calls. Its child’s three requests, one more than the parent’s MaxSteps(2), carried the child’s system prompt, no thinking level, no temperature and both of the child’s tools; the parked tool ran (gotcha).

Each event of the child run arrives in the parent’s stream wrapped in a weft.Nested: CallID is the parent call that owns the child, Event is the child’s event. Switch on the inner event as you would on the parent’s:

subagents/main.go
run := orchestrator.Stream(ctx, weft.Prompt("What is new in tool-use evaluation?"), weft.RunID("run-1"))
for ev, err := range run.Events() {
if err != nil {
return err
}
switch ev := ev.(type) {
case weft.ToolStart:
fmt.Fprintf(w, "parent tool %s: %s\n", ev.CallID, ev.Name)
case weft.Nested: // one event of the child run, owned by parent call ev.CallID
switch inner := ev.Event.(type) {
case weft.RunStart:
fmt.Fprintf(w, " child %s started: %s\n", inner.ID, inner.Agent)
case weft.ToolFinish:
fmt.Fprintf(w, " child tool %s → %s\n", inner.Name, inner.Content)
case weft.RunFinish:
fmt.Fprintf(w, " child %s finished in %d steps\n", inner.RunID, inner.Steps)
}
case weft.ToolFinish:
fmt.Fprintf(w, "parent tool %s → %s\n", ev.CallID, ev.Content)
}
}

subagents/main.go on GitHub

parent tool c1: research
child run-1/0/c1 started: researcher
child tool deep_search → 3 papers on tool-use evaluation
child run-1/0/c1 finished in 2 steps
parent tool c1 → I found 3 papers on tool-use evaluation.

The child’s whole run, RunStart through RunFinish, sits inside the delegating call’s ToolStart and ToolFinish. No Nested event for a call is delivered after that call’s ToolFinish, even when a timeout abandoned the child (the late-event rule, an amendment to ADR 0004).

A Nested event’s Seq comes from the parent’s counter, so the parent stream stays totally ordered with the child’s events in place. The inner event keeps its own RunID and Seq. A grandchild’s event is a Nested inside a Nested. wefttest.Flatten unwraps them all for a test.

A child run’s id is <parent>/<step>/<callID>: run-1/0/c1 is call c1 of step 0 of run run-1. A call executed under Approve gets <parent>/resume/<callID>. The id is on the nested RunStart (ID) and RunFinish (RunID), and on weft.CallFromContext inside the child’s tools; the parent’s tool result does not carry it.

The child’s total usage is added to the parent’s RunResult.Usage and recorded per call on StepRecord.SubagentUsage. The step’s own Usage stays the model call’s numbers:

subagents/main.go
res, err := orchestrator.Generate(ctx, weft.Prompt("What is new in tool-use evaluation?"))
if err != nil {
return err
}
step := res.Steps[0]
fmt.Fprintf(w, "step 0 model call: %d in, %d out\n", step.Usage.InputTokens, step.Usage.OutputTokens)
for callID, u := range step.SubagentUsage { // the child's total, keyed by the delegating call
fmt.Fprintf(w, "subagent %s: %d in, %d out\n", callID, u.InputTokens, u.OutputTokens)
}
fmt.Fprintf(w, "run total: %d in, %d out\n", res.Usage.InputTokens, res.Usage.OutputTokens)

subagents/main.go on GitHub

step 0 model call: 10 in, 5 out
subagent c1: 20 in, 10 out
run total: 40 in, 20 out

A failed child’s partial usage counts too, as long as the child returns before its call finishes. A child abandoned by weft.Timeout is the exception: its usage is recorded only when the child run returns, after the timed-out call has finished, so none of it reaches RunResult.Usage, SubagentUsage or the parent’s UsageLimit, including the steps it ran before the deadline.

Because the child’s usage is otherwise the parent’s, weft.UsageLimit on the parent counts delegated work (rule 13). It counts it once the delegating call returns: the parent checks its limit only between its own steps, so it cannot stop a child that is running (How does a run stop?). A weft/thread pool child is the exception: it is a session, its usage is on its receipt, never on the parent run’s Usage (Run bounded child sessions with a pool).

A child that fails never fails the parent run. Its failure is a coded tool error the parent model reads and reacts to:

subagents/main.go
res, err := orchestrator.Generate(ctx, weft.Prompt("What is new in tool-use evaluation?"))
if err != nil {
return err // the child's failure is not a parent run error
}
r := res.Steps[0].Results[0]
fmt.Fprintf(w, "error result: %t\n%s\n", r.IsError, r.Content)

subagents/main.go on GitHub

error result: true
SUBAGENT_FAILED: agent "research" failed at step 0: model stream: provider down

The three codes are exported constants, so policy middleware can branch on them without parsing text:

ConstantResult textWhen
weft.CodeSubagentFailedSUBAGENT_FAILED: agent "<tool>" failed at step N: <cause>The child run returned an error. Its *RunError is on ToolError.Err, reachable with errors.As in middleware.
weft.CodeSubagentPendingSUBAGENT_PENDING: agent "<tool>" ended awaiting approval of N call(s)The child parked a call. The parent’s transcript has nowhere to carry it.
weft.CodeSubagentCycleSUBAGENT_CYCLE: agent "<tool>" is already running in this call chainThe child is already running above this call; refused before any model call.

The messages name the tool, not the child agent’s Name: the tool name is what the parent model called. The child’s own name is on the nested RunStart.Agent. Agents are immutable, so a cycle cannot be built at construction; a weft.ToolSource can close one at run time, and the guard compares *Agent pointers.

subagents/main.go streams a delegation, reads its usage, and fails a child:

subagents/main.go
// Command subagents runs the examples of the guide "Delegate to another
// agent (subagents)": go run ./subagents. Every model is scripted with
// wefttest, so it runs offline; swap in a provider adapter for a real one.
package main
import (
"context"
"errors"
"fmt"
"io"
"os"
"time"
"github.com/weftgo/weft"
"github.com/weftgo/weft/wefttest"
)
type SearchInput struct {
Query string `json:"query" jsonschema:"what to search for"`
}
// newOrchestrator builds a researcher child and an orchestrator that
// delegates to it. childModel scripts the child; the parent calls the
// research tool once and then answers.
func newOrchestrator(childModel weft.Model) *weft.Agent {
deepSearch := weft.Tool("deep_search", "Search the paper index.",
func(_ context.Context, in SearchInput) (string, error) {
return "3 papers on " + in.Query, nil
})
parentModel := wefttest.Script(
wefttest.ToolCalls(wefttest.Call{ID: "c1", Name: "research", Args: `{"prompt":"Find recent work on tool-use evaluation."}`}),
wefttest.Say("Research found three papers."),
)
researcher := weft.New(childModel,
weft.Name("researcher"),
weft.Instructions("You research one question and answer briefly."),
deepSearch,
)
orchestrator := weft.New(parentModel,
weft.Name("orchestrator"),
weft.Subagent("research", "Research a topic in depth.", researcher,
weft.Timeout(2*time.Minute), // bounds the child run
),
)
return orchestrator
}
func researchScript() weft.Model {
return wefttest.Script(
wefttest.ToolCalls(wefttest.Call{ID: "c1", Name: "deep_search", Args: `{"query":"tool-use evaluation"}`}),
wefttest.Say("I found 3 papers on tool-use evaluation."),
)
}
// nested streams the orchestrator and prints the child's events.
func nested(ctx context.Context, w io.Writer) error {
orchestrator := newOrchestrator(researchScript())
run := orchestrator.Stream(ctx, weft.Prompt("What is new in tool-use evaluation?"), weft.RunID("run-1"))
for ev, err := range run.Events() {
if err != nil {
return err
}
switch ev := ev.(type) {
case weft.ToolStart:
fmt.Fprintf(w, "parent tool %s: %s\n", ev.CallID, ev.Name)
case weft.Nested: // one event of the child run, owned by parent call ev.CallID
switch inner := ev.Event.(type) {
case weft.RunStart:
fmt.Fprintf(w, " child %s started: %s\n", inner.ID, inner.Agent)
case weft.ToolFinish:
fmt.Fprintf(w, " child tool %s → %s\n", inner.Name, inner.Content)
case weft.RunFinish:
fmt.Fprintf(w, " child %s finished in %d steps\n", inner.RunID, inner.Steps)
}
case weft.ToolFinish:
fmt.Fprintf(w, "parent tool %s → %s\n", ev.CallID, ev.Content)
}
}
return nil
}
// usage shows the child's usage rolled into the parent's result.
func usage(ctx context.Context, w io.Writer) error {
orchestrator := newOrchestrator(researchScript())
res, err := orchestrator.Generate(ctx, weft.Prompt("What is new in tool-use evaluation?"))
if err != nil {
return err
}
step := res.Steps[0]
fmt.Fprintf(w, "step 0 model call: %d in, %d out\n", step.Usage.InputTokens, step.Usage.OutputTokens)
for callID, u := range step.SubagentUsage { // the child's total, keyed by the delegating call
fmt.Fprintf(w, "subagent %s: %d in, %d out\n", callID, u.InputTokens, u.OutputTokens)
}
fmt.Fprintf(w, "run total: %d in, %d out\n", res.Usage.InputTokens, res.Usage.OutputTokens)
return nil
}
// failure: the child's model fails; the parent model reads it as data.
func failure(ctx context.Context, w io.Writer) error {
orchestrator := newOrchestrator(wefttest.Script(wefttest.Fail(errors.New("provider down"))))
res, err := orchestrator.Generate(ctx, weft.Prompt("What is new in tool-use evaluation?"))
if err != nil {
return err // the child's failure is not a parent run error
}
r := res.Steps[0].Results[0]
fmt.Fprintf(w, "error result: %t\n%s\n", r.IsError, r.Content)
fmt.Fprintln(w, "answer:", res.Text())
return nil
}
func run(ctx context.Context, w io.Writer) error {
steps := []struct {
title string
fn func(context.Context, io.Writer) error
}{
{"nested events", nested},
{"usage", usage},
{"failure", failure},
}
for _, s := range steps {
fmt.Fprintf(w, "== %s\n", s.title)
if err := s.fn(ctx, w); err != nil {
return fmt.Errorf("%s: %w", s.title, err)
}
}
return nil
}
func main() {
if err := run(context.Background(), os.Stdout); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}

View subagents/main.go on GitHub

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

Terminal window
go run ./subagents
go test ./subagents
== nested events
parent tool c1: research
child run-1/0/c1 started: researcher
child tool deep_search → 3 papers on tool-use evaluation
child run-1/0/c1 finished in 2 steps
parent tool c1 → I found 3 papers on tool-use evaluation.
== usage
step 0 model call: 10 in, 5 out
subagent c1: 20 in, 10 out
run total: 40 in, 20 out
== failure
error result: true
SUBAGENT_FAILED: agent "research" failed at step 0: model stream: provider down
answer: Research found three papers.
  • Keep approval-gated tools in the orchestrator. A child that parks returns SUBAGENT_PENDING and its call cannot be decided from the parent; put RequireApproval on the subagent tool instead. (Source: ADR 0014, weft/core/subagent.go:23-28)
  • Pass a built agent. weft.Subagent panics when child is nil, with weft: Subagent "research" called with a nil agent for a tool named research, at construction rather than on the first call. (Source: weft/core/subagent.go:304-308)
  • Do not count on an Output child failing when it never submits. Without a valid submit_output call the result falls back to the child’s final text, with no error and no code, so the parent model reads prose where it expected JSON. (Source: weft/core/subagent.go:264-270, 331-336; weft/core/output.go:135-153)
  • Write the delegation’s description for the parent model. It is the parent’s entire routing surface for the child. (Source: weft/core/subagent.go:279-282)
  • Set a Timeout on long children, and bound what it leaves uncounted. The child runs on the call’s deadline context, so at the deadline its in-flight model request is cancelled and it calls the model no more. The steps it ran before the deadline are not counted: none of their usage reaches the parent, so the parent’s UsageLimit cannot cover them. Bound the child itself with its own MaxSteps or UsageLimit. (Source: ADR 0014, “Cancellation and timeouts” and the late-event rule; weft/core/subagent.go:318-319; weft/core/loop.go:1265-1272, 1381, 2156)
  • Configure the child agent, not the parent’s run. A per-run Thinking, UseModel, Params, Instructions, ToolChoice, OnlyTools or lowered MaxSteps changes the parent’s model calls only. Build the child with the setting it needs, or build a second child agent for the variant. To vary a child per run, give it a weft.PrepareStep that reads the inherited weft.MetadataFromContext(ctx): a child whose PrepareStep set ThinkHigh on think=high sent level 4 under a parent run with Metadata{"think": "high"}. (Source: weft/core/subagent.go:316; weft/core/loop.go:63; weft/core/agent.go:176)
  • Budget with UsageLimit on the parent, and bound each child itself. Delegated usage counts toward the parent’s limit, and there is no depth cap. The parent checks the limit only before its next model call, so every child of the step runs to its own end first. Give each child agent its own UsageLimit and MaxSteps to bound one delegation. (Source: ADR 0014, “The cycle guard”; AGENTS.md rule 13; weft/core/loop.go:849, 1102-1116)
  • Read SubagentUsage for attribution, not StepRecord.Usage. The step’s usage is its own model call only. (Source: ADR 0014, “Usage”)

Symbols used: weft.Subagent · weft.Nested · weft.CodeSubagentFailed · weft.CodeSubagentPending · weft.CodeSubagentCycle · weft.StepRecord · weft.RunResult · weft.ToolError · weft.Timeout · weft.MaxResultBytes · weft.Parallelism · weft.UsageLimit · weft.Output · weft.RunID · weft.Name · weft.Instructions · weft.Tool · weft.New · ExampleSubagent · wefttest.Flatten · wefttest.Script