▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Async HTTP and AI calls
Call many APIs or AI prompts in parallel with httpx.
🎬 Video version coming soon — read it now
Let's apply asyncio to real network work: fetching many web pages, then calling an AI model many times in parallel.
httpx: requests, but async
- One shared client reuses connections, which is much faster than a new client per request.
*(...)unpacks the generator of coroutines into gather's arguments, the unpacking from the advanced course.
Errors without losing everything
By default, one failure makes gather raise. To collect every result, errors included:
Parallel AI calls
The Anthropic SDK has an async client with the same methods:
Ten reviews take roughly as long as the slowest two or three requests, not ten requests one after another.
Why the semaphore matters
AI APIs have rate limits: a maximum number of requests and tokens per minute. Firing 500 requests at once mostly produces rate-limit errors. A semaphore of 5–10 keeps a steady, polite flow, and the SDK's automatic retries handle the occasional limit. The next lesson goes deeper.
zip(reviews, summaries) always lines up correctly.In one line
Use one shared httpx.AsyncClient or AsyncAnthropic client, run requests with gather, and cap concurrency with a semaphore to respect rate limits.
Share with a friend