Python for AI Engineers · Part A · Lesson 9 of 26

Python async and await: asyncio for concurrent LLM calls

Async Python for Java and JavaScript developers: coroutines, the event loop, asyncio.run, running LLM calls concurrently with gather, timeouts, limiting concurrency with a Semaphore, streaming with async generators, and the two bugs everyone hits.

⏱ 40 min3 exercises that check your codeRuns in your browser

By the end you can

  • Explain why waiting on an LLM API is the perfect job for async, and how the event loop compares with JS promises and Java futures
  • Write coroutines with async def and await, and start a program with asyncio.run
  • Run several model calls at once with asyncio.gather, give up on slow ones with asyncio.timeout, and cap them with a Semaphore
  • Stream a reply token by token with an async generator and async for
  • Spot the classic bugs: a coroutine called without await, and time.sleep blocking the loop
1 / 6

1Why async: most of an LLM call is waiting

When your code calls a model API, your computer does almost nothing for one to ten seconds: the request travels, the model thinks, the reply streams back. That is I/O-bound work. The CPU is idle and your program just waits.

With normal (synchronous) code, three calls wait one after another, so the waits add up. The example below fakes each call with time.sleep(0.3), which pauses the program for 0.3 seconds, the same way a real network call would. Run it and look at the total.

Try it: edit and run
import time


def call_llm(prompt):
    time.sleep(0.3)                  # stands in for waiting on the network and the model
    return f"answer to {prompt!r}"


start = time.perf_counter()          # a precise clock, in seconds
for p in ["summarize", "translate", "classify"]:
    print(call_llm(p))
print(f"total: {time.perf_counter() - start:.1f} s")
Expected output
answer to 'summarize'
answer to 'translate'
answer to 'classify'
total: 0.9 s

Nothing in this program needs the CPU while it waits. Async lets one program start the second and third calls while the first one is still waiting, so three 0.3 second calls take about 0.3 seconds in total, not 0.9. A RAG pipeline that queries several sources, an agent that calls several tools, or a script that grades 500 answers with a model all gain the same way.

Tip Async helps with waiting (network, disk, databases). It does not make CPU-heavy work like parsing a huge PDF or computing embeddings locally any faster. That is a job for processes, covered in the performance lesson.

2async def and await

async def defines a coroutine function. Calling it does not run its body. It returns a coroutine object: a paused piece of work, ready to start. This is the biggest surprise for JavaScript developers, because calling a JS async function starts it immediately and hands you a Promise that is already running.

await something means: run this coroutine (or wait for this task) and give me its result; while it waits, let other work run. You can only write await inside an async def.

asyncio.sleep(0.3) is the async version of time.sleep(0.3): it pauses only this coroutine and lets others run in the meantime. We use it everywhere in this lesson to fake a model call, so every example works without a network.

About the last line in these boxes: this page runs Python inside your browser, which already has an event loop running (the next sections explain what that is). So the boxes start the program with await main() at the top level, which works here and in Jupyter notebooks. In a normal .py file you write asyncio.run(main()) instead, as section 3 shows. Everything else is the same.

Try it: edit and run
import asyncio


async def call_llm(prompt):
    await asyncio.sleep(0.3)         # waits, but leaves Python free to do other work
    return f"answer to {prompt!r}"


async def main():
    coro = call_llm("summarize")     # nothing has run yet: we only got a coroutine object
    print(type(coro).__name__)
    answer = await coro              # now it runs; main pauses here until it returns
    print(answer)


await main()   # in a .py file: asyncio.run(main())
Expected output
coroutine
answer to 'summarize'
JavaScript (Node)
async function callLlm(prompt) {
  await new Promise((r) => setTimeout(r, 300));
  return `answer to '${prompt}'`;
}

const p = callLlm("summarize"); // already running: a Promise starts at once
console.log(await p);
Java
CompletableFuture<String> f =
    CompletableFuture.supplyAsync(() -> callLlm("summarize")); // runs on a pool thread now
String answer = f.join(); // blocks this thread until it is done
Python
coro = call_llm("summarize")   # lazy: does not start yet
answer = await coro            # starts it and waits, without blocking the thread

Tip Async is contagious: a function that awaits must itself be async def, and its caller must await it too, all the way up to main(). That is normal. Keep pure helper functions (formatting, parsing) as plain def.

