{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "02fa325c",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "# Lab\n",
    "\n",
    "**Agentic AI** · `L-Decomp`\n",
    "\n",
    "*Pydantic AI and its graph library introduced step by step; then ReWOO's planner, worker and solver on a typed plan, the plan compiled into a graph as in LLMCompiler, and a replanning loop around them.*\n",
    "\n",
    "**Five tutorials.** The first three introduce the parts of Pydantic AI and of its\n",
    "graph library pydantic-graph that the later ones use. The fourth applies them to ReWOO with a typed\n",
    "plan, which a program checks and compiles into a graph, on the revenue plan of the lecture's ReWOO and LLMCompiler examples, extended to three companies\n",
    "and the share of one; the fifth adds replanning on a failed step. Every cell is complete and is executed in order, and each\n",
    "tutorial closes with questions on what its code does and what its output shows. All tool functions are\n",
    "local and deterministic, so the runs are reproducible up to the model's sampling.\n",
    "\n",
    "**Prerequisite: coroutines and `asyncio`.** Pydantic AI and pydantic-graph are asynchronous libraries: the tutorials write `async def`, `await`, `async with` and `async for`, and [*Stepping Through a Run*](#Tutorial:-Stepping-Through-a-Run) advances a run step by step with `await anext(run)`. The Python basics notebook [*Coroutines and asyncio*](http://christianherta.de/lehre/ai-agents/playground/python/08-async-coroutines.ipynb) explains these constructs and is read before the lab."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "32d3e731",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## Setup\n",
    "\n",
    "**The lab runs on the local Ollama server**, installed as described in the lab of\n",
    "[→ L-Intro](../lecture-Intro/lecture-Intro.html), and on Pydantic AI with its graph library. Start the\n",
    "server in each session and install once:\n",
    "\n",
    "```bash\n",
    "ollama serve &\n",
    "ollama pull qwen2.5:3b\n",
    "ollama pull qwen3.5:9b      # the planner of the ReWOO tutorial\n",
    "pip install \"pydantic-ai-slim[openai]\" pydantic-graph\n",
    "```\n",
    "\n",
    "**Pydantic AI is a Python library that wraps the calls of a language model.** Its class `Agent` implements the **runtime** of an agent, every part that is neither the model nor\n",
    "the inference engine (here the Ollama server): it holds the instructions, the tools and the type of\n",
    "the expected output, and `await agent.run(prompt)` executes the agent loop of\n",
    "[→ L-ReAct](../lecture-ReAct/lecture-ReAct.html). Each step sends the whole history and the tool\n",
    "schemas to the model, executes the tool calls of the reply and appends their results to the history.\n",
    "The run ends when a reply passes validation against the output type; a run that would exceed 50 model\n",
    "requests, the default limit, raises `UsageLimitExceeded` ([Pydantic, 2026a](https://pydantic.dev/docs/ai/core-concepts/agent/);\n",
    "[Pydantic, 2026g](https://github.com/pydantic/pydantic-ai/blob/v2.54.0/pydantic_ai_slim/pydantic_ai/messages.py)). The documentation describes\n",
    "the library as *\"a typed, extensible agent loop with every model a string swap away\"*\n",
    "([Pydantic, 2026e](https://pydantic.dev/docs/ai/overview/)). **pydantic-graph** is the graph library of Pydantic AI: it executes a\n",
    "graph of steps and runs independent steps concurrently ([Pydantic, 2026b](https://pydantic.dev/docs/ai/graph/builder/)). Pydantic AI sends\n",
    "its requests to the same Ollama server as the earlier labs; pydantic-graph calls no model and runs in\n",
    "the Python process. The request, the validation of the reply and the scheduling of the steps are\n",
    "written by the libraries instead of by hand."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "41781196",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "source": [
    "**Coroutines and `await`.** Both libraries are asynchronous. A function defined with `async def` is a\n",
    "**coroutine function**: calling it returns a coroutine, and `await` executes the coroutine until it\n",
    "returns. While a coroutine waits, for a model reply or in `await asyncio.sleep(t)`, the **event loop**\n",
    "executes other coroutines; `time.sleep(t)` would block all of them. The event loop is the scheduler of\n",
    "`asyncio`: it runs the coroutines of one thread and resumes a waiting coroutine when its result has\n",
    "arrived ([Python Software Foundation, 2025](https://docs.python.org/3.14/library/asyncio-eventloop.html)). Jupyter runs an event loop, so a\n",
    "cell may contain `await` at its top level. A Python script wraps the same code in `async def main()` and\n",
    "starts it with `asyncio.run(main())`. The synchronous variant `agent.run_sync(...)` raises a\n",
    "`RuntimeError` inside Jupyter, because an event loop is already running there.\n",
    "\n",
    "The setup cell defines the model and the three tool functions `search`, `search_archive` and\n",
    "`calculator`. No agent registers them as tools: the Worker and the steps of the graphs call them as\n",
    "plain Python functions. The models write plans, choose a replacement step and compose the\n",
    "answer, and never call a tool. The tool functions work on a **fixture**, a small table of invented\n",
    "revenue figures, so that every run sees the same data. `search` raises a `ConnectionError` for every\n",
    "company in the set `OUTAGE`, which the replanning tutorial fills; `search_archive` reads a second\n",
    "table with the same content."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "09ce2778",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "import os, re, ast, operator, time, asyncio\n",
    "os.environ[\"PYDANTIC_AI_NO_BANNER\"] = \"1\"                 # no start-up banner\n",
    "\n",
    "from typing import Literal\n",
    "from pydantic import BaseModel, Field\n",
    "from pydantic_ai import Agent, ModelRetry, NativeOutput, capture_run_messages\n",
    "from pydantic_ai.exceptions import UnexpectedModelBehavior\n",
    "from pydantic_ai.models.ollama import OllamaModel\n",
    "from pydantic_ai.providers.ollama import OllamaProvider\n",
    "from IPython.display import Markdown, display\n",
    "from pydantic_graph import EndMarker, GraphBuilder, GraphTaskRequest, StepContext, reduce_list_append\n",
    "\n",
    "MODEL = OllamaModel(\"qwen2.5:3b\", provider=OllamaProvider(base_url=\"http://localhost:11434/v1\"))\n",
    "\n",
    "# --- the tools: a fixture, not real data -------------------------------------\n",
    "FACTS = {                                   # key words -> value (million EUR, fiscal year 2024)\n",
    "    (\"revenue\", \"acme\"):    \"120.5\",\n",
    "    (\"revenue\", \"globex\"):  \"80.25\",\n",
    "    (\"revenue\", \"initech\"): \"45.0\",\n",
    "}\n",
    "ARCHIVE = dict(FACTS)                       # a second source with the same content\n",
    "OUTAGE = set()                              # company names for which `search` raises\n",
    "\n",
    "def _lookup(table, query):\n",
    "    words = set(re.findall(r\"[a-z0-9]+\", query.lower()))\n",
    "    for key, value in table.items():\n",
    "        if set(key) <= words:\n",
    "            return value\n",
    "    return \"No evidence found.\"\n",
    "\n",
    "def search(query):\n",
    "    hit = [c for c in OUTAGE if c in query.lower()]\n",
    "    if hit:\n",
    "        raise ConnectionError(f\"search: source unavailable for {hit[0]!r}\")\n",
    "    return _lookup(FACTS, query)\n",
    "\n",
    "def search_archive(query):\n",
    "    return _lookup(ARCHIVE, query)\n",
    "\n",
    "_OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,\n",
    "        ast.Div: operator.truediv, ast.USub: operator.neg}\n",
    "\n",
    "def calculator(expr):\n",
    "    \"\"\"Evaluate + - * / and parentheses on numbers; anything else raises ValueError or SyntaxError.\"\"\"\n",
    "    def ev(n):\n",
    "        if isinstance(n, ast.Constant) and isinstance(n.value, (int, float)):\n",
    "            return n.value\n",
    "        if isinstance(n, ast.BinOp) and type(n.op) in _OPS:\n",
    "            return _OPS[type(n.op)](ev(n.left), ev(n.right))\n",
    "        if isinstance(n, ast.UnaryOp) and type(n.op) in _OPS:\n",
    "            return _OPS[type(n.op)](ev(n.operand))\n",
    "        raise ValueError(f\"calculator: cannot evaluate {expr!r}\")\n",
    "    return str(round(ev(ast.parse(expr, mode=\"eval\").body), 4))\n",
    "\n",
    "def show_graph(graph):\n",
    "    \"\"\"Display a pydantic-graph graph as a Mermaid state diagram (drawn by JupyterLab 4.1 or later).\"\"\"\n",
    "    display(Markdown(f\"```mermaid\\n{graph.render(direction='LR')}\\n```\"))\n",
    "\n",
    "print(\"setup ok\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "41216d28",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## Tutorial: An Agent with a Typed Output\n",
    "\n",
    "**An `Agent` of Pydantic AI holds a default model, instructions and an output type; `await agent.run(prompt)`\n",
    "sends the prompt and returns a result object with the validated output and the usage of the run**\n",
    "([Pydantic, 2026a](https://pydantic.dev/docs/ai/core-concepts/agent/)). An\n",
    "`Agent` without tools makes one model request per run, plus one per retry: it is a typed model call,\n",
    "and the loop of tool calls begins only when tools are registered. With an output type other than `str`,\n",
    "the reply must be a JSON object that matches the schema of the type. `NativeOutput` passes the schema\n",
    "to the structured-output feature of the model ([Pydantic, 2026d](https://pydantic.dev/docs/ai/core-concepts/output/)); a local Ollama server then\n",
    "generates the reply with a grammar-constrained decoder, which produces only text that matches the\n",
    "schema ([Pydantic, 2026c](https://pydantic.dev/docs/ai/models/ollama/)). If a reply still fails validation, the\n",
    "validation error is sent back to the model as a retry request. The default allows one output retry; a\n",
    "second invalid reply raises `UnexpectedModelBehavior`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15eb8daf",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# An Agent without tools and with the default output type str: one model request per run.\n",
    "helper = Agent(MODEL, instructions=\"Answer in one sentence.\")\n",
    "result = await helper.run(\"What does the scheduler of a plan do?\")\n",
    "print(result.output)                 # the reply text\n",
    "print(result.usage)                  # requests and tokens of the whole run"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "59b854c4",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# A typed output: the reply must be a Replacement, and `tool` may take only the two names of the Literal.\n",
    "class Replacement(BaseModel):\n",
    "    tool: Literal[\"search\", \"search_archive\"]\n",
    "    reason: str\n",
    "\n",
    "SYS_CHOOSE = (\"A step of a plan failed. From its failure report, choose the tool for a replacement step: \"\n",
    "              \"search, or search_archive (a second source with the same data).\")\n",
    "tool_chooser = Agent(MODEL, output_type=NativeOutput(Replacement), instructions=SYS_CHOOSE)\n",
    "\n",
    "FAILED = (\"Failed step: search(revenue globex). \"\n",
    "          \"Report: ConnectionError: search: source unavailable for 'globex'\")\n",
    "r = await tool_chooser.run(FAILED)\n",
    "print(repr(r.output))                # a Replacement object, not text\n",
    "print(r.output.tool, \"|\", r.usage.requests, \"request(s)\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "40f22074",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# What the run sent and received: one entry per request and per response.\n",
    "def show_messages(messages):\n",
    "    for m in messages:\n",
    "        for p in m.parts:\n",
    "            print(f\"{type(m).__name__:<14} {type(p).__name__:<16} {str(getattr(p, 'content', ''))[:120]}\")\n",
    "\n",
    "show_messages(r.all_messages())\n",
    "print(\"instructions of the request:\", r.all_messages()[0].instructions)\n",
    "# Plain Pydantic, independent of the run and of the LLM: the JSON Schema of the class Replacement.\n",
    "# Pydantic adds entries the class does not state: a 'title' per field and for the class (from the\n",
    "# names), 'enum' for the Literal, and 'required' for every field without a default.\n",
    "# NativeOutput derives the schema it sends from this; the request itself is not in the history.\n",
    "print(\"JSON Schema of Replacement (Pydantic):\", Replacement.model_json_schema())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5c202890",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "source": [
    "**Pydantic AI stores the history of a run by direction: a `ModelRequest` holds what the library sends\n",
    "to the model, a `ModelResponse` what the model returns, and each holds a list of typed parts.** The\n",
    "history of [→ L-ReAct](../lecture-ReAct/lecture-ReAct.html#Message-Types-%28what-the-loop-stores%29)\n",
    "holds the same content as messages tagged by role. At every call the **adapter**, the part of the\n",
    "library that builds the request for one provider API, converts the parts into such messages. For the\n",
    "Ollama model of this lab it is the adapter of the OpenAI Chat Completions API, which Ollama also\n",
    "accepts ([Pydantic, 2026g](https://github.com/pydantic/pydantic-ai/blob/v2.54.0/pydantic_ai_slim/pydantic_ai/messages.py)):\n",
    "\n",
    "| Role in the API | Type in `L-ReAct` | Pydantic AI | Held by |\n",
    "|---|---|---|---|\n",
    "| `system` | system prompt | `instructions`, a field of the request; `SystemPromptPart` | `ModelRequest` |\n",
    "| `user` | `UserMessage` | `UserPromptPart` | `ModelRequest` |\n",
    "| `tool` | `ToolResultMessage` | `ToolReturnPart`, with the `tool_call_id` of the call | `ModelRequest` |\n",
    "| `user`, or `tool` after a tool call | — | `RetryPromptPart`, the reason for a retry | `ModelRequest` |\n",
    "| `assistant`, `content` | `AssistantMessage`, text | `TextPart` | `ModelResponse` |\n",
    "| `assistant`, `tool_calls` | `AssistantMessage`, `tool_calls` | `ToolCallPart`, one per call | `ModelResponse` |\n",
    "| a field of the provider | — | `ThinkingPart`, reasoning text that the model returns separately | `ModelResponse` |\n",
    "\n",
    "One `ModelResponse` becomes one `assistant` message. One `ModelRequest` can become several messages:\n",
    "after two tool calls it holds two `ToolReturnPart`s, which are sent as two `tool` messages. With\n",
    "`NativeOutput` the reply is a `TextPart` whose content is the JSON object. A `RetryPromptPart`\n",
    "without a tool call is sent as the message of the rejection between the line `Validation feedback:` and\n",
    "the line `Fix the errors and try again.`; a reply that fails the schema is sent as the list of its\n",
    "validation errors in JSON instead (Pydantic, 2026g)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "54023bec",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "source": [
    "**An output validator is a function that the agent applies to every output that has passed the schema;\n",
    "raising `ModelRetry` rejects the output and sends its message to the model as a retry request.** The\n",
    "schema states the types and the permitted values of the fields. A rule about the content of a field, or\n",
    "about the relation between several fields or several list items, is checked by such a function\n",
    "([Pydantic, 2026d](https://pydantic.dev/docs/ai/core-concepts/output/)). A rejection uses the same budget\n",
    "as a schema failure: `Agent(..., retries=n)` permits $n$ output retries, by default one, and the run\n",
    "raises `UnexpectedModelBehavior` when they are exhausted ([Pydantic, 2026a](https://pydantic.dev/docs/ai/core-concepts/agent/)). A run\n",
    "that raises returns no result, and the exception carries no messages; `with capture_run_messages() as\n",
    "messages:` records the messages of the run as it proceeds, so that the history of a failed run can\n",
    "still be read (Pydantic, 2026a)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5dcfd9cf",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# An output validator: a rule of one's own after the schema check - here a reason of at most six words.\n",
    "terse = Agent(MODEL, output_type=NativeOutput(Replacement), instructions=SYS_CHOOSE, retries=2)\n",
    "\n",
    "@terse.output_validator\n",
    "def short_reason(out: Replacement) -> Replacement:\n",
    "    n = len(out.reason.split())\n",
    "    if n > 6:\n",
    "        raise ModelRetry(f\"The reason has {n} words; give it in at most 6 words.\")\n",
    "    return out\n",
    "\n",
    "r2 = await terse.run(FAILED)\n",
    "print(repr(r2.output.reason), \"|\", r2.usage.requests, \"request(s)\")\n",
    "show_messages(r2.all_messages())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "895b7e5c",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# A run that fails: the validator rejects every output, so the retry budget is exhausted.\n",
    "strict = Agent(MODEL, output_type=NativeOutput(Replacement), instructions=SYS_CHOOSE, retries=1)\n",
    "\n",
    "@strict.output_validator\n",
    "def never(out: Replacement) -> Replacement:\n",
    "    raise ModelRetry(\"Rejected.\")\n",
    "\n",
    "with capture_run_messages() as messages:     # filled while the run proceeds\n",
    "    try:\n",
    "        await strict.run(FAILED)\n",
    "    except UnexpectedModelBehavior as e:\n",
    "        print(\"raised:\", e)\n",
    "show_messages(messages)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e55df65",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "source": [
    "**Questions.**\n",
    "\n",
    "1. How many model requests did each of the two runs make, and what is the type of `r.output`?\n",
    "2. The reply of the model is text. Where does it become a `Replacement` object, and what prevents the\n",
    "   model from naming a tool outside the `Literal`?\n",
    "3. What happens in a run whose reply does not match the schema, and what does the caller receive when\n",
    "   the retries are exhausted?\n",
    "4. How many requests did the run of `terse` make, and which part of the message history carries the\n",
    "   rejection? Which rule could the schema itself not state?\n",
    "5. The run of `strict` raises. How many requests did it make, and what does the captured history\n",
    "   show that the exception does not?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "04797c29",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## Tutorial: A Graph of Steps\n",
    "\n",
    "**A graph of pydantic-graph is a set of steps connected by edges and executed from a start node to an\n",
    "end node; a step is an `async` function, and the value it returns is the input of the steps that its\n",
    "edges lead to.** The tutorial executes the scheduling concepts of the lecture with a library. The\n",
    "graph is the plan DAG of *The Plan as a DAG*: a step is a sub-task, an edge a dependency. A fork and a\n",
    "join are the fan-out and the fan-in of *Flow Patterns & Their Failure Modes*; a run dispatches the\n",
    "ready set of *Topological Order & the Ready Set*, and its wall-clock time is bounded below by the\n",
    "makespan of *Parallelism & the Critical Path*. The table in *Scheduling and Flow Patterns in a\n",
    "Framework* lists the full correspondence. The builder API is used in three stages ([Pydantic, 2026b](https://pydantic.dev/docs/ai/graph/builder/)):\n",
    "\n",
    "1. `g = GraphBuilder(input_type=…, output_type=…)` fixes the type of the input and of the output of a\n",
    "   run.\n",
    "2. `@g.step` registers a step. The step receives a `StepContext`, whose field `ctx.inputs` holds the\n",
    "   input of this execution of the step. The three type parameters of `StepContext[None, None, X]` are\n",
    "   the state, the dependencies and the input type; this lab uses neither state nor dependencies.\n",
    "3. `g.add(g.edge_from(a).to(b), …)` adds edges, starting at `g.start_node` and ending at `g.end_node`.\n",
    "   `g.build()` checks the graph and returns a `Graph`, which `await graph.run(inputs=…)` executes.\n",
    "   `graph.render()` returns the graph as the source text of a Mermaid state diagram; the helper\n",
    "   `show_graph` of the setup cell displays this text as a figure, in which `[*]` marks the start and\n",
    "   the end node."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d751616a",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# A linear graph: start -> add_up -> halve -> end.\n",
    "g = GraphBuilder(input_type=list[float], output_type=float)\n",
    "\n",
    "@g.step\n",
    "async def add_up(ctx: StepContext[None, None, list[float]]) -> float:\n",
    "    return sum(ctx.inputs)\n",
    "\n",
    "@g.step\n",
    "async def halve(ctx: StepContext[None, None, float]) -> float:\n",
    "    return ctx.inputs / 2\n",
    "\n",
    "g.add(g.edge_from(g.start_node).to(add_up),\n",
    "      g.edge_from(add_up).to(halve),\n",
    "      g.edge_from(halve).to(g.end_node))\n",
    "linear = g.build()\n",
    "\n",
    "print(await linear.run(inputs=[1.0, 2.0, 3.0]))\n",
    "show_graph(linear)                   # the graph as a Mermaid state diagram"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ae296a70",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "source": [
    "**A fork starts several tasks from one value; a join waits for all of them and combines their\n",
    "results.** A **task** is one execution of a step on one input. The mapping edge\n",
    "`g.add_mapping_edge(g.start_node, slow_square)` takes the input of the run, a list of numbers, and\n",
    "starts one task of `slow_square` per item, the *spread* form of a fork; a mapping edge requires the\n",
    "output of its source to be an iterable. The join `gather = g.join(reduce_list_append, initial_factory=list)`\n",
    "starts from an empty list, appends the result of each task in the order in which the tasks finish, and\n",
    "passes the list on once every task of its fork has finished ([Pydantic, 2026f](https://pydantic.dev/docs/ai/graph/builder/parallel/)).\n",
    "A join is a node like a step and is connected by ordinary edges, here `slow_square` → `gather` →\n",
    "`add_squares`. In the figure of `show_graph`, the fork and the join are drawn as black bars without a\n",
    "label; the Mermaid source names the fork `map` and the join after its reducer, `reduce_list_append`,\n",
    "not after the variable `gather`. The tasks of a fork run concurrently: while one task awaits `asyncio.sleep`, the others\n",
    "proceed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e603d2b9",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# A fork over the items of the input, a join, and one step after the join.\n",
    "DELAY = {1: 0.3, 2: 0.6, 3: 0.9}                   # seconds per item\n",
    "\n",
    "g = GraphBuilder(input_type=list[int], output_type=int)\n",
    "\n",
    "@g.step\n",
    "async def slow_square(ctx: StepContext[None, None, int]) -> int:\n",
    "    await asyncio.sleep(DELAY[ctx.inputs])         # stands for a slow tool call\n",
    "    return ctx.inputs ** 2\n",
    "\n",
    "gather = g.join(reduce_list_append, initial_factory=list)\n",
    "\n",
    "@g.step\n",
    "async def add_squares(ctx: StepContext[None, None, list[int]]) -> int:\n",
    "    print(\"the join delivers\", ctx.inputs)\n",
    "    return sum(ctx.inputs)\n",
    "\n",
    "g.add_mapping_edge(g.start_node, slow_square)      # the fork: one task per item of the input\n",
    "g.add(g.edge_from(slow_square).to(gather),\n",
    "      g.edge_from(gather).to(add_squares),\n",
    "      g.edge_from(add_squares).to(g.end_node))\n",
    "squares = g.build()\n",
    "\n",
    "await squares.run(inputs=[3, 1, 2])                # not timed: includes a one-off start-up cost\n",
    "t0 = time.perf_counter()\n",
    "out = await squares.run(inputs=[3, 1, 2])\n",
    "print(f\"output {out}, wall-clock time {time.perf_counter() - t0:.2f}s, \"\n",
    "      f\"sum of the delays {sum(DELAY.values()):.2f}s\")\n",
    "show_graph(squares)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "40dc03b2",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "source": [
    "**Questions.**\n",
    "\n",
    "1. The wall-clock time is about 0.9 s, the sum of the delays 1.8 s. Which quantity of the lecture is\n",
    "   the 0.9 s, and how long would a sequential execution take?\n",
    "2. The input is `[3, 1, 2]`. In which order does the join deliver the squares, and why does the output\n",
    "   not depend on that order here? For which combination of the results would the order matter?\n",
    "3. Which concept of *The Plan as a DAG* and *Topological Order & the Ready Set* corresponds to the\n",
    "   mapping edge, to the join and to the run itself?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e42585f4",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## Tutorial: Stepping Through a Run\n",
    "\n",
    "**`await graph.run(inputs=…)` executes a run to its end and returns only the output; the caller sees\n",
    "nothing of the run in between and cannot act on a failed step.** In the pydantic-graph (2.54.0),\n",
    "`graph.run` opens the run with `graph.iter` and advances it until the end node is reached. Called directly, `graph.iter`\n",
    "returns the run to the caller, who then controls when it advances.\n",
    "\n",
    "**`graph.iter(inputs=…)` opens a run, a `GraphRun` object, which the caller advances one event at a\n",
    "time; an event is the list of tasks that have just become ready, and the last event is an `EndMarker`\n",
    "that carries the output.** The first event holds the task of the start node. Each `await anext(run)` lets the run execute until a task finishes and returns\n",
    "the tasks that this task makes ready: its successors, or a task of the join that waits for the remaining\n",
    "branches. Between two events the caller may inspect the run and change what it executes next\n",
    "([Pydantic, 2026b](https://pydantic.dev/docs/ai/graph/builder/)). `anext` is the built-in Python function that returns the next element of\n",
    "an asynchronous iterator; `async for event in run` advances the run in the same way."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c8dee23c",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# The run of `squares`, event by event, with the time at which each event arrives.\n",
    "async with squares.iter(inputs=[3, 1, 2]) as run:\n",
    "    t0 = time.perf_counter()\n",
    "    async for event in run:\n",
    "        if isinstance(event, EndMarker):\n",
    "            print(f\"t={time.perf_counter() - t0:.2f}s  end, output {event.value}\")\n",
    "        else:\n",
    "            print(f\"t={time.perf_counter() - t0:.2f}s \", [(t.node_id, t.inputs) for t in event])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9b9090bc",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "source": [
    "**pydantic-graph represents each task by a record of three fields: the step to execute, its input,\n",
    "and the branch of the fork that the task belongs to.** The record exists in two classes, which differ\n",
    "in who creates the record ([Pydantic, 2026h](https://pydantic.dev/docs/ai/api/pydantic_graph/graph_builder/)):\n",
    "\n",
    "- A **`GraphTask`** is created by the run. Each event returned by `anext(run)` is a list of\n",
    "  `GraphTask` objects, the tasks that have just become ready. A `GraphTask` carries a fourth field,\n",
    "  `task_id`, a unique id that the run assigns.\n",
    "- A **`GraphTaskRequest`** is created by the caller, to ask the run to execute a task:\n",
    "  `run.override_next([...])` takes a list of them. It has the three fields and no task id; the run\n",
    "  converts each request into a `GraphTask` and assigns the id.\n",
    "\n",
    "The three fields:\n",
    "\n",
    "| Field | Content | Example: the first branch of `squares` |\n",
    "|---|---|---|\n",
    "| `node_id` | the id of the step to execute, `step.id` | `'slow_square'` |\n",
    "| `inputs` | the input of this execution of the step | `3` |\n",
    "| `fork_stack` | the **fork stack**: one entry per fork that the task lies behind | the start entry and one entry for the mapping edge, branch 0 |\n",
    "\n",
    "**The fork stack identifies the branch of a fork that a task belongs to; a join reads the fork stacks\n",
    "of the pending tasks to decide when every branch of its fork has arrived**\n",
    "([Pydantic, 2026h](https://pydantic.dev/docs/ai/api/pydantic_graph/graph_builder/))."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ff50a28e",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "source": [
    "**A step that raises an exception does not end the run at once: the run records an `ErrorMarker` and\n",
    "raises the exception in the caller, who may then send replacement tasks with\n",
    "`run.override_next([...])`.** Without a replacement, the next `anext(run)` raises the same exception\n",
    "again ([Pydantic, 2026h](https://pydantic.dev/docs/ai/api/pydantic_graph/graph_builder/)). A replacement is a `GraphTaskRequest` whose `node_id`\n",
    "names the replacement step and whose `inputs` and `fork_stack` are those of the failed task, which the\n",
    "caller kept from the event in which that task appeared. In the linear graph\n",
    "`flaky`, one task of each step is pending at a time, so the node id identifies the failed task. A step that\n",
    "only a repair reaches is not reachable from the start node, and `build()` rejects such a graph unless it\n",
    "is called with `validate_graph_structure=False`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dda1161b",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# A linear graph whose step `primary` always fails, and a step `fallback` that no edge leads to.\n",
    "g = GraphBuilder(input_type=str, output_type=str)\n",
    "\n",
    "@g.step\n",
    "async def primary(ctx: StepContext[None, None, str]) -> str:\n",
    "    raise ConnectionError(f\"primary source unavailable for {ctx.inputs!r}\")\n",
    "\n",
    "@g.step\n",
    "async def fallback(ctx: StepContext[None, None, str]) -> str:\n",
    "    return f\"{ctx.inputs}: answered by the fallback source\"\n",
    "\n",
    "@g.step\n",
    "async def report(ctx: StepContext[None, None, str]) -> str:\n",
    "    return ctx.inputs.upper()\n",
    "\n",
    "g.add(g.edge_from(g.start_node).to(primary), g.edge_from(primary).to(report),\n",
    "      g.edge_from(fallback).to(report), g.edge_from(report).to(g.end_node))\n",
    "flaky = g.build(validate_graph_structure=False)     # `fallback` is reached only by a repair\n",
    "show_graph(flaky)\n",
    "\n",
    "async with flaky.iter(inputs=\"revenue acme\") as run:\n",
    "    pending = {}                                     # node id -> task; unique only without a fork\n",
    "    while True:\n",
    "        try:\n",
    "            event = await anext(run)\n",
    "        except ConnectionError as e:                 # the run detects and reports\n",
    "            print(\"the caller receives:\", e)\n",
    "            failed = pending[primary.id]\n",
    "            run.override_next([GraphTaskRequest(node_id=fallback.id, inputs=failed.inputs,\n",
    "                                                fork_stack=failed.fork_stack)])   # the caller repairs\n",
    "            continue\n",
    "        if isinstance(event, EndMarker):\n",
    "            print(\"output:\", event.value)\n",
    "            break\n",
    "        print(\"ready:\", [(t.node_id, t.inputs) for t in event])\n",
    "        pending = {t.node_id: t for t in event}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8485ac2d",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "source": [
    "**A failed task inside a fork is repaired in the same way, with `override_next` and a\n",
    "`GraphTaskRequest`; three points differ from `flaky`.**\n",
    "\n",
    "- **Identification of the failed task.** The tasks of a fork belong to one step and share its node id,\n",
    "  so the node id does not say which task failed. The caller identifies the task by its input, which the\n",
    "  exception of the step must therefore carry, for example as a field of an exception class of its own.\n",
    "- **The fork stack of the failed branch.** The replacement carries the fork stack of the failed task,\n",
    "  so the join counts the result of the replacement as the result of that branch and waits for it. The\n",
    "  branches that have finished keep their results and are not executed again.\n",
    "- **The branches that are still running.** The other tasks of the fork continue while the caller\n",
    "  repairs, and their results reach the join. If the caller leaves the run instead, by leaving the\n",
    "  `async with` block, the running tasks are cancelled and their results are lost. These are the\n",
    "  lecture's two blocking policies, *drain* and *stop*, and the caller's code chooses between them."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb8c8f2d",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "source": [
    "**Questions.**\n",
    "\n",
    "1. In the trace of `squares`, which event is the dispatch of the ready set, and where does the run\n",
    "   wait?\n",
    "2. In the run of `flaky`, which component detects the failure and which repairs it? Which event shows\n",
    "   the repair?\n",
    "3. What does `g.build()` report for `flaky` without `validate_graph_structure=False`, and why is the\n",
    "   check right for a plan but wrong for a graph that is repaired at run time?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6d998882",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## Tutorial: ReWOO with a Typed Plan\n",
    "\n",
    "**Lecture concept:** ReWOO's Planner, Worker and Solver, with the edges of the plan given by the names\n",
    "of the evidence slots (*ReWOO — Planner · Worker · Solver*); the plan as a structured output that a\n",
    "program checks before it is executed (*Structured Output as the Inter-Step Contract*); the plan\n",
    "compiled into a graph that a scheduler executes in parallel, as in LLMCompiler (*LLMCompiler — a\n",
    "Streamed DAG with Ready-Set Dispatch*, *Parallelism & the Critical Path*). **Library features:** a typed output,\n",
    "an output validator with `ModelRetry`, a graph built from the plan, and a second agent as the Solver.\n",
    "\n",
    "**ReWOO writes the whole plan before any tool runs, executes the steps in the order in which they are\n",
    "listed, and lets one model call compose the answer from the results**\n",
    "([Xu et al., 2023](https://arxiv.org/html/2305.18323)). The result of step $s$ is called `#E`$s$, and\n",
    "a later step that writes `#E1` in its arguments depends on step 1. This tutorial takes the ReWOO tutorial of LangGraph as its example\n",
    "([LangGraph, 2025](https://github.com/langchain-ai/langgraph/tree/23961cff/docs/docs/tutorials)) and\n",
    "changes the form of the plan and its execution. In the LangGraph tutorial, the planner writes the plan as text, which a\n",
    "regular expression parses; a line that does not match the expression is dropped without an error, and\n",
    "a tool name that the code does not know raises `ValueError`. Here the plan is a typed object instead of text: the output type of the planner is `Plan`, a\n",
    "Pydantic model defined in the next cell. Its field `steps` is a list of `Step` objects, each with three\n",
    "fields:\n",
    "\n",
    "- `task`, the step in words (ReWOO's *Plan:* line);\n",
    "- `tool`, one of the three tool names `search`, `search_archive` and `calculator`;\n",
    "- `args`, the argument of the tool, in which `#E1`, `#E2`, … name the results of earlier steps.\n",
    "\n",
    "A reply of the model that does not have this form is rejected, and the planner is asked again. A\n",
    "program then checks the plan before the Worker executes it: first in list order, as ReWOO's Worker\n",
    "does, then compiled into a pydantic-graph that executes independent steps concurrently, as\n",
    "LLMCompiler does. The planner runs on `qwen3.5:9b` (`PLAN_MODEL`) with its reasoning text switched off; the 3B model of\n",
    "the setup is run once for comparison."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15ad7d5f",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "PLAN_MODEL = OllamaModel(\"qwen3.5:9b\", provider=OllamaProvider(base_url=\"http://localhost:11434/v1\"),\n",
    "                         settings={\"extra_body\": {\"reasoning_effort\": \"none\"}})   # no reasoning text: faster\n",
    "LATENCY = {\"acme\": 1.0, \"globex\": 1.5, \"initech\": 0.5}     # seconds per look-up\n",
    "TOOLS = {\"search\": search, \"search_archive\": search_archive, \"calculator\": calculator}\n",
    "\n",
    "def step_latency(tool, args):\n",
    "    \"\"\"The simulated duration of a tool call: the latency of the company searched, 0.2 s otherwise.\"\"\"\n",
    "    return next((LATENCY[c] for c in LATENCY if c in args.lower()), 0.2)\n",
    "\n",
    "class Step(BaseModel):\n",
    "    task: str                                              # the step in words, ReWOO's \"Plan:\" line\n",
    "    tool: Literal[\"search\", \"search_archive\", \"calculator\"]\n",
    "    args: str                                              # may contain #E1, #E2, ... of earlier steps\n",
    "\n",
    "class Plan(BaseModel):\n",
    "    steps: list[Step] = Field(min_length=1)                # the result of step s is called #Es\n",
    "\n",
    "SYS_PLAN = \"\"\"You are the planner of a ReWOO agent: write the whole plan for the question before any tool runs.\n",
    "The result of step 1 is called #E1, the result of step 2 is #E2, and so on. A step uses an earlier\n",
    "result by writing its name in its args. Tools:\n",
    "- search: returns one number for a query such as \"revenue acme\"\n",
    "- search_archive: the same on a second source with the same data\n",
    "- calculator: evaluates + - * / and parentheses on numbers and #E names, e.g. \"(#E1 + #E2) / 2\"\n",
    "Example for \"What is the ratio of the 2024 revenues of A and B?\":\n",
    "{\"steps\": [{\"task\": \"Find the revenue of A\", \"tool\": \"search\", \"args\": \"revenue a\"},\n",
    "           {\"task\": \"Find the revenue of B\", \"tool\": \"search\", \"args\": \"revenue b\"},\n",
    "           {\"task\": \"Divide the two\", \"tool\": \"calculator\", \"args\": \"#E1 / #E2\"}]}\n",
    "The last step computes the answer.\"\"\"\n",
    "\n",
    "QUESTION = (\"What was the combined 2024 revenue of Acme, Globex and Initech, \"\n",
    "            \"and what share of it did Acme have?\")\n",
    "\n",
    "FALLBACK = Plan(steps=[                               # used when the planner or the Worker fails\n",
    "    Step(task=\"Find the revenue of Acme\",    tool=\"search\",     args=\"revenue acme\"),\n",
    "    Step(task=\"Find the revenue of Globex\",  tool=\"search\",     args=\"revenue globex\"),\n",
    "    Step(task=\"Find the revenue of Initech\", tool=\"search\",     args=\"revenue initech\"),\n",
    "    Step(task=\"Add the three revenues\",      tool=\"calculator\", args=\"#E1 + #E2 + #E3\"),\n",
    "    Step(task=\"Divide the revenue of Acme by the total\", tool=\"calculator\", args=\"#E1 / #E4\"),\n",
    "])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "425e7e32",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "source": [
    "**The formal check of a plan** returns the violated rules: a step reads a name `#Ek` that is not\n",
    "computed before it, or the arguments of a `calculator` step are not an expression that the calculator\n",
    "evaluates when every name is replaced by `1`. Registered as an output validator, the check turns a plan\n",
    "that cannot be executed into a retry request to the planner."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "255db009",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# The formal check of a plan, and the planner that retries on a violation\n",
    "NAME = re.compile(r\"#E(\\d+)\\b\")\n",
    "\n",
    "def check_plan(plan):\n",
    "    errs = []\n",
    "    for s, step in enumerate(plan.steps, start=1):\n",
    "        for k in map(int, NAME.findall(step.args)):\n",
    "            if not 1 <= k < s:                              # every edge must point backwards in the list\n",
    "                errs.append(f\"step {s} reads #E{k}, which is not computed before step {s}\")\n",
    "        if step.tool == \"calculator\":\n",
    "            try:\n",
    "                calculator(NAME.sub(\"1\", step.args))       # the expression with every name set to 1\n",
    "            except ZeroDivisionError:\n",
    "                pass                                        # well-formed; only the test value 1 divides by zero\n",
    "            except Exception:\n",
    "                errs.append(f\"step {s}: the calculator cannot evaluate {step.args!r}\")\n",
    "    return errs\n",
    "\n",
    "planner = Agent(PLAN_MODEL, output_type=NativeOutput(Plan), instructions=SYS_PLAN, retries=2)\n",
    "\n",
    "@planner.output_validator\n",
    "def reject_unexecutable(plan: Plan) -> Plan:\n",
    "    errs = check_plan(plan)\n",
    "    if errs:\n",
    "        raise ModelRetry(\"The plan cannot be executed: \" + \"; \".join(errs))\n",
    "    return plan\n",
    "\n",
    "def show(plan):\n",
    "    for s, step in enumerate(plan.steps, start=1):\n",
    "        print(f\"  #E{s} = {step.tool}[{step.args}]   ({step.task})\")\n",
    "\n",
    "try:\n",
    "    pr = await planner.run(QUESTION)\n",
    "    plan, plan_requests = pr.output, pr.usage.requests\n",
    "except UnexpectedModelBehavior as e:\n",
    "    print(\"planner failed:\", e, \"- FALLBACK used\")\n",
    "    plan, plan_requests = FALLBACK, None\n",
    "print(f\"plan of {PLAN_MODEL.model_name}, {plan_requests} request(s):\"); show(plan)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d3682d68",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# The same planner on the 3B model of the setup\n",
    "small = Agent(MODEL, output_type=NativeOutput(Plan), instructions=SYS_PLAN, retries=2)\n",
    "small.output_validator(reject_unexecutable)\n",
    "try:\n",
    "    print(\"plan of qwen2.5:3b:\"); show((await small.run(QUESTION)).output)\n",
    "except UnexpectedModelBehavior as e:\n",
    "    print(\"qwen2.5:3b:\", e)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b5fa20dd",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "**ReWOO's Worker executes the steps in list order and calls no model.** For each step, `worker`\n",
    "replaces every name in the arguments by its value from the **evidence store**, a dictionary from `#Ek`\n",
    "to the result of step $k$, waits the simulated latency and calls the tool. The names decide which\n",
    "results a step reads, not when it runs: a step starts when the step before it in the list has finished.\n",
    "The Solver, a second agent, composes the answer from the step texts and the evidence; `solver_prompt`\n",
    "builds its input."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0da12465",
   "metadata": {
    "slideshow": {
     "slide_type": ""
    }
   },
   "outputs": [],
   "source": [
    "# ReWOO's Worker: list order, the names substituted, no model call\n",
    "solver = Agent(MODEL, instructions=\"Answer the question from the plan and its evidence, in one sentence.\")\n",
    "\n",
    "def solver_prompt(question, plan, evidence):\n",
    "    \"\"\"The question, the step texts and the evidence: everything the Solver reads.\"\"\"\n",
    "    return f\"Question: {question}\\n\" + \"\\n\".join(\n",
    "        f\"Plan: {st.task}\\n#E{s} = {st.tool}[{st.args}] -> {evidence[f'#E{s}']}\"\n",
    "        for s, st in enumerate(plan.steps, start=1))\n",
    "\n",
    "async def worker(plan):\n",
    "    evidence = {}\n",
    "    for s, step in enumerate(plan.steps, start=1):\n",
    "        args = NAME.sub(lambda m: evidence[m.group()], step.args)    # the edge\n",
    "        await asyncio.sleep(step_latency(step.tool, args))\n",
    "        evidence[f\"#E{s}\"] = TOOLS[step.tool](args)\n",
    "    return evidence\n",
    "\n",
    "try:\n",
    "    t0 = time.perf_counter()\n",
    "    evidence = await worker(plan)\n",
    "except Exception as e:                                     # a plan that passes the check can still fail here\n",
    "    print(\"the Worker stops on this plan:\", type(e).__name__, e, \"- FALLBACK used\")\n",
    "    plan = FALLBACK\n",
    "    t0 = time.perf_counter()\n",
    "    evidence = await worker(plan)\n",
    "worker_time = time.perf_counter() - t0\n",
    "prompt = solver_prompt(QUESTION, plan, evidence)\n",
    "sr = await solver.run(prompt)\n",
    "print(prompt); print(\"answer:\", sr.output)\n",
    "print(f\"time of the Worker {worker_time:.2f}s | model requests: planner {plan_requests}, solver {sr.usage.requests}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a62fd953",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "**A Worker that compiles the plan into a graph goes beyond ReWOO: a scheduler executes every step as\n",
    "soon as the steps it reads have finished. This is the execution model of LLMCompiler.** In ReWOO, and\n",
    "in the LangGraph tutorial, the Worker executes the steps one after another in list order, as `worker`\n",
    "does. LLMCompiler\n",
    "executes the plan as a dependency graph, which is how Kim et al. (2024) distinguish it from ReWOO: its\n",
    "**Task Fetching Unit**, modelled on the instruction fetching unit of a processor, dispatches each task\n",
    "whose dependencies have finished, and its **Executor** runs the dispatched tasks concurrently\n",
    "([Kim et al., 2024](https://arxiv.org/html/2312.04511)).\n",
    "\n",
    "**The compiler analogy.** Kim et al. (2024, §1) name the system after classical compilers, which\n",
    "identify the instructions of a program that can be executed in parallel and manage the dependencies\n",
    "between them; LLMCompiler does the same for the function calls of a plan. The analogy extends to its\n",
    "parts: the Task Fetching Unit is *\"inspired by the instruction fetching units in modern computer\n",
    "architectures\"* (Kim et al., 2024, §3.2), streaming the plan while it is generated is *\"analogous to\n",
    "instruction pipelining in modern computer systems\"* (Kim et al., 2024, §4.2), and a new plan written\n",
    "from intermediate results is called a *\"recompilation\"* (Kim et al., 2024, §3.4). In this tutorial,\n",
    "`plan_graph` is the compilation: it translates the plan that the planner writes into a graph whose\n",
    "edges are the data dependencies between the steps, and the library schedules the graph:\n",
    "\n",
    "| LLMCompiler | This tutorial |\n",
    "|---|---|\n",
    "| Function Calling Planner: a plan whose tasks read earlier results through placeholders `$1`, `$2`, … | `planner`: a `Plan` whose steps read earlier results through `#E1`, `#E2`, … |\n",
    "| the dependency graph of the plan | `plan_graph`: one graph step per plan step, one edge per name `#Ek` |\n",
    "| Task Fetching Unit: dispatches the tasks whose dependencies have finished | the run of pydantic-graph, which keeps the ready set and dispatches it: the scheduler |\n",
    "| Executor: runs the dispatched tasks concurrently | the run, which executes its tasks concurrently in the event loop |\n",
    "| streamed planning: a task starts while the plan is still being generated | not taken over: the graph is built when the plan is complete |\n",
    "| Joiner: a final model call that answers or requests a new plan | not taken over: ReWOO's Solver answers; [*Tutorial: Replanning on a Failed Step*](#Tutorial:-Replanning-on-a-Failed-Step) replans when a step fails |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "854b4ee2",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "source": [
    "**`plan_graph` compiles the plan into a pydantic-graph, and `compiled_worker` executes the graph\n",
    "without a model call.** In the typical plan, the three look-ups read no name and therefore run\n",
    "concurrently. `plan_graph` builds the\n",
    "graph from the names `#Ek` in the arguments:\n",
    "\n",
    "| Plan | pydantic-graph |\n",
    "|---|---|\n",
    "| step $s$ | a step with the node id `E`$s$, labelled with its tool call `#E`$s$` = tool[args]` |\n",
    "| a step that reads no name | an edge from `g.start_node`; several such steps form a fork |\n",
    "| a step that reads one name `#Ek` | an edge from step $k$ |\n",
    "| a step that several steps read | one edge to each of them, which pydantic-graph turns into a fork (an unlabelled bar in the figure) |\n",
    "| a step that reads several names | a join `join_E`$s$, whose reducer `merge` unites the evidence of its inputs, and an edge from the join to the step |\n",
    "| a step whose result no step reads | an edge to the join `answer`, which leads to `g.end_node` |\n",
    "\n",
    "`plan_graph` first applies `check_plan` and raises `ValueError` on a violation: the edges then point\n",
    "backwards in the list only, so the graph is acyclic. The steps of a graph built from data cannot be written as decorated functions in advance: the inner\n",
    "function `node` creates one step function per plan step, and `g.step(run, node_id=…, label=…)`, the decorator\n",
    "`@g.step` called as a function, registers it; the label is the text that `show_graph` draws in the node ([Pydantic, 2026h](https://pydantic.dev/docs/ai/api/pydantic_graph/graph_builder/)).\n",
    "The value on the edges is the evidence store. Each step replaces the names in its arguments by their values, waits the simulated latency, calls the\n",
    "tool and returns the dictionary extended by its own result; it therefore receives the results of its\n",
    "ancestors and of no other step. The output of the run holds the evidence of every step. The next cell\n",
    "executes the plan of the planner with `compiled_worker` and compares its time and its evidence with\n",
    "those of `worker`; the last cell runs `worker` once more without the revenue of Initech in `FACTS`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "578e226b",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# LLMCompiler's execution: the plan compiled into a graph, which the run schedules\n",
    "def merge(acc: dict, x: dict) -> dict:\n",
    "    \"\"\"The reducer of every join: the evidence of all inputs in one dictionary.\"\"\"\n",
    "    return {**acc, **x}\n",
    "\n",
    "def plan_graph(plan):\n",
    "    \"\"\"A pydantic-graph with one step per plan step and one edge per name #Ek in the arguments.\"\"\"\n",
    "    if errs := check_plan(plan):                            # backward edges only: the graph is a DAG\n",
    "        raise ValueError(\"plan_graph needs a checked plan: \" + \"; \".join(errs))\n",
    "    g = GraphBuilder(input_type=dict, output_type=dict)\n",
    "\n",
    "    def node(s, step):\n",
    "        async def run(ctx: StepContext[None, None, dict]) -> dict:\n",
    "            args = NAME.sub(lambda m: ctx.inputs[m.group()], step.args)      # the edge\n",
    "            await asyncio.sleep(step_latency(step.tool, args))\n",
    "            return {**ctx.inputs, f\"#E{s}\": TOOLS[step.tool](args)}\n",
    "        return g.step(run, node_id=f\"E{s}\", label=f\"#E{s} = {step.tool}[{step.args}]\")\n",
    "\n",
    "    reads = {s: {int(k) for k in NAME.findall(st.args)} for s, st in enumerate(plan.steps, start=1)}\n",
    "    nodes = {s: node(s, st) for s, st in enumerate(plan.steps, start=1)}\n",
    "    joins = {s: g.join(merge, initial_factory=dict, node_id=f\"join_E{s}\") for s in reads if len(reads[s]) > 1}\n",
    "    answer = g.join(merge, initial_factory=dict, node_id=\"answer\")\n",
    "    entry = {s: joins.get(s, nodes[s]) for s in nodes}                 # where the input of step s arrives\n",
    "    g.add(g.edge_from(g.start_node).to(*[nodes[s] for s in reads if not reads[s]]),\n",
    "          g.edge_from(answer).to(g.end_node))\n",
    "    for s in nodes:\n",
    "        if s in joins:\n",
    "            g.add(g.edge_from(joins[s]).to(nodes[s]))\n",
    "        readers = [entry[t] for t in reads if s in reads[t]]\n",
    "        g.add(g.edge_from(nodes[s]).to(*(readers or [answer])))\n",
    "    return g.build()\n",
    "\n",
    "async def compiled_worker(plan):\n",
    "    return await plan_graph(plan).run(inputs={})                       # the evidence of every step\n",
    "\n",
    "t0 = time.perf_counter()\n",
    "compiled_evidence = await compiled_worker(plan)\n",
    "print(f\"list order (worker) {worker_time:.2f}s | graph (compiled_worker) {time.perf_counter() - t0:.2f}s | \"\n",
    "      f\"same evidence: {compiled_evidence == evidence}\")\n",
    "show_graph(plan_graph(plan))                               # the executed plan as a graph"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "03b85378",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# A missing fact\n",
    "missing = FACTS.pop((\"revenue\", \"initech\"))\n",
    "try:\n",
    "    await worker(plan)\n",
    "except Exception as e:\n",
    "    print(\"the Worker stops:\", type(e).__name__, e)\n",
    "finally:\n",
    "    FACTS[(\"revenue\", \"initech\")] = missing"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e511ad90",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "source": [
    "**Questions.**\n",
    "\n",
    "1. Which faults of the LangGraph tutorial's plan text can a `Plan` not have — a dropped line, a `]`\n",
    "   inside an argument, an unknown tool name — and which faults of a plan can it still have?\n",
    "2. Why does `check_plan` need no topological sort, and why can a plan that passes it contain no\n",
    "   cycle? What must a check verify in addition if each step lists its predecessors in a field\n",
    "   `depends_on`, so that the list no longer fixes the order?\n",
    "3. Does the plan of the 3B model pass the check, and does it answer the question? What does the check\n",
    "   decide, and what not?\n",
    "4. How many model requests did the run make, and which records does the Solver read?\n",
    "5. How long do `worker` and `compiled_worker` take on the same plan, and how long is its critical\n",
    "   path? Which steps run at the same time, and in which plan does the time of `compiled_worker` exceed\n",
    "   the critical path?\n",
    "6. Where does the run without the revenue of Initech fail? Which component could have detected the\n",
    "   failure, and which two design dimensions of the lecture does ReWOO leave empty?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d79c502d",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## Tutorial: Replanning on a Failed Step\n",
    "\n",
    "**Lecture concept:** replanning triggered by a failed step, which rewrites the plan (*Replanning*); the\n",
    "fresh-context retry, which gives the planner the goal and a failure report instead of the failed run,\n",
    "and the deterministic fallback after $\\kappa_{\\text{plan}}$ rounds (*Recovery Strategies*). **Library\n",
    "features:** none beyond [*Tutorial: ReWOO with a Typed Plan*](#Tutorial:-ReWOO-with-a-Typed-Plan),\n",
    "whose `planner`, `compiled_worker`, `show`, `solver` and `solver_prompt` are reused.\n",
    "\n",
    "**Replanning revises a plan from what the run has observed. Here the trigger is a failed step, and\n",
    "the planner writes the whole plan again.** ReWOO itself never revises its plan: when a tool raises,\n",
    "the Worker stops and the run has no answer. The loop `rewoo_with_replanning` adds the revision around\n",
    "the planner and the Worker, here `compiled_worker`:\n",
    "\n",
    "1. The planner writes a plan for the question; the Worker executes it.\n",
    "2. If the Worker stops, the planner is called again with the question and a **failure report**, the\n",
    "   type and the message of the exception. The call is a fresh one: it does not read the failed plan or\n",
    "   its results.\n",
    "3. After `KAPPA_PLAN` rounds without a plan that the Worker completes, the loop stops calling the\n",
    "   model and executes a fixed plan, `ARCHIVE_FALLBACK`: the plan `FALLBACK` with every look-up on\n",
    "   `search_archive`.\n",
    "\n",
    "The run takes the source of `search` down for Initech (`OUTAGE`), so every plan that looks up Initech\n",
    "with `search` fails at that step."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "672be2d9",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Replanning on a failed step: a fresh planner call with the goal and the failure report\n",
    "KAPPA_PLAN = 2                                             # planning rounds, the first included, before the fallback\n",
    "ARCHIVE_FALLBACK = Plan(steps=[                            # FALLBACK with every look-up on the second source\n",
    "    s.model_copy(update={\"tool\": \"search_archive\"}) if s.tool == \"search\" else s for s in FALLBACK.steps])\n",
    "\n",
    "async def rewoo_with_replanning(question):\n",
    "    report = \"\"\n",
    "    for round_ in range(1, KAPPA_PLAN + 1):\n",
    "        try:\n",
    "            plan = (await planner.run(question + report)).output   # a fresh call: the goal and the failure report\n",
    "        except UnexpectedModelBehavior as e:                       # the planner's retries are exhausted\n",
    "            print(f\"round {round_}: the planner failed:\", e)\n",
    "            continue\n",
    "        print(f\"round {round_}, plan:\"); show(plan)\n",
    "        try:\n",
    "            return plan, await compiled_worker(plan)\n",
    "        except Exception as e:                                     # the Worker stops at the failed step\n",
    "            report = f\"\\nA previous plan failed: {type(e).__name__}: {e}\"\n",
    "            print(\"  the Worker stops:\", report.strip())\n",
    "    print(f\"no completed plan in {KAPPA_PLAN} rounds: the deterministic fallback\"); show(ARCHIVE_FALLBACK)\n",
    "    return ARCHIVE_FALLBACK, await compiled_worker(ARCHIVE_FALLBACK)\n",
    "\n",
    "OUTAGE.add(\"initech\")\n",
    "try:\n",
    "    final_plan, final_evidence = await rewoo_with_replanning(QUESTION)\n",
    "finally:\n",
    "    OUTAGE.discard(\"initech\")\n",
    "print(\"answer:\", (await solver.run(solver_prompt(QUESTION, final_plan, final_evidence))).output)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "09bcbeed",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "source": [
    "**Questions.**\n",
    "\n",
    "1. What does the planner receive in the second round, and what does it not receive? Why does the\n",
    "   lecture's fresh-context retry pass a failure report instead of the failed run?\n",
    "2. Which tool does the plan of the second round use for Initech? Which steps of the first round are\n",
    "   executed again, and what does one replanning round cost in model requests and in time?\n",
    "3. Run the cell several times. How often does the fallback run, and what does it guarantee that a\n",
    "   replanning round does not?\n",
    "4. Which row of the lecture's table of replanning triggers does the loop implement, and how does it\n",
    "   differ from Plan-and-Execute?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "55c458d0",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## References\n",
    "\n",
    "**Peer-reviewed papers**\n",
    "\n",
    "- Kim, Sehoon, et al. \"An LLM Compiler for Parallel Function Calling.\" International Conference on Machine Learning. Vol. 235. 2024. [arXiv:2312.04511](https://arxiv.org/html/2312.04511). — the Task Fetching Unit, which dispatches a task as soon as the tasks it reads have finished.\n",
    "\n",
    "**Preprints & other non-peer-reviewed papers**\n",
    "\n",
    "- Xu, Binfeng, et al. \"ReWOO: Decoupling Reasoning from Observations for Efficient Augmented Language Models.\" arXiv preprint [arXiv:2305.18323](https://arxiv.org/html/2305.18323) (2023). — Planner / Worker / Solver; dependency edges as variable bindings (`#E1`).\n",
    "\n",
    "**Blogs, documentation & other web sources**\n",
    "\n",
    "- LangGraph. \"Planning-agent tutorials: Plan-and-Execute, ReWOO, LLMCompiler.\" *langchain-ai/langgraph*, commit 23961cff, 2025. <https://github.com/langchain-ai/langgraph/tree/23961cff/docs/docs/tutorials> — the ReWOO tutorial, cited for what the code does: a plan parsed from text by a regular expression, tool names checked by `if`/`elif`, names substituted with `str.replace`.\n",
    "- Pydantic. \"Agents.\" *Pydantic AI documentation*, 2026a, retrieved 2026-10-30. <https://pydantic.dev/docs/ai/core-concepts/agent/> — the components an `Agent` holds; a run as the node sequence `UserPromptNode → ModelRequestNode → CallToolsNode → End`; `UsageLimits`, by default 50 requests; the retry budget, by default 1, and `UnexpectedModelBehavior`; `pydantic_graph.persistence` removed in V2.\n",
    "- Pydantic. \"Graph Builder.\" *Pydantic AI documentation*, 2026b, retrieved 2026-10-01. <https://pydantic.dev/docs/ai/graph/builder/> — steps, edges, fork and join; `graph.iter` and `GraphRun`; no persistence of a run.\n",
    "- Pydantic. \"Ollama.\" *Pydantic AI documentation*, 2026c, retrieved 2026-10-01. <https://pydantic.dev/docs/ai/models/ollama/> — `OllamaModel`; `NativeOutput` enforced by the grammar-constrained decoder of a local server.\n",
    "- Pydantic. \"Output.\" *Pydantic AI documentation*, 2026d, retrieved 2026-10-01. <https://pydantic.dev/docs/ai/core-concepts/output/> — tool, native and prompted output; validation of the output and retries.\n",
    "- Pydantic. \"Overview.\" *Pydantic AI documentation*, 2026e, retrieved 2026-10-02. <https://pydantic.dev/docs/ai/overview/> — the self-description of the library.\n",
    "- Pydantic. \"Parallel Execution.\" *Pydantic AI documentation*, 2026f, retrieved 2026-10-28. <https://pydantic.dev/docs/ai/graph/builder/parallel/> — fork (broadcast, spread) and join; reduction in completion order.\n",
    "- Pydantic. \"pydantic_ai/messages.py and models/openai.py.\" *pydantic/pydantic-ai*, GitHub, tag v2.54.0, 2026g. <https://github.com/pydantic/pydantic-ai/blob/v2.54.0/pydantic_ai_slim/pydantic_ai/messages.py> — `ModelRequest`, `ModelResponse` and their parts; the conversion of the parts into the messages of the Chat Completions API (`OpenAIChatModel`, the base class of `OllamaModel`).\n",
    "- Pydantic. \"pydantic_graph.graph_builder.\" *Pydantic AI API reference*, 2026h, retrieved 2026-10-28. <https://pydantic.dev/docs/ai/api/pydantic_graph/graph_builder/> — `GraphRun`, `ErrorMarker`, `override_next`.\n",
    "- Python Software Foundation. \"Event Loop.\" *Python 3.14 documentation*, 2025, retrieved 2026-10-29. <https://docs.python.org/3.14/library/asyncio-eventloop.html> — the event loop of `asyncio`, which runs the coroutines of one thread."
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Slideshow",
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "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.12.3"
  },
  "rise": {
   "scroll": true,
   "theme": "simple",
   "transition": "none"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}