Parallel & Batch Tool Calling: Fan-Out Execution, Latency Cuts & Dependency DAGs
How modern LLMs emit multiple tool calls in a single turn and how your harness executes them concurrently via asyncio.gather + Semaphores — cutting multi-tool latency by 3×–5× while isolating partial failures.
Parallel Tool Execution fans out independent tool calls concurrently (using asyncio + concurrency caps) while respecting dependency edges in a DAG.
Running 5 independent web or database lookups sequentially takes 5× longer; fan-out execution cuts wall-clock latency to the single slowest call.
When a user asks 'Compare weather, flights, and hotels for Tokyo & Kyoto', running 6 API calls sequentially takes 3+ seconds — Parallel Batch Execution runs all 6 in ~400 ms!
Modern frontier models natively emit an array of tool_calls: [call_1, call_2, call_3] in ONE turn — but if your Python harness still loops for call in resp.tool_calls: run(call) synchronously, you throw away 100% of that speedup!
Adding an asyncio.Semaphore(max_concurrency=5) prevents an enthusiastic agent from firing 50 parallel calls at once and getting IP-banned by upstream rate limits (HTTP 429)!
Classic systems coding problem: 'Implement a Batch Tool Executor that runs independent calls concurrently with bounded concurrency, preserves order, and never lets 1 failed tool crash the batch!'
In Python asyncio, what happens by default if one coroutine raises an exception inside await asyncio.gather(t1, t2, t3) (without return_exceptions=True)?
- Compute wall-clock speedup of Parallel Fan-Out (
max(t_i)) vs. Sequential execution (Σ t_i) for independent tool calls - Execute batched tool calls concurrently with
asyncio.gather(..., return_exceptions=True)and a concurrencyasyncio.Semaphore - Preserve deterministic result ordering matching each
tool_call_idwhile isolating partial batch failures - Schedule dependent vs. independent tool calls in parallel Waves using a Tool Dependency DAG
Imagine cooking dinner for 4 guests: Sequential means boiling pasta, waiting 10 minutes, THEN chopping salad, THEN toasting garlic bread (25 minutes!). Parallel Batch Execution puts the pasta on the stove while chopping salad and toasting bread all at once — dinner is ready in 10 minutes (and if the toaster trips, you still serve the pasta and salad)!
1. Sequential Loop vs. Parallel Fan-Out Latency
Drag the Independent Tools slider in the mini-lab below to see the instant speedup of asyncio.gather over a synchronous for loop!
Bounded Parallel Batch Executor
sem = asyncio.Semaphore(5)
async def run_one(call):
async with sem:
return await safe_dispatch(call.id, call.name, call.args)
results = await asyncio.gather(*(run_one(c) for c in resp.tool_calls))
Notice asyncio.gather automatically preserves the exact input order of resp.tool_calls regardless of which tool finishes first!
Parallel Fan-Out Latency Calculator (280 ms / API call)
2. Dependency DAGs: Parallel Waves for Multi-Hop Calls
When calc_invoice(uid, fx) needs outputs from BOTH get_user_id() and get_fx_rates(), run Wave 1 in parallel and Wave 2 right after!
Two Ways Dependencies Resolve
- Multi-Turn Native Parallelism: On Turn 1, the LLM emits
[get_user_id, get_fx_rates]together → parallel Wave 1! On Turn 2, it sees both results and emits[calc_invoice]→ Wave 2! - Explicit DAG Compiler (LLMCompiler): For known complex workflows, the LLM emits a mini-DAG with
$1, $2variable references so the harness executes Wave 1 → Wave 2 with zero extra LLM round-trip between waves!
3. Isolating Partial Batch Failures
When 2 out of 3 parallel tools succeed and 1 returns HTTP 503, return ALL 3 envelopes to the LLM so it can answer with the 2 successes and decide whether to retry only the 1 failure!
asyncio.gather(..., return_exceptions=True)), one failing tool must NEVER crash the other 3 successful observations — return per-call {ok, data, error} envelopes!Per-Call Isolation Checklist
- Every
tool_call_idMUST receive a matchingrole: "tool"response (even on timeout/error!). - Attach per-call timeouts (
asyncio.wait_for(..., timeout=10)) so 1 hung endpoint doesn't stall the entire batch forever. - Never parallelize non-idempotent conflicting writes (e.g., two concurrent
transfer_fundscalls on the same account — serialize writes with a lock or run them sequentially!).
Worked Example: Computing Critical-Path Latency of a 3-Tool DAG
get_user (200 ms) and get_fx (350 ms) are independent; calc_invoice (150 ms) depends on both.
.
Why do we add an asyncio.Semaphore(5) around asyncio.gather in a Batch Tool Executor?
Why should you be careful NOT to blindly parallelize two tool calls that mutate the same file or database row?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Original call order — which is super convenient when pairing results back to resp.tool_calls!
Sequential vs. Parallel Batch Tool Fan-Out Racer (3 Independent Tools)
Watch parallel asyncio.gather finish all 3 tool calls in 1/3rd the wall-clock time of a sequential for-loop.
asyncio.gather + Semaphore with per-call timeouts and {ok, data, error} isolation to slash latency by 3×–5× while keeping mutating writes serialized.Deep Research & Multi-Source RAG Agents
Fires 5–10 web/vector/SQL queries concurrently in one wave, cutting total research time from 20s down to 3s.
import asyncio
import time
# Fan-Out Parallel Tool Execution with Concurrency Cap (asyncio.Semaphore)
async def fetch_tool(sem: asyncio.Semaphore, name: str, delay: float) -> str:
async with sem:
await asyncio.sleep(delay)
return f"{name}:ok"
async def run_parallel_batch():
sem = asyncio.Semaphore(3) # cap in-flight external API calls
t0 = time.perf_counter()
results = await asyncio.gather(
fetch_tool(sem, "search_docs", 0.05),
fetch_tool(sem, "query_sql", 0.05),
fetch_tool(sem, "fetch_metrics", 0.05),
)
elapsed_ms = (time.perf_counter() - t0) * 1000
print(f"Results: {results} | Total latency: {elapsed_ms:.0f}ms (vs ~150ms sequential)")
asyncio.run(run_parallel_batch())
role: 'tool' message for 1 failed call in a parallel batch.tool_call_id is missing a response — ALWAYS emit an error envelope for failed calls!