What happens in one step? The loop and parallel tools
A step is one model call followed by one batch of tool calls. The loop sends the model a request, records the assistant message it streams back, runs every tool call in that message, puts the results on one tool message, and then either ends the run or starts the next step. Within a batch, calls start in call order, up to weft.Parallelism of them run at once (4 by default), and their results land in call order.
Three calls in one step, two at a time, in concepts/loop.go:
agt := weft.New(model, weft.Parallelism(2), // at most two of a step's calls execute at once slowTool("inventory", 200*time.Millisecond, false), slowTool("pricing", 20*time.Millisecond, false), slowTool("shipping", 20*time.Millisecond, true),)run := agt.Stream(ctx, weft.Prompt("Quote order 1234."))for ev, err := range run.Events() { if err != nil { return err } switch ev := ev.(type) { case weft.StepStart: fmt.Fprintf(w, "step %d starts\n", ev.Index) case weft.ToolStart: fmt.Fprintf(w, " seq %d start %s\n", ev.Seq, ev.Name) case weft.ToolFinish: fmt.Fprintf(w, " seq %d finish %s (error: %v)\n", ev.Seq, ev.Name, ev.IsError) case weft.RunFinish: fmt.Fprintf(w, "run finishes: %s\n", ev.StoppedBy) }}res, err := run.Wait()if err != nil { return err}for _, r := range res.Steps[0].Results { // call order, whatever order they finished in fmt.Fprintf(w, "result %s: %s\n", r.Name, r.Content)}step 0 starts seq 1 start inventory seq 2 start pricing seq 3 finish pricing (error: false) seq 4 start shipping seq 5 finish shipping (error: true) seq 6 finish inventory (error: false)step 1 startsrun finishes: final_answerresult inventory: inventory okresult pricing: pricing okresult shipping: shipping: carrier unavailableshipping waited for a free slot, started when pricing finished, and failed; inventory kept running and finished last. The results are still in call order, and the failed call is a result like the others.
How it works
Section titled “How it works”The run repeats steps until one of three things happens after a step: the model made no tool calls, a StopWhen condition matched, or calls are waiting for approval. One exception: when a steering source delivers a message at what would be the final step, the run takes one more step instead of ending (Steer a running turn). Before each further model call, the loop checks the budgets; MaxSteps bounds the number of steps. How does a run stop? covers every exit.
Life of a call
Section titled “Life of a call”docs/life-of-a-call.md in the weft repository lists where every phase of a step and of a tool call sits. Phases are documentation, not hooks: behaviour attaches at the two middleware seams, WrapModel and WrapTools, and observation at the tap and in the loop’s own spans and log lines.
A step, in order:
- The loop builds a
weft.ModelRequest: the instructions, the transcript so far, the step’s tools (aToolSource’s snapshot, else the static list), the thinking level,SequentialTools. weft.PrepareStepfunctions may rewrite it. What they return is what the step advertises and dispatches against.- The system prompt becomes the instructions plus the
PromptSnippettext of the advertised tools. - A
chatspan begins and the request goes through theWrapModelchain (first listed is outermost) to the adapter and the provider. - The loop enforces the stream contract: exactly one
ModelFinish, nothing after it. A violation fails the run withErrModelContract(see What is a Model?). - The step’s output joins the transcript as one assistant message: reasoning parts, text, tool calls.
- The tool calls run as one batch, below. A
max_tokensfinish with calls runs none of them: each gets an error result instead. StepFinishis emitted. Pending approvals, no calls, or a matchingStopWhenend the run withRunFinish.- Otherwise the run reaches the continuation point:
MaxModelRetries,UsageLimitandDetectLoopsare checked, first breach wins, and the next step begins.
A tool call, in order:
- The dispatcher acquires a slot (
Parallelism(n);Sequential()is one at a time; aSequentialtool is a barrier). ToolStartis emitted with itsSeq.- Inside the containment boundary, an
execute_toolspan begins, and the call goes through the agent’sWrapToolschain, then the tool’s own chain, then the base: resolve the name (unknown isNO_SUCH_TOOL), park aRequireApprovalcall that is not approved, decode the arguments (failure isINVALID_INPUT), run the handler. - At the containment boundary a panic becomes
tool "X" panicked: …and aTimeoutbecomestool "X" timed out after 10s(with the configured duration); neither fails the run. - The result is rendered (
*ToolErrorasCODE: message, any other error as its text) and capped atMaxResultByteswith a visible marker. - The span ends, then
ToolFinishis emitted, and the result joins the step’s tool message in call order. A parked call gets noToolFinish.
A subagent’s child run sits inside the handler line: it holds a slot like any tool, and its events arrive wrapped in Nested between the delegating call’s ToolStart and ToolFinish.
The two conventions the same document fixes:
- Context decoration. Middleware that verifies something (a user, a tenant, a quota) puts it on
ctxbefore callingnext; the handler reads it through a typed accessor, as it readsweft.CallFromContext. Decorate only with what the middleware verified. - Error shaping. Handlers return
*weft.ToolErrorwhen the model should branch on a code;mw.MapErrorscodes everything else centrally. The cause inToolError.Erris for audit logs anderrors.As, never for the model.
Add behaviour with middleware applies both.
Parallel tools
Section titled “Parallel tools”A step’s tool calls fan out over goroutines. weft.Parallelism(n) sets how many execute at once, 4 by default; values below 1 are ignored. As a run option it may only lower the agent’s value. weft.Sequential() on the agent runs calls one at a time, each finishing before the next starts.
Three orders are kept separately, and each is fixed:
- Start order is call order. The slot is acquired on the dispatching goroutine, in call order, before the call’s goroutine is spawned, and
ToolStartis emitted there. - Result order is call order. Results are collected by index and land on the tool message in the order the model requested them, whatever order they finished in.
- Event order is
Seqorder.ToolStart,ToolFinishandNestedevents take theirSeqand are emitted under one lock, so the observed order never contradicts the numbers and a stream replays exactly.
A tool built with weft.Sequential() is a barrier: the dispatcher lets every call in flight finish, runs that call alone, then resumes parallel dispatch for the calls after it. Other tools keep their parallelism.
Failure and cancellation follow fixed rules:
- A failing tool never cancels its siblings. An error, a panic or a timeout is that call’s result; only the run’s
ctxcancels other calls. - No tool starts after the run is canceled. A call that never got a slot gets the result
run canceled before the tool startedand no events, so everyToolFinishfollows itsToolStart. - A hung tool never hangs the run. With
weft.Timeouton the tool or the agent, an expired call is recorded as an error result and its goroutine is abandoned. Without a timeout, only the run’sctxbounds a call.
Under Sequential() or Parallelism(1) the loop also sets ModelRequest.SequentialTools. The OpenAI and Anthropic adapters then ask the provider not to emit parallel batches at all; Gemini has no such switch, so with the Google adapter the loop’s single slot is what serializes the calls.
What it does not do
Section titled “What it does not do”- No phase is a hook. You cannot attach code “after decode” or “before render”; behaviour goes in middleware around the whole call, and observation in a tap. Adding a third seam needs an ADR.
- No automatic waiting for approval-gated tools. A
RequireApprovalcall parks, and its siblings in the same step still run before the run ends.Sequential()does not change that: it is an execution barrier, and a parked call returns at once. If siblings must wait for the decision, park them too (weft.ParkOn, or middleware returningErrApprovalRequired) or deny them in middleware such asmw.Allow. - No per-run timeout option. A run’s deadline is its
ctx;weft.Timeoutbounds single tool calls.
Complete example
Section titled “Complete example”concepts/loop.go defines three tools of different speeds, one failing, and streams one step of them two at a time:
package main
import ( "context" "errors" "fmt" "io" "time"
"github.com/weftgo/weft" "github.com/weftgo/weft/wefttest")
// QuoteInput is the input of the three quote tools.type QuoteInput struct { OrderID string `json:"order_id"`}
// slowTool is a tool that takes d to answer; fail makes it return an error// instead.func slowTool(name string, d time.Duration, fail bool) *weft.ToolDef { return weft.Tool(name, "Quote one part of an order.", func(ctx context.Context, in QuoteInput) (string, error) { select { case <-time.After(d): case <-ctx.Done(): return "", ctx.Err() } if fail { return "", errors.New(name + ": carrier unavailable") } return name + " ok", nil })}
// quoteScript asks for the three quote tools in one step, then answers.func quoteScript() *wefttest.Model { return wefttest.Script( wefttest.ToolCalls( wefttest.Call{Name: "inventory", Args: `{"order_id":"1234"}`}, wefttest.Call{Name: "pricing", Args: `{"order_id":"1234"}`}, wefttest.Call{Name: "shipping", Args: `{"order_id":"1234"}`}, ), wefttest.Say("Order 1234: in stock and priced; no shipping quote yet."), )}
// demoLoop runs one step's three tool calls two at a time and prints the// events in Seq order, then the results in call order.func demoLoop(ctx context.Context, w io.Writer) error { model := quoteScript() agt := weft.New(model, weft.Parallelism(2), // at most two of a step's calls execute at once slowTool("inventory", 200*time.Millisecond, false), slowTool("pricing", 20*time.Millisecond, false), slowTool("shipping", 20*time.Millisecond, true), ) run := agt.Stream(ctx, weft.Prompt("Quote order 1234.")) for ev, err := range run.Events() { if err != nil { return err } switch ev := ev.(type) { case weft.StepStart: fmt.Fprintf(w, "step %d starts\n", ev.Index) case weft.ToolStart: fmt.Fprintf(w, " seq %d start %s\n", ev.Seq, ev.Name) case weft.ToolFinish: fmt.Fprintf(w, " seq %d finish %s (error: %v)\n", ev.Seq, ev.Name, ev.IsError) case weft.RunFinish: fmt.Fprintf(w, "run finishes: %s\n", ev.StoppedBy) } } res, err := run.Wait() if err != nil { return err } for _, r := range res.Steps[0].Results { // call order, whatever order they finished in fmt.Fprintf(w, "result %s: %s\n", r.Name, r.Content) } return nil}Run it from docs-site/examples:
go run ./concepts loopgo test ./conceptsstep 0 starts seq 1 start inventory seq 2 start pricing seq 3 finish pricing (error: false) seq 4 start shipping seq 5 finish shipping (error: true) seq 6 finish inventory (error: false)step 1 startsrun finishes: final_answerresult inventory: inventory okresult pricing: pricing okresult shipping: shipping: carrier unavailableBest practices & gotchas
Section titled “Best practices & gotchas”- Mark tools that share state
Sequential(). Parallel calls of the same step run at the same time; a barrier tool runs alone. (Source:weft/core/agent.go:233-244, deep dive §6) - Honour
ctxin every handler. A timed-out handler is abandoned, not stopped; a write after the timeout is lost, and side effects must checkctxfirst. (Source: AGENTS.md rule 9, deep dive §6 edge cases) - Consume
Events()promptly or useGenerate. Tool events are emitted under the step’s ordering lock, so a slow consumer delays the step’s later tools. (Source:weft/core/run.go:757-771) - Read results in call order, events in
Seqorder. Completion order is visible only in the events. (Source: AGENTS.md rule 3,weft/core/loop.go:1188-1206)
See also
Section titled “See also”- Set per-tool policy: timeouts, caps, ordering and strict input
- Stream a run’s events
- Add behaviour with middleware (the two seams)
- The agent loop, from first principles
- Fan out many tool calls safely
Symbols used: weft.Parallelism · weft.Sequential · weft.Timeout · weft.ModelRequest · weft.PrepareStep · weft.CallFromContext · weft.ToolStart · weft.ToolFinish · weft.StepStart · weft.RunFinish · Agent.Stream · weft.Tool · wefttest.Script