Loading Python for AI Engineering...
Asyncio is a single-threaded cooperative concurrency framework. A central event loop executes non-blocking coroutines, context-switching immediately when a task awaits an I/O operation (such as waiting for an LLM API token or database query).
“An event loop is a single master chef at a diner. While a pancake is cooking on the griddle (awaiting network response), the chef chops onions for the next customer rather than standing frozen staring at the pancake.”
Invoking a synchronous requests.get() or time.sleep() inside an async function, completely freezing all concurrent API traffic.
import asyncio
async def fetch_llm_response(prompt: str) -> str:
print(f"Sending prompt: {prompt}")
# Simulates non-blocking network socket wait
await asyncio.sleep(0.5)
return f"Response for {prompt}"
async def main():
# Runs concurrently on single OS thread:
results = await asyncio.gather(
fetch_llm_response("Translate"),
fetch_llm_response("Summarize"),
fetch_llm_response("Classify")
)
print(results)
# asyncio.run(main())