07
Async Python
Essential for parallel tool calls and streaming in agent systems.
import asyncio
# Run multiple tool calls in parallel
async def parallel_tools(tasks):
results = await asyncio.gather(
fetch_weather("NYC"),
fetch_stock("GOOG"),
fetch_news("AI"),
)
return results
# Semaphore for rate limiting
sem = asyncio.Semaphore(5) # max 5 concurrent calls
async def limited_call(url):
async with sem:
return await fetch(url)
# When to use async vs sync
# Async: I/O bound (API calls, DB queries, file reads)
# Sync: CPU bound (data processing, math)