Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 31

Parallel Tool Execution

Recommended resources

Introduction

In our previous lesson, we constructed a ToolRegistry, establishing a centralized and scalable system for managing what an agent can do. We now have a dynamic catalog of capabilities, complete with automated schema generation and validation. However, simply knowing what tools are available is only half the battle. The true power of an agent lies in its ability to execute those tools efficiently.

This lesson tackles the "how" of tool execution. We will move beyond simple, one-at-a-time function calls and implement an asynchronous tool executor capable of running multiple independent tools in parallel. For a system architect or AI engineer, this is a critical step in building performant, responsive agents that don't get bottlenecked by slow I/O operations. Your proficiency in asynchronous programming and distributed systems will be a significant asset as we explore the nuances of structured concurrency and its application to agentic workflows.

By the end of this lesson, you will have designed and implemented an AsyncToolExecutor that can take a batch of tool calls from an LLM, dispatch them concurrently, and correctly handle different types of underlying tool functions—from native coroutines to blocking I/O and even CPU-bound code.


The Imperative for Parallelism

Modern LLMs are increasingly capable of generating multiple tool calls in a single response. For example, a request like "What's the weather in San Francisco, what's on my calendar for the next hour, and what's the latest news about AI?" can be broken down into three independent tasks.

This diagram illustrates three fundamental tool-calling patterns. Our focus is on the "Parallel" pattern, where the agent executes multiple independent tool calls simultaneously to reduce latency and improve responsiveness.

Executing these tasks sequentially would mean the total time is the sum of all individual task times. However, since these tasks are independent, we can execute them concurrently, reducing the total time to that of the single longest-running task. This is the core principle behind parallel tool execution.

The sequence diagram below from Amazon Bedrock's agent implementation illustrates this exact pattern in a production system. After the LLM determines that tool calls are required, it submits them as parallel tasks to an executor.

This sequence diagram shows an agentic workflow. Note the `par` (parallel) block where multiple tools are executed concurrently via a `ThreadPoolExecutor`. Our goal is to build a similar, but more robust, `asyncio`-native execution engine.

Concurrency in Python: A Quick Refresher

Your background in systems engineering means you're already familiar with the distinction between concurrency and parallelism. In Python, this distinction is particularly important due to the Global Interpreter Lock (GIL).

  • Concurrency is about managing multiple tasks at once, switching between them when one is blocked (e.g., waiting for a network response). This is ideal for I/O-bound work and is the primary domain of asyncio.
  • Parallelism is about running multiple tasks simultaneously on different CPU cores. In Python, this requires bypassing the GIL, typically by using multiple processes (multiprocessing). This is necessary for CPU-bound work.

Most agent tools (API calls, database queries, file I/O) are I/O-bound, making asyncio the perfect foundation for our tool executor.


The Challenge of Unstructured Concurrency: asyncio.gather()

When developers first approach running multiple coroutines concurrently, asyncio.gather() is often the go-to function. It's simple and effective for basic use cases.

The video "Next-Level Concurrent Programming In Python With Asyncio" by ArjanCodes provides a clear demonstration of the performance benefits of using asyncio.gather for multiple independent HTTP requests.

Next-Level Concurrent Programming In Python With Asyncio

This video demonstrates the performance gains from switching from sequential execution to concurrent execution with asyncio.gather.

Watch the section that compares a sequential for loop of API calls with a concurrent approach using gather. Pay close attention to the significant reduction in total execution time, from over two seconds to 0.2 seconds. This highlights the "why" behind our current objective.

While gather is powerful, it has significant drawbacks in complex, long-running systems like agents. This is a classic example of where a simple tool fails under production pressures. The article "Structured Concurrency for AI Pipelines" explains these failure modes in detail.

Structured Concurrency for AI Pipelines: Why asyncio.gather() Isn't ...

This article is a critical analysis of asyncio.gather() and explains why it's a source of subtle, expensive bugs in production AI systems.

Read the introduction and the section The Three Ways gather() Fails You. Focus on understanding the "orphaned task problem" and how gather's default cancellation behavior can lead to resource leaks and incomplete cleanup.

As the article points out, asyncio.gather() creates "unstructured" concurrency. Tasks can outlive their calling scope, exceptions from one task don't reliably cancel siblings, and cleanup is not guaranteed. For a production agent system, this is unacceptable.