3Starting a program: asyncio.run

In a real script, asyncio.run(main()) is the bridge from normal code into async code. It creates an event loop, runs main() until it finishes, then closes the loop and returns whatever main() returned. Call it once, at the entry point of your program.

Calling asyncio.run while a loop is already running fails with RuntimeError: asyncio.run() cannot be called from a running event loop. That is exactly why the boxes on this page use await main(): the browser's loop is already running. Frameworks such as FastAPI also run the loop for you: you write async def endpoints and never call asyncio.run yourself.

ask.py
import asyncio


async def call_llm(prompt: str) -> str:
    await asyncio.sleep(0.3)
    return f"answer to {prompt!r}"


async def main() -> None:
    answer = await call_llm("summarize")
    print(answer)


if __name__ == "__main__":
    asyncio.run(main())
  1. asyncio is in the standard library: nothing to install.line 1
  2. By convention all the async work starts from one async def main().line 9
  3. True only when you run this file directly, not when another file imports it. Same idea as public static void main in Java.line 14
  4. Creates the event loop, runs main() to the end, closes the loop. One call per program.line 15
Output
answer to 'summarize'

Save it as ask.py and run it with uv run python ask.py inside a project from lesson 1 (or python3 ask.py). It prints the line above after about 0.3 seconds.

4The event loop: one thread taking turns

The event loop is a scheduler with a to-do list of paused coroutines. It runs one until that coroutine reaches an await on something that is not ready yet (a network reply, a timer), parks it, and runs the next one that is ready. When the reply arrives, the parked coroutine goes back on the list. All of this happens on one thread.

If you know JavaScript, this is the same model as the Node or browser event loop. If you know Java, think of one thread that never blocks, rather than a pool of threads that each block on their own call.

asyncio.create_task(coro) puts a coroutine on the loop's list to run soon, and returns a Task you can await later. It is the Python way to get "start now, collect later", like calling a JS async function without awaiting it yet. Below, await asyncio.sleep(0) means "pause and let the others have a turn": watch how A and B take turns.

Try it: edit and run
import asyncio


async def worker(name, steps):
    for i in range(1, steps + 1):
        print(f"{name} step {i}")
        await asyncio.sleep(0)       # pause here so other tasks get a turn


async def main():
    a = asyncio.create_task(worker("A", 3))   # scheduled, not started yet
    b = asyncio.create_task(worker("B", 2))
    print("tasks created")           # main has not awaited yet, so it keeps running
    await a                          # main pauses; now A and B take turns
    await b
    print("both done")


await main()   # in a .py file: asyncio.run(main())
Expected output
tasks created
A step 1
B step 1
A step 2
B step 2
A step 3
both done

Because only one coroutine runs at a time and a switch can only happen at an await, the code between two awaits runs without interruption. Simple shared state such as a counter is safe to update there without locks, unlike with Java threads.

Watch out Keep a reference to every task you create (in a variable or a list) and await it. A task nobody awaits can hide its exception, and the loop only keeps a weak reference to it, so an unreferenced task may even disappear before it finishes.

5asyncio.gather: three calls at once

asyncio.gather(c1, c2, c3) wraps each coroutine in a task, runs them all concurrently, and returns their results as a list in the same order you passed them, no matter which finished first. It is Promise.all for Python.

The example runs the same three fake calls (0.3, 0.1 and 0.2 seconds) twice: first one by one with a plain await each, then together with gather. The *( ... for ... ) part builds one coroutine per prompt and spreads them as separate arguments, the *args trick from lesson 4.

Try it: edit and run
import asyncio
import time


async def call_llm(prompt, seconds):
    await asyncio.sleep(seconds)     # a fake model call that takes `seconds`
    print(f"  finished {prompt}")
    return f"answer to {prompt!r}"


PROMPTS = [("summarize", 0.3), ("translate", 0.1), ("classify", 0.2)]


async def main():
    start = time.perf_counter()
    for prompt, seconds in PROMPTS:
        await call_llm(prompt, seconds)          # wait for each before starting the next
    print(f"one by one: {time.perf_counter() - start:.1f} s")

    start = time.perf_counter()
    answers = await asyncio.gather(*(call_llm(p, s) for p, s in PROMPTS))
    print(f"gather:     {time.perf_counter() - start:.1f} s")
    print(answers)                               # input order, not finish order


