---
title: What happens in one step? The loop and parallel tools
description: Each step is one model call followed by one batch of tool calls; the calls start in call order, run up to Parallelism at once, and their results land in call order.
url: https://weftgo.dev/docs/concepts/the-loop/
type: concept
sources:
  - weft/docs/life-of-a-call.md:1-133
  - weft/docs/agent-loop-deep-dive.md:133-180 (anatomy of one step), 822-972 (concurrency)
  - weft/AGENTS.md:79 (Parallelism), 101 (life-of-a-call), rules 1, 3, 9, 10, 11, 13
  - weft/README.md:28
  - weft/core/agent.go:220-244 (Parallelism, Sequential)
  - weft/core/loop.go:471-866 (the step loop), 1188-1441 (execTools — slots, Seq, barrier, cancellation), 1818-1865 (callTool), 1964-2204 (timeout and panic containment, result cap)
  - weft/core/model.go:178-184 (SequentialTools)
  - weft/CHANGELOG.md:6667
  - docs-site/examples/concepts/loop.go, concepts_test.go TestDemos/loop
---

# What happens in one step? The loop and parallel tools

A [step](https://weftgo.dev/docs/reference/glossary/#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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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`:

```go title="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)
}
```

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

```text
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 starts
run finishes: final_answer
result inventory: inventory ok
result pricing: pricing ok
result shipping: shipping: carrier unavailable
```

`shipping` 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

> **Diagram:** agt.Generate starts a run (RunStart). Each step is one model call, one chat span. When the model asks for tools, each call starts (ToolStart), the tools run in parallel, and their results come back (ToolFinish) to the model as one tool message; the step ends with StepFinish and, if the budgets allow, the next step calls the model again. MaxSteps bounds the loop, 10 steps by default. The run ends at RunFinish when the model answers with no tool calls, when StopWhen matches, or when calls are pending approval.

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](https://weftgo.dev/docs/guides/steering/)). Before each further model call, the loop checks the budgets; `MaxSteps` bounds the number of steps. [How does a run stop?](https://weftgo.dev/docs/concepts/budgets-and-stopping/) covers every exit.

## 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](https://weftgo.dev/docs/reference/glossary/#seam), `WrapModel` and `WrapTools`, and observation at the [tap](https://weftgo.dev/docs/reference/glossary/#tap) and in the loop's own spans and log lines.

**A step**, in order:

1. The loop builds a [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest): the instructions, the transcript so far, the step's tools (a `ToolSource`'s snapshot, else the static list), the thinking level, `SequentialTools`.
2. [`weft.PrepareStep`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#PrepareStep) functions may rewrite it. What they return is what the step advertises and dispatches against.
3. The system prompt becomes the instructions plus the `PromptSnippet` text of the advertised tools.
4. A `chat` span begins and the request goes through the `WrapModel` chain (first listed is outermost) to the adapter and the provider.
5. The loop enforces the stream contract: exactly one `ModelFinish`, nothing after it. A violation fails the run with `ErrModelContract` (see [What is a Model?](https://weftgo.dev/docs/concepts/models/#the-model-contract)).
6. The step's output joins the transcript as one assistant message: reasoning parts, text, tool calls.
7. The tool calls run as one batch, below. A `max_tokens` finish with calls runs none of them: each gets an error result instead.
8. `StepFinish` is emitted. Pending approvals, no calls, or a matching `StopWhen` end the run with `RunFinish`.
9. Otherwise the run reaches the continuation point: `MaxModelRetries`, `UsageLimit` and `DetectLoops` are checked, first breach wins, and the next step begins.

**A tool call**, in order:

1. The dispatcher acquires a slot (`Parallelism(n)`; `Sequential()` is one at a time; a `Sequential` tool is a barrier).
2. `ToolStart` is emitted with its `Seq`.
3. Inside the containment boundary, an `execute_tool` span begins, and the call goes through the agent's `WrapTools` chain, then the tool's own chain, then the base: resolve the name (unknown is `NO_SUCH_TOOL`), park a `RequireApproval` call that is not approved, decode the arguments (failure is `INVALID_INPUT`), run the handler.
4. At the containment boundary a panic becomes `tool "X" panicked: …` and a `Timeout` becomes `tool "X" timed out after 10s` (with the configured duration); neither fails the run.
5. The result is rendered (`*ToolError` as `CODE: message`, any other error as its text) and capped at `MaxResultBytes` with a visible marker.
6. The span ends, then `ToolFinish` is emitted, and the result joins the step's tool message in call order. A parked call gets no `ToolFinish`.

A [subagent's](https://weftgo.dev/docs/reference/glossary/#subagent) 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 `ctx` before calling `next`; the handler reads it through a typed accessor, as it reads [`weft.CallFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CallFromContext). Decorate only with what the middleware verified.
- **Error shaping.** Handlers return `*weft.ToolError` when the model should branch on a code; `mw.MapErrors` codes everything else centrally. The cause in `ToolError.Err` is for audit logs and `errors.As`, never for the model.

[Add behaviour with middleware](https://weftgo.dev/docs/guides/middleware/) applies both.

## Parallel tools

> **Diagram:** The model asks for three tools in one step: lookup_order, track_shipment and get_customer. With Parallelism(4), the default, each call runs on its own goroutine at the same time. lookup_order finishes in 140 ms and get_customer in 90 ms; track_shipment times out after 5 seconds and becomes an error result (IsError) instead of failing the run. The results join one tool message in call order, 1, 2, 3, whatever order they finished in, and the model sees all three. Sequential() runs them one at a time instead.

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()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#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 `ToolStart` is 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 `Seq` order.** `ToolStart`, `ToolFinish` and `Nested` events take their `Seq` and 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 `ctx` cancels 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 started` and no events, so every `ToolFinish` follows its `ToolStart`.
- **A hung tool never hangs the run.** With [`weft.Timeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Timeout) on 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's `ctx` bounds 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

- **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 `RequireApproval` call 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 returning `ErrApprovalRequired`) or deny them in middleware such as `mw.Allow`.
- **No per-run timeout option.** A run's deadline is its `ctx`; `weft.Timeout` bounds single tool calls.

## Complete example

`concepts/loop.go` defines three tools of different speeds, one failing, and streams one step of them two at a time:

```go title="concepts/loop.go"
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
}
```

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

Run it from `docs-site/examples`:

```sh
go run ./concepts loop
go test ./concepts
```

```text
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 starts
run finishes: final_answer
result inventory: inventory ok
result pricing: pricing ok
result shipping: shipping: carrier unavailable
```

## 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 `ctx` in every handler.** A timed-out handler is abandoned, not stopped; a write after the timeout is lost, and side effects must check `ctx` first. (Source: AGENTS.md rule 9, deep dive §6 edge cases)
- **Consume `Events()` promptly or use `Generate`.** 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 `Seq` order.** Completion order is visible only in the events. (Source: AGENTS.md rule 3, `weft/core/loop.go:1188-1206`)

## See also

- [Set per-tool policy: timeouts, caps, ordering and strict input](https://weftgo.dev/docs/guides/tool-policy/)
- [Stream a run's events](https://weftgo.dev/docs/guides/streaming/)
- [Add behaviour with middleware (the two seams)](https://weftgo.dev/docs/guides/middleware/)
- [The agent loop, from first principles](https://weftgo.dev/docs/explanation/agent-loop/)
- [Fan out many tool calls safely](https://weftgo.dev/docs/examples/tool-storm/)

Symbols used: [`weft.Parallelism`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Parallelism) · [`weft.Sequential`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Sequential) · [`weft.Timeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Timeout) · [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest) · [`weft.PrepareStep`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#PrepareStep) · [`weft.CallFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#CallFromContext) · [`weft.ToolStart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolStart) · [`weft.ToolFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolFinish) · [`weft.StepStart`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#StepStart) · [`weft.RunFinish`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#RunFinish) · [`Agent.Stream`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.Stream) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script)
