Chapter 8 of 32 · ~20 min read & lab+80 XP
Chapter 8 · Agentic AI

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.

What Is It?

Parallel Tool Execution fans out independent tool calls concurrently (using asyncio + concurrency caps) while respecting dependency edges in a DAG.

Why Is It Required?

Running 5 independent web or database lookups sequentially takes 5× longer; fan-out execution cuts wall-clock latency to the single slowest call.

Everyday Analogy: Boiling pasta water while chopping vegetables at the same time instead of waiting for the pot to boil before touching a knife.
Why ML Engineers & Data Scientists Actually Need This

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!

ML / AI Engineer

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!

Data Scientist

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)!

Interview & Debug Edge

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!'

Step 0 · Test Your Gut Before Any Math!

In Python asyncio, what happens by default if one coroutine raises an exception inside await asyncio.gather(t1, t2, t3) (without return_exceptions=True)?

What You Will Master in This Chapter
  • 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 concurrency asyncio.Semaphore
  • Preserve deterministic result ordering matching each tool_call_id while isolating partial batch failures
  • Schedule dependent vs. independent tool calls in parallel Waves using a Tool Dependency DAG
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 3
Tpar=max⁡i(ti)≪∑itiT_{\text{par}} = \max_i(t_i) \ll \sum_i t_iSay aloud:“parallel fan-out latency”
Plain-English Meaning
Concurrent batch latency equals only the slowest single tool instead of the sum of all tools
Everyday Example
4 × 280 ms → 280 ms (4× faster!)
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

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

Everyday Story First (Zero Math Yet!)

Drag the Independent Tools slider in the mini-lab below to see the instant speedup of asyncio.gather over a synchronous for loop!

Sequential (Σ Latency = 900 ms) vs. Parallel Batch Fan-Out (max = 300 ms!)Sequential Loop (900 ms total)Tool A (300 ms)Tool B (300 ms)Tool C (300 ms)Parallel Batch Fan-Out via asyncio.gather (300 ms — 3× Faster! ✓)A ∥ B ∥ C (300 ms)
Sequential tool execution sums latencies (300 + 300 + 300 = 900 ms); Parallel Batch Fan-Out runs independent tool calls concurrently in max(latencies) = 300 ms — 3× faster!

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!

Animated Mini-Lab • 2.2

Parallel Fan-Out Latency Calculator (280 ms / API call)

Sequential Loop
1120 ms
Parallel `asyncio.gather`
295 ms (3.8× faster ✓)

2. Dependency DAGs: Parallel Waves for Multi-Hop Calls

Everyday Story First (Zero Math Yet!)

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!

Tool Dependency DAG: Parallel Wave 1 → Dependent Wave 2Wave 1A: get_user_id()Wave 1B: get_fx_rates()Wave 2: calc_invoice(uid, fx)Final Reply ✓
When Tool C depends on Tool A's output while Tool B is independent, a Dependency DAG runs A & B in parallel Wave 1, then C in Wave 2 — achieving optimal critical-path latency!

Two Ways Dependencies Resolve

  1. 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!
  2. Explicit DAG Compiler (LLMCompiler): For known complex workflows, the LLM emits a mini-DAG with $1, $2 variable references so the harness executes Wave 1 → Wave 2 with zero extra LLM round-trip between waves!

3. Isolating Partial Batch Failures

Everyday Story First (Zero Math Yet!)

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!

Isolated Batch Envelopes: Partial Failure Must Never Crash Sibling Results!Call #1: weather{ok: true, 22°C}Call #2: stocks{ok: false, 503}Call #3: news{ok: true, 3 items}
In parallel batch execution (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_id MUST receive a matching role: "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_funds calls on the same account — serialize writes with a lock or run them sequentially!).
Walk Through With Me · Interactive Worked Example

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.

11. Sequential latencyStep 1 / 2

200+350+150=700 ms200 + 350 + 150 = \mathbf{700\text{ ms}}.

Teacher's Note: Wastes 200 ms waiting unnecessarily.
Pause & Check · Quick Intuition Pulse

Why do we add an asyncio.Semaphore(5) around asyncio.gather in a Batch Tool Executor?

Try It YourselfStandard

Why should you be careful NOT to blindly parallelize two tool calls that mutate the same file or database row?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

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!

Interactive Visual Lab
Lab Challenge: Watch the 60 FPS Parallel Batch Fan-Out Racer finish 3 tools in 1/3rd the time of a sequential loop.
Interactive Animation • 2.2 Deep Lab

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.

Running...
Parallel Fan-Out (weather ∥ stocks ∥ news)0%
Sequential For-Loop (weather → stocks → news)0% (0 / 900 ms)
0%
Elapsed 0 ms
Intuition Takeaway: Execute independent tool calls concurrently via asyncio.gather + Semaphore with per-call timeouts and {ok, data, error} isolation to slash latency by 3×–5× while keeping mutating writes serialized.
Where This Powers Real ML, Deep Learning & Generative AI

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.

Production NumPy & PyTorch Code Patterns
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())
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Missing a role: 'tool' message for 1 failed call in a parallel batch.
Best Practice: OpenAI/Anthropic APIs reject the next turn with HTTP 400 if ANY tool_call_id is missing a response — ALWAYS emit an error envelope for failed calls!
Chapter Mastery Check (+80 XP)
Score: 0 / 1
1If an LLM emits 4 independent read-only tool calls taking 200 ms, 350 ms, 150 ms, and 300 ms respectively, what is the ideal parallel batch latency?

Apply What You Learned — Solve Matching Coding Problems