await main()   # in a .py file: asyncio.run(main())
Expected output
  finished summarize
  finished translate
  finished classify
one by one: 0.6 s
  finished translate
  finished classify
  finished summarize
gather:     0.3 s
["answer to 'summarize'", "answer to 'translate'", "answer to 'classify'"]
JavaScript
const answers = await Promise.all(
  prompts.map(([p, s]) => callLlm(p, s)),
);
Java
List<CompletableFuture<String>> fs = prompts.stream()
    .map(p -> CompletableFuture.supplyAsync(() -> callLlm(p)))
    .toList();
CompletableFuture.allOf(fs.toArray(new CompletableFuture[0])).join();
List<String> answers = fs.stream().map(CompletableFuture::join).toList();

The total with gather is the slowest call (0.3 s), not the sum (0.6 s). With real model calls that take seconds, this is the difference between a batch job of 500 prompts finishing in minutes or in hours.

Watch out If one call raises, gather passes that first exception to you, but the other calls keep running in the background. Pass return_exceptions=True to get errors back in the list instead, or use async with asyncio.TaskGroup() as tg: (Python 3.11+), which cancels the remaining tasks when one fails.

6asyncio.timeout: give up on slow calls

A model can hang: an overloaded server, a huge prompt, a local model still loading. async with asyncio.timeout(seconds): puts a deadline on everything inside the block. When time runs out, the call inside is cancelled and the block raises the built-in TimeoutError, which you catch like any other exception.

asyncio.timeout is new in Python 3.11. Older code does the same with await asyncio.wait_for(coro, timeout=0.5).

Try it: edit and run
import asyncio


async def call_llm(prompt, seconds):
    await asyncio.sleep(seconds)
    return f"answer to {prompt!r}"


async def ask_with_timeout(prompt, seconds, limit):
    try:
        async with asyncio.timeout(limit):       # deadline for everything in this block
            return await call_llm(prompt, seconds)
    except TimeoutError:                         # the slow call was cancelled
        return f"gave up on {prompt!r} after {limit} s"


async def main():
    print(await ask_with_timeout("quick", 0.1, limit=0.5))
    print(await ask_with_timeout("slow", 2.0, limit=0.5))


await main()   # in a .py file: asyncio.run(main())
Expected output
answer to 'quick'
gave up on 'slow' after 0.5 s

Tip The OpenAI SDK already has a per-request timeout= option. Use asyncio.timeout for a deadline on a whole step, such as "this agent turn, with all its tool calls, gets 30 seconds", by wrapping the gather or the loop in one block.

7Semaphore: at most N calls at a time

Firing 500 requests at once with gather gets you 429 Too Many Requests from a hosted API, and a local Ollama server only works on a few requests in parallel anyway (its OLLAMA_NUM_PARALLEL setting). You want concurrency, but capped.

asyncio.Semaphore(2) holds 2 permits. async with limit: takes a permit, or waits until one is free, and gives it back when the block ends, even after an error. Java has the same idea in java.util.concurrent.Semaphore; in JavaScript people use the p-limit package.

Below, five calls of 0.1 seconds share two permits, so they start in three waves: about 0.0, 0.1 and 0.2 seconds. stats is a small dict that counts how many calls are inside the block at the same moment.

Try it: edit and run
import asyncio
import time

stats = {"now": 0, "peak": 0}        # calls running right now, and the most at once


async def call_llm(i, limit, start):
    async with limit:                # waits here while 2 calls already hold a permit
        stats["now"] += 1
        stats["peak"] = max(stats["peak"], stats["now"])
        print(f"start {i} at {time.perf_counter() - start:.1f} s")
        await asyncio.sleep(0.1)
        stats["now"] -= 1
        return i * 10


async def main():
    limit = asyncio.Semaphore(2)     # 2 permits
    start = time.perf_counter()
    results = await asyncio.gather(*(call_llm(i, limit, start) for i in range(5)))
    print(results, "peak:", stats["peak"])


