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:
- All
tool_useblocks from one assistant turn run concurrently withasyncio(standard library only). A turn with three 1s tools should take about 1s, not 3s.run_agentitself stays a normal function. - The
tool_resultblocks still go back in one user message, in the same order as thetool_useblocks, each with its owntool_use_id. - A tool that hasn't finished
tool_timeoutseconds after the turn's tools started gets anis_errorresult saying it timed out, and the loop moves on without waiting for it. The timed-out call must be cancelled, not left running. - Everything that works today keeps working: an unknown tool or a tool that raises still comes back as
is_errorwithout dropping the other results, andmax_turnsstill raisesRuntimeError.
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