Async Python: many API calls at once
Python for AI Apps · 10 questions
Short notes
Key idea
Calling an API mostly means waiting. With async, one program can start many calls and wait for all of them at once, so 50 calls take about as long as the slowest one instead of the sum of all.
Syntax
import asyncio
from google import genai
client = genai.Client()
async def summarise(text: str) -> str:
r = await client.aio.models.generate_content(model=MODEL, contents=text)
return r.text
async def main(texts):
sem = asyncio.Semaphore(5) # at most 5 at a time
async def one(t):
async with sem:
return await summarise(t)
return await asyncio.gather(*(one(t) for t in texts))
results = asyncio.run(main(texts))
Example
Summarising 100 reviews one by one at 2 seconds each takes over 3 minutes. With 5 at a time, about 40 seconds, and the semaphore keeps you under the rate limit.
Traps
- Forgetting
awaitgives a coroutine object, not a result. - Blocking calls (
time.sleep,requests) inside async code freeze everything; useasyncio.sleep,httpx.AsyncClient. - Unlimited concurrency hits rate limits; use a semaphore.
- In Jupyter, use
await main(...)instead ofasyncio.run, since a loop is already running.
Want the full lesson with step-by-step examples, a project and a certificate? Python for AI Apps course, ₹180 →
- Question 1easy
Why does async help when calling an LLM API many times?
- Question 2medium
What does this print?
import asyncio async def label(t): return t.upper() x = label("refund") print(type(x).__name__) x.close() - Question 3medium
Each call waits 0.1 seconds. About how many calls' worth of time does the gather take?
import asyncio, time async def call(i): await asyncio.sleep(0.1) return i async def main(): start = time.perf_counter() await asyncio.gather(*(call(i) for i in range(5))) return round((time.perf_counter() - start) / 0.1) print(asyncio.run(main())) - Question 4medium
What does this print?
import asyncio async def call(name, seconds): await asyncio.sleep(seconds) return name async def main(): return await asyncio.gather(call("slow", 0.2), call("fast", 0.01), call("mid", 0.1)) print(asyncio.run(main())) - Question 5hard
What does this print?
import asyncio async def call(i): await asyncio.sleep(0.3 if i == 0 else 0.01) return i async def main(): tasks = [asyncio.wait_for(call(i), timeout=0.1) for i in range(3)] out = await asyncio.gather(*tasks, return_exceptions=True) return [type(r).__name__ if isinstance(r, Exception) else r for r in out] print(asyncio.run(main()))
Async Python: many API calls at once
Async Python: many API calls at once
Async Python: many API calls at once
Async Python: many API calls at once
Async Python: many API calls at once
5 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.