Structured Concurrency with asyncio.TaskGroup

The solution, introduced in Python 3.11, is structured concurrency via asyncio.TaskGroup. It provides a simple but powerful guarantee: the async with block that defines the task group will not exit until every task created within it has completed or been cleanly cancelled.

This eliminates the "orphaned task" problem and provides robust, predictable behavior for managing concurrent operations. The "Structured Concurrency" article explains this solution beautifully.

Structured Concurrency for AI Pipelines: Why asyncio.gather() Isn't ...

This resource explains the benefits of TaskGroup and shows the correct pattern for parallel tool calls.

First, read the section What Structured Concurrency Gives You to understand the core invariant of TaskGroup. Next, study the code in The Production Pattern. This is the fundamental blueprint for our AsyncToolExecutor. Notice how it dispatches all tool calls within a single TaskGroup and then collects the results.

Corey Schafer's comprehensive asyncio guide also provides an excellent breakdown of TaskGroup versus gather, especially regarding error handling.

Python Tutorial: AsyncIO - Complete Guide to Asynchronous Programming with Animations

This video offers a detailed comparison of different ways to schedule and await tasks, including a clear explanation of the differences between gather and TaskGroup.

Watch the segment starting at scheduling and awaiting tasks. Pay close attention to the discussion on error handling and cleanup, which highlights why TaskGroup is generally the safer choice for all-or-nothing concurrent operations.


Implementing the AsyncToolExecutor

Now, let's design our AsyncToolExecutor. Its primary job is to take a list of tool calls, execute them concurrently using our ToolRegistry from the last lesson, and return the aggregated results. A key challenge is that our tools might not all be async-native.

Case 1: Executing Native Coroutines

This is the simplest case. If a tool registered in our ToolRegistry is an async def function (a coroutine), we can directly create a task from it and run it in our TaskGroup.

import asyncio

class AsyncToolExecutor:
    def __init__(self, tool_registry):
        self.tool_registry = tool_registry

    async def execute_parallel(self, tool_calls: list[dict]):
        tool_results = []
        try:
            async with asyncio.TaskGroup() as tg:
                tasks = []
                for tool_call in tool_calls:



                    # Assume tool_registry.get_function() returns the callable
                    func = self.tool_registry.get_function(tool_call['name'])
                    args = tool_call['arguments']
                    



                    # For now, let's assume 'func' is a coroutine
                    task = tg.create_task(func(**args))
                    tasks.append(task)




            # The 'async with' block ensures all tasks are complete here
            for task, tool_call in zip(tasks, tool_calls):
                tool_results.append({
                    "tool_call_id": tool_call['id'],
                    "result": task.result()
                })
        except* Exception as eg:



            # Handle exceptions from the group
            # For now, we'll just re-raise, but you could add logging/error formatting
            raise eg
            
        return tool_results

Case 2: Handling Synchronous, I/O-Bound Tools

What if a tool uses a standard, blocking library like requests? Calling it directly would block the entire event loop, defeating the purpose of asyncio.

Python Tutorial: AsyncIO - Complete Guide to Asynchronous Programming with Animations

Corey Schafer's guide vividly illustrates why running blocking code in an async function is a critical mistake.

Watch the section that explains and animates what happens when you block the event loop with a synchronous call like time.sleep(). The animation clearly shows how the loop freezes, preventing any other tasks from running.

The solution is to offload the blocking call to a separate thread, which asyncio can manage without blocking the main event loop. The asyncio.to_thread function (Python 3.9+) makes this straightforward.

Python Tutorial: AsyncIO - Complete Guide to Asynchronous Programming with Animations

This part of the video explains the correct pattern for integrating blocking I/O-bound code into an asyncio application.

Focus on the segment explaining how to use asyncio.to_thread to pass blocking code to threads. This allows the event loop to remain non-blocked while the synchronous function executes in the background.

We can adapt our executor to handle this by checking if the function is a coroutine.

import asyncio
import inspect




# ... inside AsyncToolExecutor.execute_parallel ...
async with asyncio.TaskGroup() as tg:
    tasks = []
    for tool_call in tool_calls:
        func = self.tool_registry.get_function(tool_call['name'])
        args = tool_call['arguments']
        
        if inspect.iscoroutinefunction(func):
            task = tg.create_task(func(**args))
        else:



            # It's a synchronous function, run it in a thread
            task = tg.create_task(asyncio.to_thread(func, **args))
        
        tasks.append(task)