await main()   # in a .py file: asyncio.run(main())
Expected output
start 0 at 0.0 s
start 1 at 0.0 s
start 2 at 0.1 s
start 3 at 0.1 s
start 4 at 0.2 s
[0, 10, 20, 30, 40] peak: 2

Tip Create the semaphore once and share it with every call that hits the same API. A new semaphore per call limits nothing.

8Async generators: streaming a reply

In lesson 8 a generator used yield to hand out values one at a time. Put yield inside an async def and you get an async generator: it can await between values. You read it with async for, which waits for each next value without blocking the loop.

That is exactly the shape of a streaming LLM reply: tokens arrive one by one over the network, and you print each as it comes so the user sees the answer being written. Note that tokens are pieces of words, often with a leading space, not whole words.

Try it: edit and run
import asyncio


async def fake_stream(prompt):
    """Yields a reply piece by piece, like a model streaming tokens."""
    for token in ["Par", "is", " is", " the", " capital", " of", " France", "."]:
        await asyncio.sleep(0.05)    # the next token arrives a little later
        yield token


async def main():
    parts = []
    async for token in fake_stream("Capital of France?"):
        print(token, end="", flush=True)     # show it as soon as it arrives
        parts.append(token)
    print()                                  # end the streamed line
    print("tokens:", len(parts), "| full reply:", "".join(parts))


await main()   # in a .py file: asyncio.run(main())
Expected output
Paris is the capital of France.
tokens: 8 | full reply: Paris is the capital of France.

With the real async SDK the loop looks the same. This is not runnable here (it needs a model server), and you will build it properly in the streaming chat lab:

from openai import AsyncOpenAI

client = AsyncOpenAI(base_url="http://localhost:11434/v1", api_key="ollama")


async def main():
    stream = await client.chat.completions.create(
        model="llama3.2:3b",
        messages=[{"role": "user", "content": "What is DNS?"}],
        stream=True,                       # ask for tokens as they are generated
    )
    async for chunk in stream:             # each chunk carries a small piece of text
        if chunk.choices and chunk.choices[0].delta.content:
            print(chunk.choices[0].delta.content, end="", flush=True)

AsyncOpenAI is the async twin of the OpenAI client from lab 1: same methods, but you await them. JavaScript has the same loop as for await (const chunk of stream).

9Two bugs everyone hits

Bug 1: calling a coroutine without await. You get a coroutine object instead of the answer, and the call never runs. Python later prints RuntimeWarning: coroutine ... was never awaited. The example calls .close() on it only to keep that warning out of the output.

Bug 2: a blocking call inside async code. time.sleep, the requests library, or a slow synchronous database driver freeze the whole loop, because the loop runs on one thread and they never reach an await. Every other task stops too. Watch what happens to gather:

Try it: edit and run
import asyncio
import time


async def blocking_call(i):
    time.sleep(0.2)                  # BUG: freezes the loop, nothing else can run
    return i


async def polite_call(i):
    await asyncio.sleep(0.2)         # correct: other tasks run while this one waits
    return i


async def timed(label, fn):
    start = time.perf_counter()
    await asyncio.gather(*(fn(i) for i in range(3)))
    print(f"{label}: {time.perf_counter() - start:.1f} s")


async def main():
    result = polite_call(1)          # BUG: no await
    print("without await:", type(result).__name__)
    result.close()                   # only to silence the "never awaited" warning
    print("with await:", await polite_call(1))

    await timed("time.sleep   ", blocking_call)
    await timed("asyncio.sleep", polite_call)


await main()   # in a .py file: asyncio.run(main())
Expected output
without await: coroutine
with await: 1
time.sleep   : 0.6 s
asyncio.sleep: 0.2 s

The fixes: use async libraries (httpx.AsyncClient instead of requests, AsyncOpenAI instead of OpenAI), and when you must call a blocking function, run it on a worker thread with await asyncio.to_thread(fn, arg) (Python 3.9+). to_thread does not work in these browser boxes, because Python in the browser has no threads, but it works in any normal Python.

Tip Running with PYTHONASYNCIODEBUG=1 (or asyncio.run(main(), debug=True)) makes asyncio log every step that blocks the loop for more than 100 ms, and shows where a never-awaited coroutine was created.

