{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "# Coroutines and asyncio\n",
    "\n",
    "**Agentic AI** · playground\n",
    "\n",
    "*A coroutine is a function that can suspend its execution at marked points and be resumed later. With an event loop that switches between suspended coroutines, one thread serves many waiting operations at once. The notebook covers the constructs that the labs of the course use: `async def` and `await`, top-level `await` in Jupyter, the event loop, `gather`, and the asynchronous context managers and iterators of PydanticAI and pydantic-graph (`async with agent.iter(...)`, `async for node in run`, `await anext(run)`). Tasks, cancellation, time limits, blocking calls and concurrency limits follow in `08b-async-tasks-and-cancellation.ipynb`.*"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1",
   "metadata": {},
   "source": [
    "## Concurrency for Waiting Programs\n",
    "\n",
    "**Concurrency is the property of a program that several of its operations are in progress during the same period of time.** It does not require that they execute at the same instant, which would be **parallelism**.\n",
    "\n",
    "An agent spends most of its running time waiting: for the reply of a model server, for a web request, for a tool. While it waits, the processor is idle. Suppose that a plan contains three independent steps of two seconds each. Executed one after the other, they take six seconds. Started together, they take two seconds, because the three waiting periods overlap. The computation itself did not become faster; the waiting was merged.\n",
    "\n",
    "`asyncio` is Python's mechanism for this case. It is suited to **input/output-bound** work (work whose duration is determined by waiting) and gives no advantage for **CPU-bound** work (work whose duration is determined by computation), which `10-processes-and-threads.ipynb` treats."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "## Coroutines\n",
    "\n",
    "**A coroutine is a function whose execution can be suspended and resumed.** The Python glossary contrasts it with an ordinary function, a subroutine: *\"Subroutines are entered at one point and exited at another point. Coroutines can be entered, exited, and resumed at many different points\"* ([Python Software Foundation, 2023, *Glossary*](https://docs.python.org/3.12/glossary.html#term-coroutine)). The syntax was introduced by [Selivanov (2015, PEP 492)](https://peps.python.org/pep-0492/)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "n0",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "**Two requests to two models, started by one caller, take as long as the slower one, not as long as both together.** `ask_model_a` waits 0.5 s and `ask_model_b` waits 0.8 s for its reply; the caller `ask_both` starts both, waits until both have replied and returns the two answers as a list, in the order of the arguments of `gather`. The two waiting periods overlap, so the total is about 0.8 s instead of 1.3 s. `asyncio.sleep(t)` stands for an operation that waits `t` seconds without using the processor; here it represents a request to a model server. The parts are explained below: `async def` and `await` in this section, the scheduler that switches between waiting functions in [*Event Loop*](#Event-Loop), and `gather` in [*Concurrent Execution with `gather`*](#Concurrent-Execution-with-gather)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "n1",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "import asyncio\n",
    "import time\n",
    "\n",
    "\n",
    "async def ask_model_a(prompt: str) -> str:\n",
    "    await asyncio.sleep(0.5)                        # model A: waits 0.5 s for its reply\n",
    "    return f\"A: answer to {prompt!r}\"\n",
    "\n",
    "\n",
    "async def ask_model_b(prompt: str) -> str:\n",
    "    await asyncio.sleep(0.8)                        # model B: waits 0.8 s for its reply\n",
    "    return f\"B: answer to {prompt!r}\"\n",
    "\n",
    "\n",
    "async def ask_both(prompt: str) -> list[str]:\n",
    "    # the caller starts both requests; their waiting periods overlap\n",
    "    return await asyncio.gather(ask_model_a(prompt), ask_model_b(prompt))\n",
    "\n",
    "\n",
    "start = time.perf_counter()\n",
    "answers = await ask_both(\"capital of Italy\")\n",
    "print(answers)\n",
    "print(f\"total: {time.perf_counter() - start:.2f} s\")  # about 0.8 s, not 0.5 + 0.8 = 1.3 s"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "n2",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "The mechanism consists of one keyword for the declaration and one for the suspension:\n",
    "\n",
    "- `async def` declares a **coroutine function**. Calling it does **not** execute the body. The call returns a **coroutine object**, a value that represents the execution that has not yet started.\n",
    "- `await x` executes the awaitable `x` and suspends the surrounding coroutine until `x` has a result. The suspension is the point at which other coroutines may proceed. `await` is permitted only inside `async def`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "async def ask_model(prompt: str, seconds: float = 0.3) -> str:\n",
    "    await asyncio.sleep(seconds)                    # stands for the request to a model server\n",
    "    return f\"answer to {prompt!r}\"\n",
    "\n",
    "\n",
    "coroutine = ask_model(\"2 + 2\")\n",
    "print(coroutine)                                    # a coroutine object: nothing has been executed\n",
    "print(await coroutine)                              # await executes it and yields its result"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ac1acd39-eaf0-4d5d-afd7-7fc6446e2e3b",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Top-Level `await` in Jupyter\n",
    "\n",
    "The last line uses `await` outside of any function. A notebook permits this, because Jupyter executes every cell inside an event loop that is already running. An **event loop** is the scheduler that holds the started coroutines and switches between them whenever one of them has to wait (see [*Event Loop*](#Event-Loop)). A Python script has no running event loop; there, the entry point is `asyncio.run(main())`, which creates a loop, executes the coroutine `main` to its end and closes the loop.\n",
    "\n",
    "The reverse does not hold. `asyncio.run` inside a notebook cell raises `RuntimeError: asyncio.run() cannot be called from a running event loop`. For the same reason the synchronous convenience methods of libraries, such as `agent.run_sync` in PydanticAI, fail in a notebook, with `RuntimeError: This event loop is already running`; `await agent.run(...)` is the form to use."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "### Missing `await`\n",
    "\n",
    "A call without `await` yields the coroutine object, not the result. The program continues with a wrong value, and Python reports `RuntimeWarning: coroutine '...' was never awaited` when the object is discarded. This is the most frequent defect in asynchronous code."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "answer = ask_model(\"capital of Italy\")              # await is missing\n",
    "print(type(answer).__name__)                        # a coroutine, not a str\n",
    "answer.close()                                      # discard it explicitly, to avoid the warning\n",
    "\n",
    "answer = await ask_model(\"capital of Italy\")\n",
    "print(type(answer).__name__, \"|\", answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "top-level-and-nested",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "### Top-Level Coroutine and Nested Coroutines\n",
    "\n",
    "**The top-level coroutine is the one coroutine handed to the event loop — `main` in `asyncio.run(main())`, or the coroutine after a top-level `await` in a cell; every other coroutine is started inside it.** A coroutine starts a child in one of two ways:\n",
    "\n",
    "- `await child(...)` executes the child as part of the caller, which is suspended until the child returns. Such calls nest to any depth.\n",
    "- `await asyncio.gather(child_1(...), child_2(...))` wraps each child in a **task**, a coroutine object that the event loop executes independently of its creator (`08b-async-tasks-and-cancellation.ipynb` treats tasks in detail). The children proceed concurrently; when all of them have returned, `gather` yields their results as a list, in the order of the arguments, not the order of completion.\n",
    "\n",
    "In the first example, the cell awaits `ask_both`, and `ask_both` gathers `ask_model_a` and `ask_model_b`:\n",
    "\n",
    "<div class=\"mermaid-figure\" style=\"max-width:100%;overflow-x:auto\">\n",
    "<svg style=\"width:100%;max-width:497.25px;height:auto\" id=\"mmd-0\" xmlns=\"http://www.w3.org/2000/svg\" class=\"flowchart\" viewBox=\"0 0 497.25 302\" role=\"graphics-document document\" aria-roledescription=\"flowchart-v2\"><style>#mmd-0{font-family:\"trebuchet ms\",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mmd-0 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mmd-0 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mmd-0 .error-icon{fill:#552222;}#mmd-0 .error-text{fill:#552222;stroke:#552222;}#mmd-0 .edge-thickness-normal{stroke-width:1px;}#mmd-0 .edge-thickness-thick{stroke-width:3.5px;}#mmd-0 .edge-pattern-solid{stroke-dasharray:0;}#mmd-0 .edge-thickness-invisible{stroke-width:0;fill:none;}#mmd-0 .edge-pattern-dashed{stroke-dasharray:3;}#mmd-0 .edge-pattern-dotted{stroke-dasharray:2;}#mmd-0 .marker{fill:#333333;stroke:#333333;}#mmd-0 .marker.cross{stroke:#333333;}#mmd-0 svg{font-family:\"trebuchet ms\",verdana,arial,sans-serif;font-size:16px;}#mmd-0 p{margin:0;}#mmd-0 .label{font-family:\"trebuchet ms\",verdana,arial,sans-serif;color:#333;}#mmd-0 .cluster-label text{fill:#333;}#mmd-0 .cluster-label span{color:#333;}#mmd-0 .cluster-label span p{background-color:transparent;}#mmd-0 .label text,#mmd-0 span{fill:#333;color:#333;}#mmd-0 .node rect,#mmd-0 .node circle,#mmd-0 .node ellipse,#mmd-0 .node polygon,#mmd-0 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mmd-0 .rough-node .label text,#mmd-0 .node .label text,#mmd-0 .image-shape .label,#mmd-0 .icon-shape .label{text-anchor:middle;}#mmd-0 .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mmd-0 .rough-node .label,#mmd-0 .node .label,#mmd-0 .image-shape .label,#mmd-0 .icon-shape .label{text-align:center;}#mmd-0 .node.clickable{cursor:pointer;}#mmd-0 .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mmd-0 .arrowheadPath{fill:#333333;}#mmd-0 .edgePath .path{stroke:#333333;stroke-width:1px;}#mmd-0 .flowchart-link{stroke:#333333;fill:none;}#mmd-0 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mmd-0 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mmd-0 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mmd-0 .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mmd-0 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mmd-0 .cluster text{fill:#333;}#mmd-0 .cluster span{color:#333;}#mmd-0 .node .collapsed-indicator{fill:#aaaa33;stroke:none;opacity:0.6;}#mmd-0 .node .collapsed-separator{stroke:#aaaa33;stroke-width:0.75px;}#mmd-0 div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:\"trebuchet ms\",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mmd-0 .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mmd-0 rect.text{fill:none;stroke-width:0;}#mmd-0 .icon-shape,#mmd-0 .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mmd-0 .icon-shape p,#mmd-0 .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mmd-0 .icon-shape .label rect,#mmd-0 .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mmd-0 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mmd-0 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mmd-0 .node .neo-node{stroke:#9370DB;}#mmd-0 [data-look=\"neo\"].node rect,#mmd-0 [data-look=\"neo\"].cluster rect,#mmd-0 [data-look=\"neo\"].node polygon{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#mmd-0 [data-look=\"neo\"].swimlane.cluster rect{filter:none;}#mmd-0 [data-look=\"neo\"].node path{stroke:#9370DB;stroke-width:1px;}#mmd-0 [data-look=\"neo\"].node .outer-path{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#mmd-0 [data-look=\"neo\"].node .neo-line path{stroke:#9370DB;filter:none;}#mmd-0 [data-look=\"neo\"].node circle{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#mmd-0 [data-look=\"neo\"].node circle .state-start{fill:#000000;}#mmd-0 [data-look=\"neo\"].icon-shape .icon{fill:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#mmd-0 [data-look=\"neo\"].icon-shape .icon-neo path{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#mmd-0 :root{--mermaid-font-family:\"trebuchet ms\",verdana,arial,sans-serif;}</style><g><marker id=\"mmd-0_flowchart-v2-pointEnd\" class=\"marker flowchart-v2\" viewBox=\"0 0 10 10\" refX=\"5\" refY=\"5\" markerUnits=\"userSpaceOnUse\" markerWidth=\"8\" markerHeight=\"8\" orient=\"auto\"><path d=\"M 0 0 L 10 5 L 0 10 z\" class=\"arrowMarkerPath\" style=\"stroke-width: 1; stroke-dasharray: 1, 0;\"></path></marker><marker id=\"mmd-0_flowchart-v2-pointStart\" class=\"marker flowchart-v2\" viewBox=\"0 0 10 10\" refX=\"4.5\" refY=\"5\" markerUnits=\"userSpaceOnUse\" markerWidth=\"8\" markerHeight=\"8\" orient=\"auto\"><path d=\"M 0 5 L 10 10 L 10 0 z\" class=\"arrowMarkerPath\" style=\"stroke-width: 1; stroke-dasharray: 1, 0;\"></path></marker><marker id=\"mmd-0_flowchart-v2-pointEnd-margin\" class=\"marker flowchart-v2\" viewBox=\"0 0 11.5 14\" refX=\"11.5\" refY=\"7\" markerUnits=\"userSpaceOnUse\" markerWidth=\"10.5\" markerHeight=\"14\" orient=\"auto\"><path d=\"M 0 0 L 11.5 7 L 0 14 z\" class=\"arrowMarkerPath\" style=\"stroke-width: 0; stroke-dasharray: 1, 0;\"></path></marker><marker id=\"mmd-0_flowchart-v2-pointStart-margin\" class=\"marker flowchart-v2\" viewBox=\"0 0 11.5 14\" refX=\"1\" refY=\"7\" markerUnits=\"userSpaceOnUse\" markerWidth=\"11.5\" markerHeight=\"14\" orient=\"auto\"><polygon points=\"0,7 11.5,14 11.5,0\" class=\"arrowMarkerPath\" style=\"stroke-width: 0; stroke-dasharray: 1, 0;\"></polygon></marker><marker id=\"mmd-0_flowchart-v2-circleEnd\" class=\"marker flowchart-v2\" viewBox=\"0 0 10 10\" refX=\"11\" refY=\"5\" markerUnits=\"userSpaceOnUse\" markerWidth=\"11\" markerHeight=\"11\" orient=\"auto\"><circle cx=\"5\" cy=\"5\" r=\"5\" class=\"arrowMarkerPath\" style=\"stroke-width: 1; stroke-dasharray: 1, 0;\"></circle></marker><marker id=\"mmd-0_flowchart-v2-circleStart\" class=\"marker flowchart-v2\" viewBox=\"0 0 10 10\" refX=\"-1\" refY=\"5\" markerUnits=\"userSpaceOnUse\" markerWidth=\"11\" markerHeight=\"11\" orient=\"auto\"><circle cx=\"5\" cy=\"5\" r=\"5\" class=\"arrowMarkerPath\" style=\"stroke-width: 1; stroke-dasharray: 1, 0;\"></circle></marker><marker id=\"mmd-0_flowchart-v2-circleEnd-margin\" class=\"marker flowchart-v2\" viewBox=\"0 0 10 10\" refY=\"5\" refX=\"12.25\" markerUnits=\"userSpaceOnUse\" markerWidth=\"14\" markerHeight=\"14\" orient=\"auto\"><circle cx=\"5\" cy=\"5\" r=\"5\" class=\"arrowMarkerPath\" style=\"stroke-width: 0; stroke-dasharray: 1, 0;\"></circle></marker><marker id=\"mmd-0_flowchart-v2-circleStart-margin\" class=\"marker flowchart-v2\" viewBox=\"0 0 10 10\" refX=\"-2\" refY=\"5\" markerUnits=\"userSpaceOnUse\" markerWidth=\"14\" markerHeight=\"14\" orient=\"auto\"><circle cx=\"5\" cy=\"5\" r=\"5\" class=\"arrowMarkerPath\" style=\"stroke-width: 0; stroke-dasharray: 1, 0;\"></circle></marker><marker id=\"mmd-0_flowchart-v2-crossEnd\" class=\"marker cross flowchart-v2\" viewBox=\"0 0 11 11\" refX=\"12\" refY=\"5.2\" markerUnits=\"userSpaceOnUse\" markerWidth=\"11\" markerHeight=\"11\" orient=\"auto\"><path d=\"M 1,1 l 9,9 M 10,1 l -9,9\" class=\"arrowMarkerPath\" style=\"stroke-width: 2; stroke-dasharray: 1, 0;\"></path></marker><marker id=\"mmd-0_flowchart-v2-crossStart\" class=\"marker cross flowchart-v2\" viewBox=\"0 0 11 11\" refX=\"-1\" refY=\"5.2\" markerUnits=\"userSpaceOnUse\" markerWidth=\"11\" markerHeight=\"11\" orient=\"auto\"><path d=\"M 1,1 l 9,9 M 10,1 l -9,9\" class=\"arrowMarkerPath\" style=\"stroke-width: 2; stroke-dasharray: 1, 0;\"></path></marker><marker id=\"mmd-0_flowchart-v2-crossEnd-margin\" class=\"marker cross flowchart-v2\" viewBox=\"0 0 15 15\" refX=\"17.7\" refY=\"7.5\" markerUnits=\"userSpaceOnUse\" markerWidth=\"12\" markerHeight=\"12\" orient=\"auto\"><path d=\"M 1,1 L 14,14 M 1,14 L 14,1\" class=\"arrowMarkerPath\" style=\"stroke-width: 2.5;\"></path></marker><marker id=\"mmd-0_flowchart-v2-crossStart-margin\" class=\"marker cross flowchart-v2\" viewBox=\"0 0 15 15\" refX=\"-3.5\" refY=\"7.5\" markerUnits=\"userSpaceOnUse\" markerWidth=\"12\" markerHeight=\"12\" orient=\"auto\"><path d=\"M 1,1 L 14,14 M 1,14 L 14,1\" class=\"arrowMarkerPath\" style=\"stroke-width: 2.5; stroke-dasharray: 1, 0;\"></path></marker><g class=\"root\"><g class=\"clusters\"></g><g class=\"edgePaths\"><path d=\"M248.625,56L248.625,61.917C248.625,67.833,248.625,79.667,248.625,90.833C248.625,102,248.625,112.5,248.625,117.75L248.625,123\" id=\"mmd-0-L_T_AB_0\" class=\" edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link\" style=\";\" data-edge=\"true\" data-et=\"edge\" data-id=\"L_T_AB_0\" data-points=\"W3sieCI6MjQ4LjYyNSwieSI6NTZ9LHsieCI6MjQ4LjYyNSwieSI6OTEuNX0seyJ4IjoyNDguNjI1LCJ5IjoxMjd9XQ==\" data-look=\"classic\" marker-end=\"url(#mmd-0_flowchart-v2-pointEnd)\"></path><path d=\"M195.054,175L181.847,180.917C168.64,186.833,142.226,198.667,129.019,209.833C115.813,221,115.813,231.5,115.813,236.75L115.813,242\" id=\"mmd-0-L_AB_A_0\" class=\" edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link\" style=\";\" data-edge=\"true\" data-et=\"edge\" data-id=\"L_AB_A_0\" data-points=\"W3sieCI6MTk1LjA1MzU3MTQyODU3MTQ0LCJ5IjoxNzV9LHsieCI6MTE1LjgxMjUsInkiOjIxMC41fSx7IngiOjExNS44MTI1LCJ5IjoyNDZ9XQ==\" data-look=\"classic\" marker-end=\"url(#mmd-0_flowchart-v2-pointEnd)\"></path><path d=\"M302.196,175L315.403,180.917C328.61,186.833,355.024,198.667,368.231,209.833C381.438,221,381.438,231.5,381.438,236.75L381.438,242\" id=\"mmd-0-L_AB_B_0\" class=\" edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link\" style=\";\" data-edge=\"true\" data-et=\"edge\" data-id=\"L_AB_B_0\" data-points=\"W3sieCI6MzAyLjE5NjQyODU3MTQyODU2LCJ5IjoxNzV9LHsieCI6MzgxLjQzNzUsInkiOjIxMC41fSx7IngiOjM4MS40Mzc1LCJ5IjoyNDZ9XQ==\" data-look=\"classic\" marker-end=\"url(#mmd-0_flowchart-v2-pointEnd)\"></path></g><g class=\"edgeLabels\"><g class=\"edgeLabel\" transform=\"translate(248.625, 91.5)\"><g class=\"label\" data-id=\"L_T_AB_0\" transform=\"translate(-0.2734375, -10.5)\"><g><rect class=\"background\" style=\"\" x=\"-20.6796875\" y=\"0\" width=\"41.90625\" height=\"21\"></rect><text y=\"-10.1\" text-anchor=\"middle\" style=\"\"><tspan class=\"text-outer-tspan row\" x=\"0\" y=\"-0.1em\" dy=\"1.1em\" text-anchor=\"middle\"><tspan font-style=\"normal\" class=\"text-inner-tspan\" font-weight=\"normal\">await</tspan></tspan></text></g></g></g><g class=\"edgeLabel\" transform=\"translate(115.8125, 210.5)\"><g class=\"label\" data-id=\"L_AB_A_0\" transform=\"translate(-0.49609375, -10.5)\"><g><rect class=\"background\" style=\"\" x=\"-43.8046875\" y=\"0\" width=\"88.6015625\" height=\"21\"></rect><text y=\"-10.1\" text-anchor=\"middle\" style=\"\"><tspan class=\"text-outer-tspan row\" x=\"0\" y=\"-0.1em\" dy=\"1.1em\" text-anchor=\"middle\"><tspan font-style=\"normal\" class=\"text-inner-tspan\" font-weight=\"normal\">gather:</tspan><tspan font-style=\"normal\" class=\"text-inner-tspan\" font-weight=\"normal\"> task</tspan></tspan></text></g></g></g><g class=\"edgeLabel\" transform=\"translate(381.4375, 210.5)\"><g class=\"label\" data-id=\"L_AB_B_0\" transform=\"translate(-0.49609375, -10.5)\"><g><rect class=\"background\" style=\"\" x=\"-43.8046875\" y=\"0\" width=\"88.6015625\" height=\"21\"></rect><text y=\"-10.1\" text-anchor=\"middle\" style=\"\"><tspan class=\"text-outer-tspan row\" x=\"0\" y=\"-0.1em\" dy=\"1.1em\" text-anchor=\"middle\"><tspan font-style=\"normal\" class=\"text-inner-tspan\" font-weight=\"normal\">gather:</tspan><tspan font-style=\"normal\" class=\"text-inner-tspan\" font-weight=\"normal\"> task</tspan></tspan></text></g></g></g></g><g class=\"nodes\"><g class=\"node default  \" id=\"mmd-0-flowchart-T-0\" data-look=\"classic\" transform=\"translate(248.625, 32)\"><rect class=\"basic label-container\" style=\"\" x=\"-111.8125\" y=\"-24\" width=\"223.625\" height=\"48\"></rect><g class=\"label\" style=\"\" transform=\"translate(0, -9)\"><rect></rect><g><rect class=\"background\" style=\"stroke: none\"></rect><text y=\"-10.1\" style=\"\"><tspan class=\"text-outer-tspan row\" x=\"0\" y=\"-0.1em\" dy=\"1.1em\"><tspan font-style=\"normal\" class=\"text-inner-tspan\" font-weight=\"normal\">cell:</tspan><tspan font-style=\"normal\" class=\"text-inner-tspan\" font-weight=\"normal\"> await</tspan><tspan font-style=\"normal\" class=\"text-inner-tspan\" font-weight=\"normal\"> ask_both(...)</tspan></tspan></text></g></g></g><g class=\"node default  \" id=\"mmd-0-flowchart-AB-1\" data-look=\"classic\" transform=\"translate(248.625, 151)\"><rect class=\"basic label-container\" style=\"\" x=\"-92.6953125\" y=\"-24\" width=\"185.390625\" height=\"48\"></rect><g class=\"label\" style=\"\" transform=\"translate(0, -9)\"><rect></rect><g><rect class=\"background\" style=\"stroke: none\"></rect><text y=\"-10.1\" style=\"\"><tspan class=\"text-outer-tspan row\" x=\"0\" y=\"-0.1em\" dy=\"1.1em\"><tspan font-style=\"normal\" class=\"text-inner-tspan\" font-weight=\"normal\">ask_both(prompt)</tspan></tspan></text></g></g></g><g class=\"node default  \" id=\"mmd-0-flowchart-A-3\" data-look=\"classic\" transform=\"translate(115.8125, 270)\"><rect class=\"basic label-container\" style=\"\" x=\"-107.8125\" y=\"-24\" width=\"215.625\" height=\"48\"></rect><g class=\"label\" style=\"\" transform=\"translate(0, -9)\"><rect></rect><g><rect class=\"background\" style=\"stroke: none\"></rect><text y=\"-10.1\" style=\"\"><tspan class=\"text-outer-tspan row\" x=\"0\" y=\"-0.1em\" dy=\"1.1em\"><tspan font-style=\"normal\" class=\"text-inner-tspan\" font-weight=\"normal\">ask_model_a(prompt)</tspan></tspan></text></g></g></g><g class=\"node default  \" id=\"mmd-0-flowchart-B-5\" data-look=\"classic\" transform=\"translate(381.4375, 270)\"><rect class=\"basic label-container\" style=\"\" x=\"-107.8125\" y=\"-24\" width=\"215.625\" height=\"48\"></rect><g class=\"label\" style=\"\" transform=\"translate(0, -9)\"><rect></rect><g><rect class=\"background\" style=\"stroke: none\"></rect><text y=\"-10.1\" style=\"\"><tspan class=\"text-outer-tspan row\" x=\"0\" y=\"-0.1em\" dy=\"1.1em\"><tspan font-style=\"normal\" class=\"text-inner-tspan\" font-weight=\"normal\">ask_model_b(prompt)</tspan></tspan></text></g></g></g></g></g></g><defs><filter id=\"mmd-0-drop-shadow\" height=\"130%\" width=\"130%\"><feDropShadow dx=\"4\" dy=\"4\" stdDeviation=\"0\" flood-opacity=\"0.06\" flood-color=\"#000000\"></feDropShadow></filter></defs><defs><filter id=\"mmd-0-drop-shadow-small\" height=\"150%\" width=\"150%\"><feDropShadow dx=\"2\" dy=\"2\" stdDeviation=\"0\" flood-opacity=\"0.06\" flood-color=\"#000000\"></feDropShadow></filter></defs></svg>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "## Event Loop\n",
    "\n",
    "**An event loop is the scheduler of asynchronous code: it holds the set of started coroutines, executes one of them until that coroutine reaches an `await` that has to wait, and then continues with another one that is ready.** All coroutines of a loop execute in **one thread**. A switch happens only at an `await`; between two `await` expressions, a coroutine is never interrupted. This form of scheduling is called **cooperative**: each coroutine returns control voluntarily.\n",
    "\n",
    "The loop does not call coroutine *functions*. It receives coroutine *objects*, which the program has already created by calling the coroutine functions, and **resumes** them: each resumption calls the coroutine object's `send` method, which executes the body up to the next suspending `await` and returns control to the loop. A program hands its top-level coroutine to the loop once; every further coroutine reaches the loop through an `await`, a task or `gather` inside it. In a script, the loop is started by `asyncio.run`, here with the two model requests of the first example:\n",
    "\n",
    "```python\n",
    "async def main() -> None:\n",
    "    answers = await ask_both(\"capital of Italy\")\n",
    "    print(answers)\n",
    "\n",
    "\n",
    "asyncio.run(main())   # create a loop, execute main() to its end, close the loop\n",
    "```\n",
    "\n",
    "`asyncio.run(main())` corresponds, in simplified form, to three steps — create a loop, execute `main()` on it to its end, close the loop — which are the three statements of the code below. `asyncio.run` additionally cancels the tasks that are still pending and closes asynchronous generators before it closes the loop:\n",
    "\n",
    "```python\n",
    "loop = asyncio.new_event_loop()\n",
    "try:\n",
    "    loop.run_until_complete(main())   # wrap main() in a task, resume tasks until main() has returned\n",
    "finally:\n",
    "    loop.close()\n",
    "```\n",
    "\n",
    "In a notebook, Jupyter has already executed the first step and keeps its loop running between cells; a top-level `await` in a cell hands the coroutine to that loop.\n",
    "\n",
    "<div class=\"mermaid-figure\" style=\"max-width:100%;overflow-x:auto\">\n",
    "<svg style=\"width:100%;max-width:1319.5px;height:auto\" id=\"mmd-1\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"-50 -10 1319.5 725\" role=\"graphics-document document\" aria-roledescription=\"sequence\"><g><rect x=\"1059.5\" y=\"639\" fill=\"#eaeaea\" stroke=\"#666\" width=\"160\" height=\"65\" name=\"B\" rx=\"3\" ry=\"3\" class=\"actor actor-bottom\"></rect><text x=\"1139.5\" y=\"671.5\" dominant-baseline=\"central\" alignment-baseline=\"central\" class=\"actor actor-box\" style=\"text-anchor: middle; font-size: 16px; font-weight: 400;\"><tspan x=\"1139.5\" dy=\"0\">task B (ask_model_b)</tspan></text></g><g><rect x=\"850.5\" y=\"639\" fill=\"#eaeaea\" stroke=\"#666\" width=\"159\" height=\"65\" name=\"A\" rx=\"3\" ry=\"3\" class=\"actor actor-bottom\"></rect><text x=\"930\" y=\"671.5\" dominant-baseline=\"central\" alignment-baseline=\"central\" class=\"actor actor-box\" style=\"text-anchor: middle; font-size: 16px; font-weight: 400;\"><tspan x=\"930\" dy=\"0\">task A (ask_model_a)</tspan></text></g><g><rect x=\"451\" y=\"639\" fill=\"#eaeaea\" stroke=\"#666\" width=\"150\" height=\"65\" name=\"L\" rx=\"3\" ry=\"3\" class=\"actor actor-bottom\"></rect><text x=\"526\" y=\"671.5\" dominant-baseline=\"central\" alignment-baseline=\"central\" class=\"actor actor-box\" style=\"text-anchor: middle; font-size: 16px; font-weight: 400;\"><tspan x=\"526\" dy=\"0\">event loop</tspan></text></g><g><rect x=\"0\" y=\"639\" fill=\"#eaeaea\" stroke=\"#666\" width=\"150\" height=\"65\" name=\"P\" rx=\"3\" ry=\"3\" class=\"actor actor-bottom\"></rect><text x=\"75\" y=\"671.5\" dominant-baseline=\"central\" alignment-baseline=\"central\" class=\"actor actor-box\" style=\"text-anchor: middle; font-size: 16px; font-weight: 400;\"><tspan x=\"75\" dy=\"0\">ask_both(prompt)</tspan></text></g><g><line id=\"actor3\" x1=\"1139.5\" y1=\"65\" x2=\"1139.5\" y2=\"639\" class=\"actor-line 200\" stroke-width=\"0.5px\" stroke=\"#999\" name=\"B\" data-et=\"life-line\" data-id=\"B\"></line><g id=\"root-3\" data-et=\"participant\" data-type=\"participant\" data-id=\"B\"><rect x=\"1059.5\" y=\"0\" fill=\"#eaeaea\" stroke=\"#666\" width=\"160\" height=\"65\" name=\"B\" rx=\"3\" ry=\"3\" class=\"actor actor-top\"></rect><text x=\"1139.5\" y=\"32.5\" dominant-baseline=\"central\" alignment-baseline=\"central\" class=\"actor actor-box\" style=\"text-anchor: middle; font-size: 16px; font-weight: 400;\"><tspan x=\"1139.5\" dy=\"0\">task B (ask_model_b)</tspan></text></g></g><g><line id=\"actor2\" x1=\"930\" y1=\"65\" x2=\"930\" y2=\"639\" class=\"actor-line 200\" stroke-width=\"0.5px\" stroke=\"#999\" name=\"A\" data-et=\"life-line\" data-id=\"A\"></line><g id=\"root-2\" data-et=\"participant\" data-type=\"participant\" data-id=\"A\"><rect x=\"850.5\" y=\"0\" fill=\"#eaeaea\" stroke=\"#666\" width=\"159\" height=\"65\" name=\"A\" rx=\"3\" ry=\"3\" class=\"actor actor-top\"></rect><text x=\"930\" y=\"32.5\" dominant-baseline=\"central\" alignment-baseline=\"central\" class=\"actor actor-box\" style=\"text-anchor: middle; font-size: 16px; font-weight: 400;\"><tspan x=\"930\" dy=\"0\">task A (ask_model_a)</tspan></text></g></g><g><line id=\"actor1\" x1=\"526\" y1=\"65\" x2=\"526\" y2=\"639\" class=\"actor-line 200\" stroke-width=\"0.5px\" stroke=\"#999\" name=\"L\" data-et=\"life-line\" data-id=\"L\"></line><g id=\"root-1\" data-et=\"participant\" data-type=\"participant\" data-id=\"L\"><rect x=\"451\" y=\"0\" fill=\"#eaeaea\" stroke=\"#666\" width=\"150\" height=\"65\" name=\"L\" rx=\"3\" ry=\"3\" class=\"actor actor-top\"></rect><text x=\"526\" y=\"32.5\" dominant-baseline=\"central\" alignment-baseline=\"central\" class=\"actor actor-box\" style=\"text-anchor: middle; font-size: 16px; font-weight: 400;\"><tspan x=\"526\" dy=\"0\">event loop</tspan></text></g></g><g><line id=\"actor0\" x1=\"75\" y1=\"65\" x2=\"75\" y2=\"639\" class=\"actor-line 200\" stroke-width=\"0.5px\" stroke=\"#999\" name=\"P\" data-et=\"life-line\" data-id=\"P\"></line><g id=\"root-0\" data-et=\"participant\" data-type=\"participant\" data-id=\"P\"><rect x=\"0\" y=\"0\" fill=\"#eaeaea\" stroke=\"#666\" width=\"150\" height=\"65\" name=\"P\" rx=\"3\" ry=\"3\" class=\"actor actor-top\"></rect><text x=\"75\" y=\"32.5\" dominant-baseline=\"central\" alignment-baseline=\"central\" class=\"actor actor-box\" style=\"text-anchor: middle; font-size: 16px; font-weight: 400;\"><tspan x=\"75\" dy=\"0\">ask_both(prompt)</tspan></text></g></g><style>#mmd-1{font-family:\"trebuchet ms\",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mmd-1 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mmd-1 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mmd-1 .error-icon{fill:#552222;}#mmd-1 .error-text{fill:#552222;stroke:#552222;}#mmd-1 .edge-thickness-normal{stroke-width:1px;}#mmd-1 .edge-thickness-thick{stroke-width:3.5px;}#mmd-1 .edge-pattern-solid{stroke-dasharray:0;}#mmd-1 .edge-thickness-invisible{stroke-width:0;fill:none;}#mmd-1 .edge-pattern-dashed{stroke-dasharray:3;}#mmd-1 .edge-pattern-dotted{stroke-dasharray:2;}#mmd-1 .marker{fill:#333333;stroke:#333333;}#mmd-1 .marker.cross{stroke:#333333;}#mmd-1 svg{font-family:\"trebuchet ms\",verdana,arial,sans-serif;font-size:16px;}#mmd-1 p{margin:0;}#mmd-1 .actor{stroke:#9370DB;fill:#ECECFF;stroke-width:1;}#mmd-1 rect.actor.outer-path[data-look=\"neo\"]{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#mmd-1 rect.note[data-look=\"neo\"]{stroke:#aaaa33;fill:#fff5ad;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#mmd-1 text.actor&gt;tspan{fill:black;stroke:none;}#mmd-1 .actor-line{stroke:#9370DB;}#mmd-1 .innerArc{stroke-width:1.5;stroke-dasharray:none;}#mmd-1 .messageLine0{stroke-width:1.5;stroke-dasharray:none;stroke:#333;}#mmd-1 .messageLine1{stroke-width:1.5;stroke-dasharray:2,2;stroke:#333;}#mmd-1 [id$=\"-arrowhead\"] path{fill:#333;stroke:#333;}#mmd-1 .sequenceNumber{fill:white;}#mmd-1 [id$=\"-sequencenumber\"]{fill:#333;}#mmd-1 [id$=\"-crosshead\"] path{fill:#333;stroke:#333;}#mmd-1 .messageText{fill:#333;stroke:none;}#mmd-1 .labelBox{stroke:#9370DB;fill:#ECECFF;filter:none;}#mmd-1 .labelText,#mmd-1 .labelText&gt;tspan{fill:black;stroke:none;}#mmd-1 .loopText,#mmd-1 .loopText&gt;tspan{fill:black;stroke:none;}#mmd-1 .sectionTitle,#mmd-1 .sectionTitle&gt;tspan{fill:black;stroke:none;}#mmd-1 .loopLine{stroke-width:2px;stroke-dasharray:2,2;stroke:#9370DB;fill:#9370DB;}#mmd-1 .note{stroke:#aaaa33;fill:#fff5ad;}#mmd-1 .noteText,#mmd-1 .noteText&gt;tspan{fill:black;stroke:none;font-weight:normal;}#mmd-1 .activation0{fill:#f4f4f4;stroke:#666;}#mmd-1 .activation1{fill:#f4f4f4;stroke:#666;}#mmd-1 .activation2{fill:#f4f4f4;stroke:#666;}#mmd-1 .actorPopupMenu{position:absolute;}#mmd-1 .actorPopupMenuPanel{position:absolute;fill:#ECECFF;box-shadow:0px 8px 16px 0px rgba(0,0,0,0.2);filter:drop-shadow(3px 5px 2px rgb(0 0 0 / 0.4));}#mmd-1 .actor-man circle,#mmd-1 line{fill:#ECECFF;stroke-width:2px;}#mmd-1 g rect.rect{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));stroke:#9370DB;}#mmd-1 .node .neo-node{stroke:#9370DB;}#mmd-1 [data-look=\"neo\"].node rect,#mmd-1 [data-look=\"neo\"].cluster rect,#mmd-1 [data-look=\"neo\"].node polygon{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#mmd-1 [data-look=\"neo\"].swimlane.cluster rect{filter:none;}#mmd-1 [data-look=\"neo\"].node path{stroke:#9370DB;stroke-width:1px;}#mmd-1 [data-look=\"neo\"].node .outer-path{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#mmd-1 [data-look=\"neo\"].node .neo-line path{stroke:#9370DB;filter:none;}#mmd-1 [data-look=\"neo\"].node circle{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#mmd-1 [data-look=\"neo\"].node circle .state-start{fill:#000000;}#mmd-1 [data-look=\"neo\"].icon-shape .icon{fill:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#mmd-1 [data-look=\"neo\"].icon-shape .icon-neo path{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#mmd-1 :root{--mermaid-font-family:\"trebuchet ms\",verdana,arial,sans-serif;}</style><g></g><defs><symbol id=\"mmd-1-computer\" width=\"24\" height=\"24\"><path transform=\"scale(.5)\" d=\"M2 2v13h20v-13h-20zm18 11h-16v-9h16v9zm-10.228 6l.466-1h3.524l.467 1h-4.457zm14.228 3h-24l2-6h2.104l-1.33 4h18.45l-1.297-4h2.073l2 6zm-5-10h-14v-7h14v7z\"></path></symbol></defs><defs><symbol id=\"mmd-1-database\" fill-rule=\"evenodd\" clip-rule=\"evenodd\"><path transform=\"scale(.5)\" d=\"M12.258.001l.256.004.255.005.253.008.251.01.249.012.247.015.246.016.242.019.241.02.239.023.236.024.233.027.231.028.229.031.225.032.223.034.22.036.217.038.214.04.211.041.208.043.205.045.201.046.198.048.194.05.191.051.187.053.183.054.18.056.175.057.172.059.168.06.163.061.16.063.155.064.15.066.074.033.073.033.071.034.07.034.069.035.068.035.067.035.066.035.064.036.064.036.062.036.06.036.06.037.058.037.058.037.055.038.055.038.053.038.052.038.051.039.05.039.048.039.047.039.045.04.044.04.043.04.041.04.04.041.039.041.037.041.036.041.034.041.033.042.032.042.03.042.029.042.027.042.026.043.024.043.023.043.021.043.02.043.018.044.017.043.015.044.013.044.012.044.011.045.009.044.007.045.006.045.004.045.002.045.001.045v17l-.001.045-.002.045-.004.045-.006.045-.007.045-.009.044-.011.045-.012.044-.013.044-.015.044-.017.043-.018.044-.02.043-.021.043-.023.043-.024.043-.026.043-.027.042-.029.042-.03.042-.032.042-.033.042-.034.041-.036.041-.037.041-.039.041-.04.041-.041.04-.043.04-.044.04-.045.04-.047.039-.048.039-.05.039-.051.039-.052.038-.053.038-.055.038-.055.038-.058.037-.058.037-.06.037-.06.036-.062.036-.064.036-.064.036-.066.035-.067.035-.068.035-.069.035-.07.034-.071.034-.073.033-.074.033-.15.066-.155.064-.16.063-.163.061-.168.06-.172.059-.175.057-.18.056-.183.054-.187.053-.191.051-.194.05-.198.048-.201.046-.205.045-.208.043-.211.041-.214.04-.217.038-.22.036-.223.034-.225.032-.229.031-.231.028-.233.027-.236.024-.239.023-.241.02-.242.019-.246.016-.247.015-.249.012-.251.01-.253.008-.255.005-.256.004-.258.001-.258-.001-.256-.004-.255-.005-.253-.008-.251-.01-.249-.012-.247-.015-.245-.016-.243-.019-.241-.02-.238-.023-.236-.024-.234-.027-.231-.028-.228-.031-.226-.032-.223-.034-.22-.036-.217-.038-.214-.04-.211-.041-.208-.043-.204-.045-.201-.046-.198-.048-.195-.05-.19-.051-.187-.053-.184-.054-.179-.056-.176-.057-.172-.059-.167-.06-.164-.061-.159-.063-.155-.064-.151-.066-.074-.033-.072-.033-.072-.034-.07-.034-.069-.035-.068-.035-.067-.035-.066-.035-.064-.036-.063-.036-.062-.036-.061-.036-.06-.037-.058-.037-.057-.037-.056-.038-.055-.038-.053-.038-.052-.038-.051-.039-.049-.039-.049-.039-.046-.039-.046-.04-.044-.04-.043-.04-.041-.04-.04-.041-.039-.041-.037-.041-.036-.041-.034-.041-.033-.042-.032-.042-.03-.042-.029-.042-.027-.042-.026-.043-.024-.043-.023-.043-.021-.043-.02-.043-.018-.044-.017-.043-.015-.044-.013-.044-.012-.044-.011-.045-.009-.044-.007-.045-.006-.045-.004-.045-.002-.045-.001-.045v-17l.001-.045.002-.045.004-.045.006-.045.007-.045.009-.044.011-.045.012-.044.013-.044.015-.044.017-.043.018-.044.02-.043.021-.043.023-.043.024-.043.026-.043.027-.042.029-.042.03-.042.032-.042.033-.042.034-.041.036-.041.037-.041.039-.041.04-.041.041-.04.043-.04.044-.04.046-.04.046-.039.049-.039.049-.039.051-.039.052-.038.053-.038.055-.038.056-.038.057-.037.058-.037.06-.037.061-.036.062-.036.063-.036.064-.036.066-.035.067-.035.068-.035.069-.035.07-.034.072-.034.072-.033.074-.033.151-.066.155-.064.159-.063.164-.061.167-.06.172-.059.176-.057.179-.056.184-.054.187-.053.19-.051.195-.05.198-.048.201-.046.204-.045.208-.043.211-.041.214-.04.217-.038.22-.036.223-.034.226-.032.228-.031.231-.028.234-.027.236-.024.238-.023.241-.02.243-.019.245-.016.247-.015.249-.012.251-.01.253-.008.255-.005.256-.004.258-.001.258.001zm-9.258 20.499v.01l.001.021.003.021.004.022.005.021.006.022.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.023.018.024.019.024.021.024.022.025.023.024.024.025.052.049.056.05.061.051.066.051.07.051.075.051.079.052.084.052.088.052.092.052.097.052.102.051.105.052.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.048.144.049.147.047.152.047.155.047.16.045.163.045.167.043.171.043.176.041.178.041.183.039.187.039.19.037.194.035.197.035.202.033.204.031.209.03.212.029.216.027.219.025.222.024.226.021.23.02.233.018.236.016.24.015.243.012.246.01.249.008.253.005.256.004.259.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.021.224-.024.22-.026.216-.027.212-.028.21-.031.205-.031.202-.034.198-.034.194-.036.191-.037.187-.039.183-.04.179-.04.175-.042.172-.043.168-.044.163-.045.16-.046.155-.046.152-.047.148-.048.143-.049.139-.049.136-.05.131-.05.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.053.083-.051.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.05.023-.024.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.023.01-.022.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.127l-.077.055-.08.053-.083.054-.085.053-.087.052-.09.052-.093.051-.095.05-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.045-.118.044-.12.043-.122.042-.124.042-.126.041-.128.04-.13.04-.132.038-.134.038-.135.037-.138.037-.139.035-.142.035-.143.034-.144.033-.147.032-.148.031-.15.03-.151.03-.153.029-.154.027-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.01-.179.008-.179.008-.181.006-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.006-.179-.008-.179-.008-.178-.01-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.027-.153-.029-.151-.03-.15-.03-.148-.031-.146-.032-.145-.033-.143-.034-.141-.035-.14-.035-.137-.037-.136-.037-.134-.038-.132-.038-.13-.04-.128-.04-.126-.041-.124-.042-.122-.042-.12-.044-.117-.043-.116-.045-.113-.045-.112-.046-.109-.047-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.05-.093-.052-.09-.051-.087-.052-.085-.053-.083-.054-.08-.054-.077-.054v4.127zm0-5.654v.011l.001.021.003.021.004.021.005.022.006.022.007.022.009.022.01.022.011.023.012.023.013.023.015.024.016.023.017.024.018.024.019.024.021.024.022.024.023.025.024.024.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.052.11.051.114.051.119.052.123.05.127.051.131.05.135.049.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.044.171.042.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.022.23.02.233.018.236.016.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.012.241-.015.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.048.139-.05.136-.049.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.051.051-.049.023-.025.023-.024.021-.025.02-.024.019-.024.018-.024.017-.024.015-.023.014-.023.013-.024.012-.022.01-.023.01-.023.008-.022.006-.022.006-.022.004-.021.004-.022.001-.021.001-.021v-4.139l-.077.054-.08.054-.083.054-.085.052-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.044-.118.044-.12.044-.122.042-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.035-.143.033-.144.033-.147.033-.148.031-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.009-.179.009-.179.007-.181.007-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.007-.179-.007-.179-.009-.178-.009-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.031-.146-.033-.145-.033-.143-.033-.141-.035-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.04-.126-.041-.124-.042-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.051-.093-.051-.09-.051-.087-.053-.085-.052-.083-.054-.08-.054-.077-.054v4.139zm0-5.666v.011l.001.02.003.022.004.021.005.022.006.021.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.024.018.023.019.024.021.025.022.024.023.024.024.025.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.051.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.043.171.043.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.021.23.02.233.018.236.017.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.013.241-.014.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.049.139-.049.136-.049.131-.051.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.049.023-.025.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.022.01-.023.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.153l-.077.054-.08.054-.083.053-.085.053-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.048-.105.048-.106.048-.109.046-.111.046-.114.046-.115.044-.118.044-.12.043-.122.043-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.034-.143.034-.144.033-.147.032-.148.032-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.024-.161.024-.162.023-.163.023-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.01-.178.01-.179.009-.179.007-.181.006-.182.006-.182.004-.184.003-.184.001-.185.001-.185-.001-.184-.001-.184-.003-.182-.004-.182-.006-.181-.006-.179-.007-.179-.009-.178-.01-.176-.01-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.023-.162-.023-.161-.024-.159-.024-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.032-.146-.032-.145-.033-.143-.034-.141-.034-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.041-.126-.041-.124-.041-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.048-.105-.048-.102-.048-.1-.05-.097-.049-.095-.051-.093-.051-.09-.052-.087-.052-.085-.053-.083-.053-.08-.054-.077-.054v4.153zm8.74-8.179l-.257.004-.254.005-.25.008-.247.011-.244.012-.241.014-.237.016-.233.018-.231.021-.226.022-.224.023-.22.026-.216.027-.212.028-.21.031-.205.032-.202.033-.198.034-.194.036-.191.038-.187.038-.183.04-.179.041-.175.042-.172.043-.168.043-.163.045-.16.046-.155.046-.152.048-.148.048-.143.048-.139.049-.136.05-.131.05-.126.051-.123.051-.118.051-.114.052-.11.052-.106.052-.101.052-.096.052-.092.052-.088.052-.083.052-.079.052-.074.051-.07.052-.065.051-.06.05-.056.05-.051.05-.023.025-.023.024-.021.024-.02.025-.019.024-.018.024-.017.023-.015.024-.014.023-.013.023-.012.023-.01.023-.01.022-.008.022-.006.023-.006.021-.004.022-.004.021-.001.021-.001.021.001.021.001.021.004.021.004.022.006.021.006.023.008.022.01.022.01.023.012.023.013.023.014.023.015.024.017.023.018.024.019.024.02.025.021.024.023.024.023.025.051.05.056.05.06.05.065.051.07.052.074.051.079.052.083.052.088.052.092.052.096.052.101.052.106.052.11.052.114.052.118.051.123.051.126.051.131.05.136.05.139.049.143.048.148.048.152.048.155.046.16.046.163.045.168.043.172.043.175.042.179.041.183.04.187.038.191.038.194.036.198.034.202.033.205.032.21.031.212.028.216.027.22.026.224.023.226.022.231.021.233.018.237.016.241.014.244.012.247.011.25.008.254.005.257.004.26.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.022.224-.023.22-.026.216-.027.212-.028.21-.031.205-.032.202-.033.198-.034.194-.036.191-.038.187-.038.183-.04.179-.041.175-.042.172-.043.168-.043.163-.045.16-.046.155-.046.152-.048.148-.048.143-.048.139-.049.136-.05.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.05.051-.05.023-.025.023-.024.021-.024.02-.025.019-.024.018-.024.017-.023.015-.024.014-.023.013-.023.012-.023.01-.023.01-.022.008-.022.006-.023.006-.021.004-.022.004-.021.001-.021.001-.021-.001-.021-.001-.021-.004-.021-.004-.022-.006-.021-.006-.023-.008-.022-.01-.022-.01-.023-.012-.023-.013-.023-.014-.023-.015-.024-.017-.023-.018-.024-.019-.024-.02-.025-.021-.024-.023-.024-.023-.025-.051-.05-.056-.05-.06-.05-.065-.051-.07-.052-.074-.051-.079-.052-.083-.052-.088-.052-.092-.052-.096-.052-.101-.052-.106-.052-.11-.052-.114-.052-.118-.051-.123-.051-.126-.051-.131-.05-.136-.05-.139-.049-.143-.048-.148-.048-.152-.048-.155-.046-.16-.046-.163-.045-.168-.043-.172-.043-.175-.042-.179-.041-.183-.04-.187-.038-.191-.038-.194-.036-.198-.034-.202-.033-.205-.032-.21-.031-.212-.028-.216-.027-.22-.026-.224-.023-.226-.022-.231-.021-.233-.018-.237-.016-.241-.014-.244-.012-.247-.011-.25-.008-.254-.005-.257-.004-.26-.001-.26.001z\"></path></symbol></defs><defs><symbol id=\"mmd-1-clock\" width=\"24\" height=\"24\"><path transform=\"scale(.5)\" d=\"M12 2c5.514 0 10 4.486 10 10s-4.486 10-10 10-10-4.486-10-10 4.486-10 10-10zm0-2c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm5.848 12.459c.202.038.202.333.001.372-1.907.361-6.045 1.111-6.547 1.111-.719 0-1.301-.582-1.301-1.301 0-.512.77-5.447 1.125-7.445.034-.192.312-.181.343.014l.985 6.238 5.394 1.011z\"></path></symbol></defs><defs><marker id=\"mmd-1-arrowhead\" refX=\"7.9\" refY=\"5\" markerUnits=\"userSpaceOnUse\" markerWidth=\"12\" markerHeight=\"12\" orient=\"auto-start-reverse\"><path d=\"M -1 0 L 10 5 L 0 10 z\"></path></marker></defs><defs><marker id=\"mmd-1-crosshead\" markerWidth=\"15\" markerHeight=\"8\" orient=\"auto\" refX=\"4\" refY=\"4.5\"><path fill=\"none\" stroke=\"#000000\" stroke-width=\"1pt\" d=\"M 1,2 L 6,7 M 6,2 L 1,7\" style=\"stroke-dasharray: 0, 0;\"></path></marker></defs><defs><marker id=\"mmd-1-filled-head\" refX=\"15.5\" refY=\"7\" markerWidth=\"20\" markerHeight=\"28\" orient=\"auto\"><path d=\"M 18,7 L9,13 L14,7 L9,1 Z\"></path></marker></defs><defs><marker id=\"mmd-1-sequencenumber\" refX=\"15\" refY=\"15\" markerWidth=\"60\" markerHeight=\"40\" orient=\"auto\"><circle cx=\"15\" cy=\"15\" r=\"6\"></circle></marker></defs><defs><marker id=\"mmd-1-solidTopArrowHead\" refX=\"7.9\" refY=\"7.25\" markerUnits=\"userSpaceOnUse\" markerWidth=\"12\" markerHeight=\"12\" orient=\"auto-start-reverse\"><path d=\"M 0 0 L 10 8 L 0 8 z\"></path></marker></defs><defs><marker id=\"mmd-1-solidBottomArrowHead\" refX=\"7.9\" refY=\"0.75\" markerUnits=\"userSpaceOnUse\" markerWidth=\"12\" markerHeight=\"12\" orient=\"auto-start-reverse\"><path d=\"M 0 0 L 10 0 L 0 8 z\"></path></marker></defs><defs><marker id=\"mmd-1-stickTopArrowHead\" refX=\"7.5\" refY=\"7\" markerUnits=\"userSpaceOnUse\" markerWidth=\"12\" markerHeight=\"12\" orient=\"auto-start-reverse\"><path d=\"M 0 0 L 7 7\" stroke=\"black\" stroke-width=\"1.5\" fill=\"none\"></path></marker></defs><defs><marker id=\"mmd-1-stickBottomArrowHead\" refX=\"7.5\" refY=\"0\" markerUnits=\"userSpaceOnUse\" markerWidth=\"12\" markerHeight=\"12\" orient=\"auto-start-reverse\"><path d=\"M 0 7 L 7 0\" stroke=\"black\" stroke-width=\"1.5\" fill=\"none\"></path></marker></defs><g data-et=\"note\" data-id=\"i1\"><rect x=\"50\" y=\"121\" fill=\"#EDF2AE\" stroke=\"#666\" width=\"501\" height=\"37\" class=\"note\"></rect><text x=\"301\" y=\"126\" text-anchor=\"middle\" dominant-baseline=\"middle\" alignment-baseline=\"middle\" class=\"noteText\" dy=\"1em\" style=\"font-size: 16px; font-weight: 400;\"><tspan x=\"301\">the calls created two coroutine objects, and gather wrapped each in a task</tspan></text></g><g data-et=\"note\" data-id=\"i6\"><rect x=\"367.5\" y=\"352\" fill=\"#EDF2AE\" stroke=\"#666\" width=\"317\" height=\"37\" class=\"note\"></rect><text x=\"526\" y=\"357\" text-anchor=\"middle\" dominant-baseline=\"middle\" alignment-baseline=\"middle\" class=\"noteText\" dy=\"1em\" style=\"font-size: 16px; font-weight: 400;\"><tspan x=\"526\">both requests are in progress, the thread is idle</tspan></text></g><text x=\"299\" y=\"80\" text-anchor=\"middle\" dominant-baseline=\"middle\" alignment-baseline=\"middle\" class=\"messageText\" dy=\"1em\" style=\"font-size: 16px; font-weight: 400;\">await gather(ask_model_a(prompt), ask_model_b(prompt))</text><line x1=\"76\" y1=\"111\" x2=\"522\" y2=\"111\" class=\"messageLine0\" data-et=\"message\" data-id=\"i0\" data-from=\"P\" data-to=\"L\" stroke-width=\"2\" stroke=\"none\" marker-end=\"url(#mmd-1-arrowhead)\" style=\"fill: none;\"></line><text x=\"727\" y=\"173\" text-anchor=\"middle\" dominant-baseline=\"middle\" alignment-baseline=\"middle\" class=\"messageText\" dy=\"1em\" style=\"font-size: 16px; font-weight: 400;\">A.send(None) — body starts</text><line x1=\"527\" y1=\"204\" x2=\"926\" y2=\"204\" class=\"messageLine0\" data-et=\"message\" data-id=\"i2\" data-from=\"L\" data-to=\"A\" stroke-width=\"2\" stroke=\"none\" marker-end=\"url(#mmd-1-arrowhead)\" style=\"fill: none;\"></line><text x=\"730\" y=\"219\" text-anchor=\"middle\" dominant-baseline=\"middle\" alignment-baseline=\"middle\" class=\"messageText\" dy=\"1em\" style=\"font-size: 16px; font-weight: 400;\">await asyncio.sleep(0.5) — control returns</text><line x1=\"929\" y1=\"250\" x2=\"530\" y2=\"250\" class=\"messageLine1\" data-et=\"message\" data-id=\"i3\" data-from=\"A\" data-to=\"L\" stroke-width=\"2\" stroke=\"none\" marker-end=\"url(#mmd-1-arrowhead)\" style=\"stroke-dasharray: 3, 3; fill: none;\"></line><text x=\"831\" y=\"265\" text-anchor=\"middle\" dominant-baseline=\"middle\" alignment-baseline=\"middle\" class=\"messageText\" dy=\"1em\" style=\"font-size: 16px; font-weight: 400;\">B.send(None) — body starts</text><line x1=\"527\" y1=\"296\" x2=\"1135.5\" y2=\"296\" class=\"messageLine0\" data-et=\"message\" data-id=\"i4\" data-from=\"L\" data-to=\"B\" stroke-width=\"2\" stroke=\"none\" marker-end=\"url(#mmd-1-arrowhead)\" style=\"fill: none;\"></line><text x=\"834\" y=\"311\" text-anchor=\"middle\" dominant-baseline=\"middle\" alignment-baseline=\"middle\" class=\"messageText\" dy=\"1em\" style=\"font-size: 16px; font-weight: 400;\">await asyncio.sleep(0.8) — control returns</text><line x1=\"1138.5\" y1=\"342\" x2=\"530\" y2=\"342\" class=\"messageLine1\" data-et=\"message\" data-id=\"i5\" data-from=\"B\" data-to=\"L\" stroke-width=\"2\" stroke=\"none\" marker-end=\"url(#mmd-1-arrowhead)\" style=\"stroke-dasharray: 3, 3; fill: none;\"></line><text x=\"727\" y=\"404\" text-anchor=\"middle\" dominant-baseline=\"middle\" alignment-baseline=\"middle\" class=\"messageText\" dy=\"1em\" style=\"font-size: 16px; font-weight: 400;\">A.send(None) — after 0.5 s, resumes after the await</text><line x1=\"527\" y1=\"435\" x2=\"926\" y2=\"435\" class=\"messageLine0\" data-et=\"message\" data-id=\"i7\" data-from=\"L\" data-to=\"A\" stroke-width=\"2\" stroke=\"none\" marker-end=\"url(#mmd-1-arrowhead)\" style=\"fill: none;\"></line><text x=\"730\" y=\"450\" text-anchor=\"middle\" dominant-baseline=\"middle\" alignment-baseline=\"middle\" class=\"messageText\" dy=\"1em\" style=\"font-size: 16px; font-weight: 400;\">return \"A: answer to …\" (task A done)</text><line x1=\"929\" y1=\"481\" x2=\"530\" y2=\"481\" class=\"messageLine1\" data-et=\"message\" data-id=\"i8\" data-from=\"A\" data-to=\"L\" stroke-width=\"2\" stroke=\"none\" marker-end=\"url(#mmd-1-arrowhead)\" style=\"stroke-dasharray: 3, 3; fill: none;\"></line><text x=\"831\" y=\"496\" text-anchor=\"middle\" dominant-baseline=\"middle\" alignment-baseline=\"middle\" class=\"messageText\" dy=\"1em\" style=\"font-size: 16px; font-weight: 400;\">B.send(None) — after 0.8 s, resumes after the await</text><line x1=\"527\" y1=\"527\" x2=\"1135.5\" y2=\"527\" class=\"messageLine0\" data-et=\"message\" data-id=\"i9\" data-from=\"L\" data-to=\"B\" stroke-width=\"2\" stroke=\"none\" marker-end=\"url(#mmd-1-arrowhead)\" style=\"fill: none;\"></line><text x=\"834\" y=\"542\" text-anchor=\"middle\" dominant-baseline=\"middle\" alignment-baseline=\"middle\" class=\"messageText\" dy=\"1em\" style=\"font-size: 16px; font-weight: 400;\">return \"B: answer to …\" (task B done)</text><line x1=\"1138.5\" y1=\"573\" x2=\"530\" y2=\"573\" class=\"messageLine1\" data-et=\"message\" data-id=\"i10\" data-from=\"B\" data-to=\"L\" stroke-width=\"2\" stroke=\"none\" marker-end=\"url(#mmd-1-arrowhead)\" style=\"stroke-dasharray: 3, 3; fill: none;\"></line><text x=\"302\" y=\"588\" text-anchor=\"middle\" dominant-baseline=\"middle\" alignment-baseline=\"middle\" class=\"messageText\" dy=\"1em\" style=\"font-size: 16px; font-weight: 400;\">list of both results — ask_both resumes after 0.8 s</text><line x1=\"525\" y1=\"619\" x2=\"79\" y2=\"619\" class=\"messageLine1\" data-et=\"message\" data-id=\"i11\" data-from=\"L\" data-to=\"P\" stroke-width=\"2\" stroke=\"none\" marker-end=\"url(#mmd-1-arrowhead)\" style=\"stroke-dasharray: 3, 3; fill: none;\"></line></svg>\n",
    "</div>\n",
    "\n",
    "The converse does not hold: an `await` switches only when the awaited operation has to wait. An `await` on a coroutine that returns without waiting — one that contains no `await` of its own — continues in the same coroutine, without a switch. Two consequences follow for state that several coroutines share. Between two `await` expressions no other coroutine executes, so a sequence of statements without `await` is never interleaved and needs no lock. Across an `await`, any other coroutine may have changed the shared state, so a value read before the `await` may be out of date after it — the *lost update* that `10-processes-and-threads.ipynb` treats for threads.\n",
    "\n",
    "Awaiting two coroutines one after the other gives no concurrency: each `await` completes before the next line starts. `ask_both_sequential` sends the two requests of the first example in sequence, so their waiting periods add up to 0.5 s + 0.8 s = 1.3 s, against 0.8 s for `ask_both`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "async def ask_both_sequential(prompt: str) -> list[str]:\n",
    "    # the caller awaits each request before it starts the next; the waiting periods do not overlap\n",
    "    answer_a = await ask_model_a(prompt)            # waits 0.5 s\n",
    "    answer_b = await ask_model_b(prompt)            # then waits 0.8 s\n",
    "    return [answer_a, answer_b]\n",
    "\n",
    "\n",
    "start = time.perf_counter()\n",
    "answers = await ask_both_sequential(\"capital of Italy\")\n",
    "print(answers)\n",
    "print(f\"sequential: {time.perf_counter() - start:.2f} s\")  # about 0.5 + 0.8 = 1.3 s, not 0.8 s"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "## Concurrent Execution with `gather`\n",
    "\n",
    "`asyncio.gather(*awaitables) -> Future[list]` wraps every coroutine among the awaitables in a task, which schedules it on the event loop, and returns a future at once; `await` on that future suspends the caller until all awaitables have finished and yields the list of their results.\n",
    "\n",
    "A **future** is an object that *\"represents an eventual result of an asynchronous operation\"* ([Python Software Foundation, 2025, *Futures*](https://docs.python.org/3.14/library/asyncio-future.html#asyncio.Future)). It is created without a result and is marked *done* when its result is set; a coroutine that awaits it is suspended until then, and awaiting it again yields the same result. A task is a future whose result is the return value of its coroutine. `gather` returns an internal subclass of `Future`, `_GatheringFuture` in Python 3.12.3, whose result is set when the last awaitable has finished.\n",
    "\n",
    "The documentation specifies that result: *\"an aggregate list of returned values. The order of result values corresponds to the order of awaitables\"* ([Python Software Foundation, 2023, *Coroutines and Tasks*](https://docs.python.org/3.12/library/asyncio-task.html)) — the order of the arguments, not the order of completion.\n",
    "\n",
    "Three requests to `ask_model`, each waiting 0.3 s, take 0.3 s in total; awaited one after the other, they would take 0.9 s."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "start = time.perf_counter()\n",
    "answers = await asyncio.gather(*(ask_model(f\"question {i}\") for i in range(3)))\n",
    "print(f\"concurrent: {time.perf_counter() - start:.2f} s\")\n",
    "print(answers)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "10",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "The trace shows the interleaving. Each coroutine prints when it starts and when it finishes; all three start before the first one finishes, and the shortest wait finishes first."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "async def traced(name: str, seconds: float) -> str:\n",
    "    print(f\"{name} started\")\n",
    "    await asyncio.sleep(seconds)\n",
    "    print(f\"{name} finished after {seconds} s\")\n",
    "    return name\n",
    "\n",
    "\n",
    "print(await asyncio.gather(traced(\"A\", 0.3), traced(\"B\", 0.1), traced(\"C\", 0.2)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "29",
   "metadata": {},
   "source": [
    "## Asynchronous Context Managers\n",
    "\n",
    "**A context manager is an object that defines an action on entry to a `with` block and an action on exit, where the exit action is executed even when the block raises an exception** (`09-exceptions-and-retries.ipynb`). An **asynchronous** context manager is one whose two actions are coroutines; it is used with `async with`. The methods are `__aenter__` and `__aexit__`.\n",
    "\n",
    "A run of an agent is a resource of this kind: it is opened, used step by step, and has to be closed whatever happens. In PydanticAI, `async with agent.iter(prompt) as run:` opens a run. `contextlib.asynccontextmanager` builds an asynchronous context manager from a coroutine with one `yield`: the code before `yield` is the entry action, the code after it the exit action. A `yield`, not a `return`, is needed because the function has to pause between the two actions while the body of the `async with` block executes: on entry, the context manager advances the generator to the `yield` and binds the yielded value by `as`; on exit, it resumes the generator after the `yield`, or raises the block's exception at the `yield`. The `try`/`finally` around the `yield` therefore executes the exit action also when the block fails. A `return` would end the function at once and leave no place for the exit action."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "30",
   "metadata": {},
   "outputs": [],
   "source": [
    "from contextlib import asynccontextmanager\n",
    "\n",
    "\n",
    "@asynccontextmanager\n",
    "async def model_session(name: str):\n",
    "    print(f\"open connection to {name}\")\n",
    "    await asyncio.sleep(0.05)\n",
    "    try:\n",
    "        yield {\"model\": name}                       # the value bound by `as`\n",
    "    finally:\n",
    "        await asyncio.sleep(0.05)\n",
    "        print(f\"close connection to {name}\")\n",
    "\n",
    "\n",
    "async with model_session(\"qwen2.5:7b\") as session:\n",
    "    print(\"using\", session)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "31",
   "metadata": {},
   "source": [
    "## Asynchronous Iterators\n",
    "\n",
    "**An asynchronous iterator is an object that produces a sequence of values, where the production of each value may wait.** It is consumed with `async for`. The simplest way to write one is an **asynchronous generator**: an `async def` function that contains `yield`. Each `yield` delivers one value to the loop and suspends the generator until the next value is requested.\n",
    "\n",
    "Agent code iterates asynchronously over the tokens of a reply and over the steps of a run. A model reply is **streamed**: the tokens arrive one at a time and are displayed as they arrive. A run is executed **step by step**: `async for node in run:` yields the nodes of the agent's graph one at a time, so that the caller can inspect each node, count it, or stop."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "32",
   "metadata": {},
   "outputs": [],
   "source": [
    "async def stream_reply(text: str):\n",
    "    for token in text.split():\n",
    "        await asyncio.sleep(0.3)                   # the next token arrives\n",
    "        yield token\n",
    "\n",
    "\n",
    "async for token in stream_reply(\"The capital of Italy is Rome.\"):\n",
    "    print(token, end=\" \", flush=True)\n",
    "print()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "33",
   "metadata": {},
   "source": [
    "The last cell combines both constructs into the shape of `agent.iter`: a context manager that opens a run and yields an object over which the caller iterates. The caller's loop is the place where a bound on the number of steps or a request for approval is written.\n",
    "\n",
    "With a bound of three steps, the caller stops the run at the fourth node. The exit action of the context manager is executed nonetheless, and `run.result` keeps the value `None`, because the iteration did not reach `End`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "34",
   "metadata": {},
   "outputs": [],
   "source": [
    "class Run:\n",
    "    def __init__(self, steps):\n",
    "        self.steps, self.result = steps, None\n",
    "\n",
    "    async def __aiter__(self):                      # an asynchronous generator as the iterator\n",
    "        for step in self.steps:\n",
    "            await asyncio.sleep(0.05)\n",
    "            yield step\n",
    "        self.result = \"final answer\"\n",
    "\n",
    "\n",
    "@asynccontextmanager\n",
    "async def iter_run(prompt: str):\n",
    "    run = Run([\"UserPromptNode\", \"ModelRequestNode\", \"CallToolsNode\", \"ModelRequestNode\", \"End\"])\n",
    "    try:\n",
    "        yield run\n",
    "    finally:\n",
    "        print(\"run closed\")\n",
    "\n",
    "\n",
    "step_limit = 3\n",
    "try:\n",
    "    async with iter_run(\"Put my money on square eighteen\") as run:\n",
    "        n = 0\n",
    "        async for node in run:\n",
    "            n += 1\n",
    "            if n > step_limit:\n",
    "                raise RuntimeError(f\"step limit of {step_limit} exceeded\")\n",
    "            print(f\"step {n}: {node}\")\n",
    "except RuntimeError as error:\n",
    "    print(\"stopped:\", error)\n",
    "print(\"result:\", run.result)                        # None: the run did not reach End"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "anext-0",
   "metadata": {},
   "source": [
    "## Manual Iteration with `anext`\n",
    "\n",
    "**`await anext(it)` executes one step of an asynchronous iterator: it returns the next value, or raises the exception that the step raised.** `anext` (Python ≥ 3.10) is the asynchronous counterpart of `next`: it calls the iterator's method `__anext__` and awaits the result. With a second argument, `anext(it, default)` returns `default` instead of raising `StopAsyncIteration` when the iterator is exhausted ([Python Software Foundation, 2023, *Built-in Functions*](https://docs.python.org/3.12/library/functions.html#anext)).\n",
    "\n",
    "`async for` is defined by this step. PEP 492 specifies `async for x in it: body` as *\"semantically equivalent to\"* a `while` loop that awaits `__anext__` inside a `try` whose only handler catches `StopAsyncIteration` ([Selivanov, 2015](https://peps.python.org/pep-0492/#asynchronous-iterators-and-async-for)). In simplified form:\n",
    "\n",
    "```python\n",
    "it = aiter(ITER)\n",
    "while True:\n",
    "    try:\n",
    "        x = await anext(it)\n",
    "    except StopAsyncIteration:\n",
    "        break\n",
    "    body\n",
    "```\n",
    "\n",
    "Every other exception raised by a step therefore leaves the `async for` statement. A caller that has to **catch a failed step and continue the iteration** — a run of a plan graph in which a failed tool call is replaced by another — writes this loop itself: `await anext(run)` inside `try`, a handler for the failure, and `continue`.\n",
    "\n",
    "**The iterator must survive the exception.** An exception that leaves an asynchronous generator ends the generator: the next `anext` raises `StopAsyncIteration`. The documentation states this end explicitly for `aclose()` and for a normal exit ([Python Software Foundation, 2023, *Expressions*](https://docs.python.org/3.12/reference/expressions.html#asynchronous-generator-iterator-methods)); for a raised exception, the cell below shows it (Python 3.12.3)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "anext-1",
   "metadata": {},
   "outputs": [],
   "source": [
    "async def steps():\n",
    "    yield \"search(acme)\"\n",
    "    raise ConnectionError(\"search: source unavailable for 'globex'\")\n",
    "    yield \"calculator(#E1 + #E2)\"                   # never reached\n",
    "\n",
    "\n",
    "it = steps()\n",
    "print(await anext(it))\n",
    "try:\n",
    "    await anext(it)\n",
    "except ConnectionError as error:\n",
    "    print(\"caught:\", error)\n",
    "print(await anext(it, \"exhausted\"))                 # the generator has ended"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "anext-2",
   "metadata": {},
   "source": [
    "An iterator that can be continued after a failure is therefore a class with its own `__anext__`: the object keeps the state of the run between two calls, and a failed step is reported by raising its exception, after which the next call continues. `PlanRun` below executes a list of plan steps; `override_next` is the caller's repair, a new step placed before the remaining ones.\n",
    "\n",
    "pydantic-graph has the same structure: its `GraphRun` is a class with `__anext__`, and the generator that executes the graph inside it **yields** a failed step as a value (an `ErrorMarker`) instead of raising. `GraphRun.__anext__` raises the step's exception to the caller; the inner generator stays suspended, and after `run.override_next(...)` the next `anext(run)` continues the run (pydantic-graph 2.54.0, [`graph_builder.py`](https://github.com/pydantic/pydantic-ai/blob/v2.54.0/pydantic_graph/pydantic_graph/graph_builder.py))."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "anext-3",
   "metadata": {},
   "outputs": [],
   "source": [
    "class PlanRun:\n",
    "    \"\"\"A run over plan steps; a failed step is raised to the caller, who may replace it.\"\"\"\n",
    "\n",
    "    def __init__(self, steps: list[str], down: set[str]):\n",
    "        self.queue, self.down, self.done = list(steps), down, []\n",
    "\n",
    "    def __aiter__(self):\n",
    "        return self\n",
    "\n",
    "    async def __anext__(self) -> str:\n",
    "        if not self.queue:\n",
    "            raise StopAsyncIteration\n",
    "        step = self.queue.pop(0)\n",
    "        await asyncio.sleep(0.05)                   # the tool call\n",
    "        if step in self.down:\n",
    "            raise ConnectionError(f\"{step}: source unavailable\")\n",
    "        self.done.append(step)\n",
    "        return step\n",
    "\n",
    "    def override_next(self, step: str) -> None:\n",
    "        self.queue.insert(0, step)                  # the repair: a new step before the remaining ones\n",
    "\n",
    "\n",
    "run = PlanRun([\"search(acme)\", \"search(globex)\", \"calculator(#E1 + #E2)\"], down={\"search(globex)\"})\n",
    "while True:\n",
    "    try:\n",
    "        step = await anext(run)\n",
    "    except StopAsyncIteration:\n",
    "        break\n",
    "    except ConnectionError as error:                # the run reports the failure\n",
    "        print(\"failure:\", error)\n",
    "        run.override_next(\"search_archive(globex)\") # the caller repairs\n",
    "        continue\n",
    "    print(\"done:\", step)\n",
    "print(run.done)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "35",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "| Written | Meaning |\n",
    "|---|---|\n",
    "| `async def f(): …` | a coroutine function; `f()` returns a coroutine object and executes nothing |\n",
    "| `await x` | execute `x`; the surrounding coroutine is suspended until `x` has a result |\n",
    "| `asyncio.run(main())` | entry point of a script; not usable in a notebook, where `await` is written at the top level |\n",
    "| `await asyncio.gather(a, b, c)` | concurrent execution; results in the order of the arguments |\n",
    "| `async with cm as x`, `async for x in it` | context manager and iterator whose steps may wait |\n",
    "| `await anext(it)`, `anext(it, default)` | one step of an asynchronous iterator; its exception reaches the caller, who may continue |\n",
    "\n",
    "Tasks, cancellation, `TaskGroup`, time limits, `to_thread` and semaphores: `08b-async-tasks-and-cancellation.ipynb`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "36",
   "metadata": {},
   "source": [
    "## Tasks\n",
    "\n",
    "**Task 1.** Write `ask_all(prompts)`, which sends all prompts concurrently with `ask_model` and returns a dictionary from prompt to answer. Measure the duration for five prompts.\n",
    "\n",
    "**Task 2.** Write `collect(run)`, which iterates over an asynchronous iterator with `await anext(run)` and returns two lists: the values of the steps and the messages of the exceptions raised by failed steps. A failure does not end the iteration; `StopAsyncIteration` does. Apply `collect` to a `PlanRun` with one unavailable source, without repair, and to the generator `steps()` from the section [*Manual Iteration with `anext`*](#Manual-Iteration-with-anext). Explain why the second result contains no value after the failure."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "37",
   "metadata": {},
   "source": [
    "### Solutions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "38",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Task 1\n",
    "async def ask_all(prompts: list[str]) -> dict[str, str]:\n",
    "    answers = await asyncio.gather(*(ask_model(p, seconds=0.2) for p in prompts))\n",
    "    return dict(zip(prompts, answers))\n",
    "\n",
    "\n",
    "start = time.perf_counter()\n",
    "result = await ask_all([f\"question {i}\" for i in range(5)])\n",
    "print(len(result), f\"answers in {time.perf_counter() - start:.2f} s\")\n",
    "\n",
    "\n",
    "# Task 2\n",
    "async def collect(run) -> tuple[list[str], list[str]]:\n",
    "    values, failures = [], []\n",
    "    while True:\n",
    "        try:\n",
    "            values.append(await anext(run))\n",
    "        except StopAsyncIteration:\n",
    "            return values, failures\n",
    "        except Exception as error:                  # a failed step: record it and continue\n",
    "            failures.append(str(error))\n",
    "\n",
    "\n",
    "print(await collect(PlanRun([\"search(acme)\", \"search(globex)\", \"calculator(#E1 + #E2)\"], down={\"search(globex)\"})))\n",
    "print(await collect(steps()))\n",
    "# steps() is an asynchronous generator: the exception ended it, so the next anext raises StopAsyncIteration\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "39",
   "metadata": {},
   "source": [
    "## References\n",
    "\n",
    "- Pydantic. \"graph_builder.py.\" pydantic-ai repository, pydantic-graph 2.54.0. 2026. <https://github.com/pydantic/pydantic-ai/blob/v2.54.0/pydantic_graph/pydantic_graph/graph_builder.py>\n",
    "- Python Software Foundation. \"Built-in Functions.\" Python 3.12 documentation. 2023. <https://docs.python.org/3.12/library/functions.html>\n",
    "- Python Software Foundation. \"Coroutines and Tasks.\" Python 3.12 documentation. 2023. <https://docs.python.org/3.12/library/asyncio-task.html>\n",
    "- Python Software Foundation. \"Expressions.\" Python 3.12 documentation. 2023. <https://docs.python.org/3.12/reference/expressions.html>\n",
    "- Python Software Foundation. \"Futures.\" Python 3.14 documentation. 2025. <https://docs.python.org/3.14/library/asyncio-future.html>\n",
    "- Python Software Foundation. \"Glossary.\" Python 3.12 documentation. 2023. <https://docs.python.org/3.12/glossary.html>\n",
    "- Selivanov, Yury. \"PEP 492 – Coroutines with async and await syntax.\" Python Enhancement Proposals. 2015. <https://peps.python.org/pep-0492/>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.15",
   "language": "python",
   "name": "py315"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.15.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}