Case 3: Handling Synchronous, CPU-Bound Tools

For CPU-bound tasks (e.g., complex calculations, image processing), threads won't help due to the GIL. We must use a separate process to achieve true parallelism. We can accomplish this using loop.run_in_executor with a concurrent.futures.ProcessPoolExecutor.

Python Tutorial: AsyncIO - Complete Guide to Asynchronous Programming with Animations

This video also covers the advanced use case of integrating multiprocessing for CPU-bound work.

First, see the explanation of how to use a ProcessPoolExecutor with the event loop here. Then, watch the practical application in the real-world example, where a CPU-bound image processing task is offloaded to processes for a massive performance gain.

This makes our executor more complex, as it now needs to manage a process pool, but it provides a complete solution for all tool types.


A Deeper Dive: Capped Parallelism and Pipelines

Unbounded parallelism is risky. Firing off thousands of API requests at once can get you rate-limited or banned. A production-grade executor needs a mechanism to limit concurrency. This is often achieved with a semaphore or a more sophisticated pipeline pattern.

A discussion on the official Python forums proposes a from-scratch implementation of an async pipeline with capped parallelism. This is a fantastic first-principles look at how to build such a system using asyncio.Queue and a pool of worker tasks.

Add task pipeline to asyncio with capped parallelism and lazy ...

This discussion provides a masterclass in building a robust, memory-friendly, concurrent processing pipeline from scratch.

First, read the Motivation section to understand the problem with primitives like gather for large or dynamic inputs. Next, examine the proposed API and usage example to see the high-level goal. Finally, and most importantly, carefully study the full implementation of the pipeline function. Analyze how it uses an input_queue, an output_queue, a pool of _worker tasks, and a _feeder task to control the flow of data and limit the number of concurrent operations to the parallelism value. This is a powerful pattern for any concurrent data processing system.

While we won't implement this entire pipeline in our executor today, the core idea of using a semaphore is a simpler way to achieve the same goal of capped parallelism.




# A simplified example using a semaphore
class AsyncToolExecutor:
    def __init__(self, tool_registry, max_concurrency=10):
        self.tool_registry = tool_registry
        self.semaphore = asyncio.Semaphore(max_concurrency)

    async def _execute_with_semaphore(self, func, **kwargs):
        async with self.semaphore:
            if inspect.iscoroutinefunction(func):
                return await func(**kwargs)
            else:
                return await asyncio.to_thread(func, **kwargs)

    async def execute_parallel(self, tool_calls: list[dict]):



        # ...
        async with asyncio.TaskGroup() as tg:
            tasks = []
            for tool_call in tool_calls:
                func = self.tool_registry.get_function(tool_call['name'])
                args = tool_call['arguments']
                task = tg.create_task(self._execute_with_semaphore(func, **args))
                tasks.append(task)



        # ...

This semaphore ensures that no more than max_concurrency tools are running at any given moment.


Conclusion

In this lesson, we have engineered the engine of our agent's action-taking capabilities. By moving from naive sequential execution to robust, structured concurrency, we have laid the groundwork for a highly performant and reliable system.

Here are the key takeaways:

  • Structured Concurrency is Key: asyncio.TaskGroup provides essential guarantees about task lifetime and exception handling that are non-negotiable for production systems, making it vastly superior to asyncio.gather for agentic tool execution.
  • One Executor, Many Tool Types: A robust executor must correctly handle native async tools, blocking I/O-bound tools (via asyncio.to_thread), and CPU-bound tools (via a ProcessPoolExecutor).
  • Control Your Concurrency: Unbounded parallelism is a liability. Using primitives like asyncio.Semaphore is crucial for managing resource usage and respecting external API rate limits.
  • From Principles to Production: By understanding the failure modes of simpler approaches and building upon the solid foundation of structured concurrency, you can engineer systems that are not just fast, but also stable and predictable.

You now have a ToolRegistry to define what your agent can do and an AsyncToolExecutor to manage how it does it. In our next lesson, we will focus on a particularly powerful and complex type of tool: designing and implementing a secure code execution tool using a sandboxed environment. This will put our executor to the test and introduce critical concepts of agent safety and security.