Common mistakes

  • Calling an async def function without await: you get a coroutine object, not the answer, and the call never runs.
  • Using time.sleep, requests or another blocking library inside async def. It freezes every task. Use asyncio.sleep, httpx.AsyncClient, or asyncio.to_thread.
  • Awaiting calls one by one in a loop when they do not depend on each other. Use asyncio.gather (or a TaskGroup) to run them together.
  • Calling asyncio.run inside code that is already async (a FastAPI endpoint, a notebook). Just await there.
  • Sending hundreds of requests at once with gather and no limit, then hitting rate limits. Share one asyncio.Semaphore across the calls.
  • Creating tasks with create_task and never keeping or awaiting them, so their errors are lost.

Practice

Write the code, then press Check. Your work is saved in this browser.

1Ask them all at once

ask_all(prompts) should call call_llm for every prompt concurrently and return the answers as a list in the same order as prompts. Right now it forgets something and runs nothing. Fix it so 5 prompts take about 0.1 seconds, not 0.5. You can try your code in the box with print(await ask_all(["a", "b"])).

Exercise
import asyncio


async def call_llm(prompt):
    await asyncio.sleep(0.1)         # a fake model call
    return prompt.upper()


async def ask_all(prompts):
    answers = []
    for p in prompts:
        answers.append(call_llm(p))  # something is missing here
    return answers
Hint

`return await asyncio.gather(*(call_llm(p) for p in prompts))` starts every call at once and keeps the order.

2Stream in chunks

Write an async generator chunks(text, size) that yields text in pieces of size characters (the last piece may be shorter), doing await asyncio.sleep(0) before each piece to act like the network. Then write collect(stream), which reads any async stream with async for and returns all its pieces joined into one string.

Exercise
import asyncio


async def chunks(text, size):
    # yield text[0:size], then text[size:2*size], ... with await asyncio.sleep(0) before each
    pass


async def collect(stream):
    # read the stream with async for and join the pieces
    return ""
Hint

`for i in range(0, len(text), size):` then `await asyncio.sleep(0)` and `yield text[i:i + size]`. In `collect`, use `async for piece in stream:` and append to a list.

3No more than N at a time

ask_limited(prompts, limit) must call call_llm for every prompt concurrently but with at most limit calls running at the same moment, and return the answers in the order of prompts. Use one asyncio.Semaphore(limit) shared by all the calls.

Exercise
import asyncio


async def call_llm(prompt):
    await asyncio.sleep(0.05)
    return prompt.upper()


async def ask_limited(prompts, limit):
    # runs everything at once: no limit yet
    return await asyncio.gather(*(call_llm(p) for p in prompts))
Hint

Create `sem = asyncio.Semaphore(limit)` inside `ask_limited`, write a small inner `async def one(p):` that does `async with sem: return await call_llm(p)`, and gather `one(p)` for every prompt.

Interview questions

Q1When does asyncio make a program faster, and when does it not?

When the program spends its time waiting on I/O (HTTP calls to a model API, databases, files), because one thread can wait on many operations at once. It does not speed up CPU-bound work, since only one coroutine runs at a time on one thread; use processes for that.

Q2What is the difference between a coroutine, a Task and a Future?

A coroutine is the paused object you get by calling an async def function; it does nothing until awaited or scheduled. A Task wraps a coroutine and schedules it on the event loop right away (asyncio.create_task). A Future is the low-level "result that will arrive later" that a Task is built on.

Q3How is Python's async different from JavaScript promises?

Both use a single-threaded event loop and async/await. The main difference: calling a JS async function starts it immediately and returns a running Promise, while calling a Python async def returns a lazy coroutine that only runs when awaited or wrapped in a task. Python also needs an explicit loop, started with asyncio.run.

Q4How would you send 1,000 prompts to an LLM API quickly without getting rate limited?

Run them concurrently with asyncio.gather or a TaskGroup, cap concurrency with one shared asyncio.Semaphore sized to the provider's limits, put a timeout on each call, retry 429 and 5xx with backoff, and use return_exceptions=True (or per-call try/except) so one failure does not lose the batch.

Q5What happens if you call time.sleep or requests.get inside an async function?

It blocks the event loop thread, so every other task freezes until it returns and the program loses all concurrency. Use the async equivalents (asyncio.sleep, httpx.AsyncClient) or move the blocking call to a thread with asyncio.to_thread.