AI Agents by HandAll problemsAbout

All problems › Agent problem · hard · ~20 min

Run tool calls in parallel

parallel tool calls timeouts asyncio

Solve it in your browser →

Run the tools in parallel (~20 min)

parallel_tools.py is a travel planner with three tools (search_flights, search_hotels, get_weather) and a working loop. It's correct, but each tool calls a slow partner API (about 1s, see LATENCY), and the loop runs them one after another:

python -m parallel_tools

The tool handlers are already async functions (the partner APIs have async clients), but the loop runs each one to completion with its own asyncio.run before starting the next. When the model asks for flights, hotels and weather in one turn, the user waits for all three in sequence. Sometimes a partner hangs, and then the whole agent hangs with it.

Change run_agent(prompt, client=None, max_turns=10, tool_timeout=TOOL_TIMEOUT) -> str so that:

  1. All tool_use blocks from one assistant turn run concurrently with asyncio (standard library only). A turn with three 1s tools should take about 1s, not 3s. run_agent itself stays a normal function.
  2. The tool_result blocks still go back in one user message, in the same order as the tool_use blocks, each with its own tool_use_id.
  3. A tool that hasn't finished tool_timeout seconds after the turn's tools started gets an is_error result saying it timed out, and the loop moves on without waiting for it. The timed-out call must be cancelled, not left running.
  4. Everything that works today keeps working: an unknown tool or a tool that raises still comes back as is_error without dropping the other results, and max_turns still raises RuntimeError.

Be ready to say when running tool calls in parallel is unsafe, what cancelling a call does (and doesn't) undo, and what would happen if one handler called time.sleep instead of awaiting.

Try it: python -m parallel_tools Check it: pytest tests/test_parallel_tools.py

Starter code and hidden tests open in the editor. Nothing to install.