---
title: Fan out many tool calls safely
description: Run a step's many tool calls under weft.Parallelism, make a shared-state write a weft.Sequential barrier, and cap an oversized result with weft.MaxResultBytes, with results always in call order.
url: https://weftgo.dev/docs/examples/tool-storm/
type: how-to
sources:
  - 'weft/core/agent.go:23-27 (defaults: parallelism 4, result cap 64 KiB), 220-226 (Parallelism), 230-244 (Sequential, the barrier), 524-535 (MaxResultBytes)'
  - weft/core/loop.go:1230 (the parallelism semaphore is per step), 493 (SequentialTools when the run's parallelism is 1), 2201-2222 (capResult and its marker)
  - weft/obsdb/problems.go:40-44 (Truncated)
  - weft/openai/convert.go:91, weft/anthropic/convert.go:96-102 (the adapters honour SequentialTools)
  - weft/AGENTS.md:677-683 (rule 3), 694-697 (rule 8)
  - weft/example_test.go:527 (ExampleSequential)
  - 'weft-arena/internal/suites/realworld.go: rwToolStorm (inspiration only)'
  - docs-site/examples/cookbook/toolstorm/main.go, main_test.go TestToolStorm, TestCapAndBarrierHold
---

# Fan out many tool calls safely

When one step asks for many tools, three options decide what runs. [`weft.Parallelism(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Parallelism) caps how many of the step's calls execute at once (default 4). [`weft.Sequential()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Sequential) on a tool makes it a barrier that runs alone. [`weft.MaxResultBytes(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxResultBytes) cuts a result that is too long, with a marker the model sees. Whatever order the calls finish in, their results join the transcript in call order.

The weather desk in `cookbook/toolstorm/main.go`:

```go title="cookbook/toolstorm/main.go"
ledger := weft.Tool("ledger_append", "Append one entry to the audit ledger.",
	func(_ context.Context, _ EntryInput) (string, error) {
		g.mu.Lock()
		g.ledgerSawRunning = g.now // 0: nothing else is running
		g.mu.Unlock()
		return "ledger entry recorded", nil
	},
	weft.Sequential(), // a barrier: runs alone, under any parallelism
)
forecast := weft.Tool("forecast_report", "The full 14-day forecast for a city (very long).",
	func(_ context.Context, in CityInput) (string, error) {
		return strings.Repeat(in.City+": mild, light wind, 10% rain. ", 600), nil
	},
	weft.MaxResultBytes(2000), // this tool's cap; the agent default is 64 KiB
)
return weft.New(model,
	weft.Name("weather-desk"),
	weft.Parallelism(3), // at most three handlers at once (the default is 4)
	weft.MaxSteps(4),
	getWeather, ledger, forecast,
)
```

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

## How it works

The shape comes from the weft-arena scenario `rw.tool-storm`. In one step the model asks for the weather in six cities, a ledger entry and Oslo's 14-day forecast: eight calls. Each weather lookup takes 50 ms upstream, the ledger is shared state, and the forecast is about 20 KB of text.

The loop starts the calls in call order ([rule 3](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them)) and runs them on a bounded pool:

> **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.

1. `w1`, `w2` and `w3` start at once: `Parallelism(3)`. `w4` starts when one of them finishes, and so on.
2. `l1`, the ledger write, is a barrier. The calls in flight finish first, `l1` runs alone, and the calls after it wait.
3. `f1` runs after the barrier. Its result is cut to 2,000 bytes.
4. The step's results join one tool message in call order, `w1` to `f1`.

## Parallel fan-out

`Parallelism` applies to every run of the agent, one step at a time. As a run option it may only lower the agent's value: a raise fails the run with `ErrInvalidRunOption` before any model call. The program measures what the cap allows: at most three `get_weather` handlers ran at once, and they did overlap. The peak is a timing measurement, 3 on an idle machine and 2 when the scheduler is slow to start a call, so the program prints whether it is within those bounds rather than the number. Each result lands on its own call id, so the six cities never get mixed up:

```go title="cookbook/toolstorm/main.go"
for _, r := range res.Steps[0].Results { // call order, whatever order they finished in
	content := r.Content
	if i := strings.Index(content, "\n…[truncated"); i >= 0 {
		content = fmt.Sprintf("%d bytes kept, then %q", i, content[i+1:])
	}
	fmt.Fprintf(w, "%s %s → %s\n", r.CallID, r.Name, content)
}
```

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

## Sequential barrier

On a tool, `Sequential()` is a barrier: the dispatcher lets every in-flight call of the step finish, runs this call alone, then resumes the step's parallelism for the calls after it. The other tools keep running in parallel; only this one is serialized. That is the setting for a tool with shared state, such as an append-only ledger. The program checks that no weather call was running while `ledger_append` ran.

On the agent, `Sequential()` sets the run's parallelism to 1, so every call runs one at a time in call order. When the parallelism is 1 the loop also sets `ModelRequest.SequentialTools`, and the openai and anthropic adapters ask the provider not to emit parallel batches at all. The package example [`ExampleSequential`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Sequential) puts a `write` barrier between two `check` calls under `Parallelism(4)`, and the results come back `check`, `write`, `check`.

## Cap a result

A result longer than its cap is cut on a rune boundary and ends with a marker naming what the model did not receive ([rule 8](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them)):

```text
…[truncated 18400 bytes]
```

The agent's default cap is 64 KiB for every tool. `MaxResultBytes` on a tool overrides it for that tool alone, and `MaxResultBytes(0)` lifts the cap for a tool whose output must arrive whole. The cap applies to successes, failures and panics alike. `Agent.CallTool` returns uncapped output: the cap is a run policy, applied by the loop.

## What to look at in Studio

The program records the run with `otel.Install(otel.Local(""))`:

- On the [run page](https://weftgo.dev/docs/observe/studio/run-page/)'s waterfall, step 0's eight `execute_tool` spans show the shape: three bars at a time, the ledger alone, the forecast after it.
- The cut result counts under `truncated` in the run's problem counters, from the span's `weft.tool.truncated_bytes`. The program reads it back: `truncated results: 1`.
- The [Timeline in the devtools panel](https://weftgo.dev/docs/observe/devtools/reading-runs/) draws the same rows one level deep.

![The weather desk's run in Studio: step 0's six get_weather calls run three at a time, two waves of overlapping bars, then ledger_append and forecast_report, with one result cut by the result cap counted in the header](https://weftgo.dev/docs/_astro/studio-run-tool-storm.light.mfIRAasa.webp)

*The weather desk's step 0 on the waterfall: get_weather calls three at a time, then ledger_append and forecast_report; the header counts the result the cap cut.*

## The weft features it combines

| Feature | What it does here | Guide |
|---|---|---|
| `weft.Parallelism` | at most three calls at once | [What happens in one step?](https://weftgo.dev/docs/concepts/the-loop/) |
| `weft.Sequential` on a tool | the ledger write runs alone | [Set per-tool policy](https://weftgo.dev/docs/guides/tool-policy/) |
| `weft.MaxResultBytes` on a tool | cuts the forecast to 2,000 bytes | [Set per-tool policy](https://weftgo.dev/docs/guides/tool-policy/) |
| Results in call order | `res.Steps[0].Results` follows the calls | [What does a run return?](https://weftgo.dev/docs/concepts/runs/) |
| Problem counters | count the truncated result | [Read a run in Studio](https://weftgo.dev/docs/observe/studio/run-page/) |

## The program

```go title="cookbook/toolstorm/main.go"
// Command toolstorm is the recipe "Fan out many tool calls safely":
// go run ./cookbook/toolstorm. One step asks for the weather in six
// cities, a ledger write and a very long forecast. Parallelism(3) caps
// how many calls run at once, the Sequential ledger write runs alone, the
// oversized forecast is cut with a marker the model sees, and every
// result lands on its own call in call order. The model is scripted with
// wefttest, so it runs offline; the run is recorded to the local sink
// ($WEFT_DB, else ./.weft/weft.db).
package main

import (
	"context"
	"fmt"
	"io"
	"os"
	"strings"
	"sync"
	"time"

	"github.com/weftgo/weft"
	"github.com/weftgo/weft/otel"
	"github.com/weftgo/weft/wefttest"
)

type CityInput struct {
	City string `json:"city" jsonschema:"the city name"`
}

type EntryInput struct {
	Entry string `json:"entry" jsonschema:"the ledger line"`
}

// gauge tracks how many get_weather handlers run at once, and how many
// were running when the ledger write ran.
type gauge struct {
	mu               sync.Mutex
	now, peak        int
	ledgerSawRunning int
}

func (g *gauge) enter() {
	g.mu.Lock()
	g.now++
	g.peak = max(g.peak, g.now)
	g.mu.Unlock()
}

func (g *gauge) exit() {
	g.mu.Lock()
	g.now--
	g.mu.Unlock()
}

var weather = map[string]string{
	"Paris": "18°C cloudy", "Tokyo": "24°C clear", "Lima": "16°C mist",
	"Cairo": "33°C sunny", "Oslo": "7°C rain", "Sydney": "21°C windy",
}

// newDesk builds the weather desk; g watches its handlers.
func newDesk(model weft.Model, g *gauge) *weft.Agent {
	getWeather := weft.Tool("get_weather", "Current weather for one city.",
		func(_ context.Context, in CityInput) (map[string]string, error) {
			g.enter()
			defer g.exit()
			time.Sleep(50 * time.Millisecond) // a slow upstream: calls overlap
			w, ok := weather[in.City]
			if !ok {
				return nil, weft.Errorf("UNKNOWN_CITY", "no station for %q", in.City)
			}
			return map[string]string{"city": in.City, "weather": w}, nil
		})
	ledger := weft.Tool("ledger_append", "Append one entry to the audit ledger.",
		func(_ context.Context, _ EntryInput) (string, error) {
			g.mu.Lock()
			g.ledgerSawRunning = g.now // 0: nothing else is running
			g.mu.Unlock()
			return "ledger entry recorded", nil
		},
		weft.Sequential(), // a barrier: runs alone, under any parallelism
	)
	forecast := weft.Tool("forecast_report", "The full 14-day forecast for a city (very long).",
		func(_ context.Context, in CityInput) (string, error) {
			return strings.Repeat(in.City+": mild, light wind, 10% rain. ", 600), nil
		},
		weft.MaxResultBytes(2000), // this tool's cap; the agent default is 64 KiB
	)
	return weft.New(model,
		weft.Name("weather-desk"),
		weft.Parallelism(3), // at most three handlers at once (the default is 4)
		weft.MaxSteps(4),
		getWeather, ledger, forecast,
	)
}

// stormScript asks for everything in one step.
func stormScript() *wefttest.Model {
	var calls []wefttest.Call
	for i, c := range []string{"Paris", "Tokyo", "Lima", "Cairo", "Oslo", "Sydney"} {
		calls = append(calls, wefttest.Call{ID: fmt.Sprintf("w%d", i+1), Name: "get_weather", Args: `{"city":"` + c + `"}`})
	}
	calls = append(calls,
		wefttest.Call{ID: "l1", Name: "ledger_append", Args: `{"entry":"weather sweep for 6 cities"}`},
		wefttest.Call{ID: "f1", Name: "forecast_report", Args: `{"city":"Oslo"}`},
	)
	return wefttest.Script(wefttest.ToolCalls(calls...),
		wefttest.Say("Paris 18°C, Tokyo 24°C, Lima 16°C, Cairo 33°C, Oslo 7°C, Sydney 21°C."))
}

func run(ctx context.Context, w io.Writer) error {
	defer otel.Install(otel.Local(""))()

	g := &gauge{}
	res, err := newDesk(stormScript(), g).Generate(ctx, weft.Prompt("Weather for six cities, a ledger entry and Oslo's forecast."))
	if err != nil {
		return err
	}
	for _, r := range res.Steps[0].Results { // call order, whatever order they finished in
		content := r.Content
		if i := strings.Index(content, "\n…[truncated"); i >= 0 {
			content = fmt.Sprintf("%d bytes kept, then %q", i, content[i+1:])
		}
		fmt.Fprintf(w, "%s %s → %s\n", r.CallID, r.Name, content)
	}
	// The peak is a timing measurement: 3 on an idle machine, 2 when the
	// scheduler is slow to start the third call. Both are within the cap.
	fmt.Fprintln(w, "get_weather calls overlapped, never more than 3 at once:", g.peak >= 2 && g.peak <= 3)
	fmt.Fprintln(w, "calls running beside the ledger write:", g.ledgerSawRunning)

	row, err := otel.LocalDB().Run(ctx, res.ID)
	if err != nil {
		return err
	}
	fmt.Fprintln(w, "recorded: truncated results:", row.Problems.Truncated)
	return nil
}

func main() {
	if err := run(context.Background(), os.Stdout); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
```

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

[View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/cookbook/toolstorm) · run it from `docs-site/examples`:

```sh
go run ./cookbook/toolstorm
go test ./cookbook/toolstorm
```

```text
w1 get_weather → {"city":"Paris","weather":"18°C cloudy"}
w2 get_weather → {"city":"Tokyo","weather":"24°C clear"}
w3 get_weather → {"city":"Lima","weather":"16°C mist"}
w4 get_weather → {"city":"Cairo","weather":"33°C sunny"}
w5 get_weather → {"city":"Oslo","weather":"7°C rain"}
w6 get_weather → {"city":"Sydney","weather":"21°C windy"}
l1 ledger_append → ledger entry recorded
f1 forecast_report → 2000 bytes kept, then "…[truncated 18400 bytes]"
get_weather calls overlapped, never more than 3 at once: true
calls running beside the ledger write: 0
recorded: truncated results: 1
```

The tests also run the storm five times and check, each time, that the cap held, that calls overlapped and that the ledger ran alone.

## Best practices & gotchas

- **Mark shared-state writes `Sequential`.** Parallel calls to one ledger or one file race; a barrier serializes only that tool and leaves the rest parallel. (Source: `weft/core/agent.go:230-244`)
- **`Parallelism` bounds concurrency within one step only.** It does not bound calls across steps or across concurrent runs; for an upstream with a rate limit, add rate-limit middleware, as in [the governed stack](https://weftgo.dev/docs/examples/governed-stack/#rate-limit). A per-run raise is refused, so a run cannot escape the agent's bound. (Source: `weft/core/agent.go:220-226`, `weft/core/loop.go:1230`, `weft/mw/example_test.go:180`)
- **Cap results per tool, not only per agent.** The default 64 KiB fits most tools; a known-large tool gets its own cap, and one whose output must arrive whole gets `MaxResultBytes(0)`. (Source: `weft/core/agent.go:524-535`)
- **Read results by call id, not by position in time.** They are in call order whatever order the calls finished in. (Source: AGENTS.md rule 3)
- **Expect the model to see the marker.** A cut result ends with `…[truncated N bytes]`, so the model knows it holds a prefix; nothing is cut silently. (Source: `weft/core/loop.go:2201-2222`, AGENTS.md rule 8)

## See also

- [What happens in one step? The loop and parallel tools](https://weftgo.dev/docs/concepts/the-loop/): how the dispatcher orders calls and events
- [Set per-tool policy: timeouts, caps, ordering and strict input](https://weftgo.dev/docs/guides/tool-policy/)
- [Survive flaky infrastructure](https://weftgo.dev/docs/examples/flaky-infrastructure/): when the parallel calls fail
- [Read a run in Studio](https://weftgo.dev/docs/observe/studio/run-page/)

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.MaxResultBytes`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxResultBytes) · [`weft.ErrInvalidRunOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrInvalidRunOption) · [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest) · [`Agent.CallTool`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.CallTool) · [`weft.Errorf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Errorf) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install) · [`obsdb.Problems`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#Problems) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script)
