liveBook · Manning

Coroutine

As explained in Building LLM Applications with DSPy

A coroutine is a function-like unit of computation that can pause and resume execution, enabling cooperative concurrency.

A coroutine is a function-like unit that can pause at an `await` point and resume later, letting other tasks run while it waits. With asyncio, an event loop manages these tasks—useful when an application spends more time waiting for language-model responses than processing data. section 7.5.1

Listing 7.17 asyncio example
import asyncio
import time

async def func1():
    print("Start func1")
    await asyncio.sleep(5)
    print("End func1")
    return "func1 complete"

async def func2():
    print("Start func2")
    await asyncio.sleep(3)
    print("End func2")
    return "func2 complete"

async def main():
    start_time = time.time()
    co_routines = asyncio.gather(func1(), func2())
    a, b = await co_routines
    print(a, b)
    end_time = time.time()
    print("time", end_time-start_time)

asyncio.run(main())

See two coroutines wait for different durations, run together with `asyncio.gather`, and return results with elapsed time measured. section 7.5.1

How Building LLM Applications with DSPy covers it

How deep it goes
Defines async functions, tasks, event loops, and await points, without detailing event-loop internals.
Examples
Demonstrates two coroutines waiting for different durations, gathered together with results and elapsed time printed.
What you can do after
Apply asyncio to run waiting tasks concurrently using coroutines and await points.
How it connects
Connects coroutines with asyncio, event loops, tasks, concurrency, and async/await.

Also explained in

Compare how 8 books explain coroutine →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building LLM Applications with DSPy. The section links point to the parts of the book it draws on.