Fan out many tool calls safely
When one step asks for many tools, three options decide what runs. weft.Parallelism(n) caps how many of the step’s calls execute at once (default 4). weft.Sequential() on a tool makes it a barrier that runs alone. weft.MaxResultBytes(n) 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:
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,)How it works
Section titled “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) and runs them on a bounded pool:
w1,w2andw3start at once:Parallelism(3).w4starts when one of them finishes, and so on.l1, the ledger write, is a barrier. The calls in flight finish first,l1runs alone, and the calls after it wait.f1runs after the barrier. Its result is cut to 2,000 bytes.- The step’s results join one tool message in call order,
w1tof1.
Parallel fan-out
Section titled “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:
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)}Sequential barrier
Section titled “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 puts a write barrier between two check calls under Parallelism(4), and the results come back check, write, check.
Cap a result
Section titled “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):
…[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
Section titled “What to look at in Studio”The program records the run with otel.Install(otel.Local("")):
- On the run page’s waterfall, step 0’s eight
execute_toolspans show the shape: three bars at a time, the ledger alone, the forecast after it. - The cut result counts under
truncatedin the run’s problem counters, from the span’sweft.tool.truncated_bytes. The program reads it back:truncated results: 1. - The Timeline in the devtools panel draws the same rows one level deep.


The weft features it combines
Section titled “The weft features it combines”| Feature | What it does here | Guide |
|---|---|---|
weft.Parallelism | at most three calls at once | What happens in one step? |
weft.Sequential on a tool | the ledger write runs alone | Set per-tool policy |
weft.MaxResultBytes on a tool | cuts the forecast to 2,000 bytes | Set per-tool policy |
| Results in call order | res.Steps[0].Results follows the calls | What does a run return? |
| Problem counters | count the truncated result | Read a run in Studio |
The program
Section titled “The program”// 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) }}View on GitHub · run it from docs-site/examples:
go run ./cookbook/toolstormgo test ./cookbook/toolstormw1 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 recordedf1 forecast_report → 2000 bytes kept, then "…[truncated 18400 bytes]"get_weather calls overlapped, never more than 3 at once: truecalls running beside the ledger write: 0recorded: truncated results: 1The 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
Section titled “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) Parallelismbounds 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. 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
Section titled “See also”- What happens in one step? The loop and parallel tools: how the dispatcher orders calls and events
- Set per-tool policy: timeouts, caps, ordering and strict input
- Survive flaky infrastructure: when the parallel calls fail
- Read a run in Studio
Symbols used: weft.Parallelism · weft.Sequential · weft.MaxResultBytes · weft.ErrInvalidRunOption · weft.ModelRequest · Agent.CallTool · weft.Errorf · weft.Tool · weft.New · otel.Install · obsdb.Problems · wefttest.Script