Skip to content

Fan out many tool calls safely

View as Markdown

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:

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

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:

Three tool calls from one step run at once; their results join one tool message in call order.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.

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:

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

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.

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.

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

  • On the 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 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 headerThe 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
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.
FeatureWhat it does hereGuide
weft.Parallelismat most three calls at onceWhat happens in one step?
weft.Sequential on a toolthe ledger write runs aloneSet per-tool policy
weft.MaxResultBytes on a toolcuts the forecast to 2,000 bytesSet per-tool policy
Results in call orderres.Steps[0].Results follows the callsWhat does a run return?
Problem counterscount the truncated resultRead a run in Studio
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)
}
}

View cookbook/toolstorm/main.go on GitHub

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

Terminal window
go run ./cookbook/toolstorm
go test ./cookbook/toolstorm
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.

  • 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. 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)

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