Agentic AI

Combining the patterns

Real workflows nest the five patterns. Compare them side by side, then build a report writer in one script with Gemini: a planner, parallel writers, and a reviewer that sends the report back to an editor, at most twice.

Concept + code Python 3.12 Needs GOOGLE_API_KEY

Lessons 13.1 to 13.5 built each workflow pattern on its own. Real applications combine them: a router in front of chains, a parallel vote as a gate, workers that are themselves small chains, an evaluator after the merge. This lesson puts the five side by side, then builds one combination in a single script: a report writer whose planner and parallel writers come from lesson 13.4 and whose review loop comes from lesson 13.5.

Five shapes

Five workflow shapes

Each pattern drawn as the graph its lesson builds, with the edge that makes it.

Prompt chaining The input goes to generate, a model call. A gate in code follows: pass leads to improve and then polish, two more model calls, and then to the output; fail leads back to generate. Prompt chaining · 13.1 fixed steps, a gate between them in generate gate improve polish out pass fail Parallelization The input fans out to three model calls, character, setting and premise, which run in the same super-step; all three lead to combine, which produces the output. Parallelization · 13.2 independent calls at once, then a merge in character setting premise combine out three calls in one super-step Routing The input goes to router, a model call that classifies it. Dashed conditional edges lead to three handlers, story, joke and poem, of which one runs; each leads to the output. Routing · 13.3 classify first, then one handler in router story joke poem out one runs a conditional edge picks the node Orchestrator-worker The input goes to orchestrator, a model call that plans the subtasks. A dashed edge labelled Send times n starts one run of llm_call per subtask, drawn as a stack of cards. All runs lead to synthesizer, plain code that joins the results, and then to the output. Orchestrator-worker · 13.4 a plan made at run time, a worker each in orchestrator llm_call × n synthesizer out Send × n Evaluator-optimizer The input goes to generator, a model call, then to evaluator, a second model call. A dashed edge marked rejected plus feedback loops back to generator; another, marked accepted, leads to the output. Evaluator-optimizer · 13.5 write, grade, revise until accepted in generator evaluator out rejected + feedback accepted a loop: cap the rounds

Observe: all five are ordinary nodes and edges. What differs is how many paths leave a node and what chooses them: fixed edges (chaining, parallelization), a function that picks one (routing), a function that creates as many as the plan needs (orchestrator-worker), or a function that can lead back (evaluator-optimizer).

Pattern Use it when Built with Model calls per run Main risk
Prompt chaining (13.1) The task splits into fixed steps, each needing the last one's output Edges in a line; a gate on a conditional edge One per step, plus retries Errors compound; an unbounded retry loop
Parallelization (13.2) Independent subtasks, or several opinions on one task Several edges from one node; fan-in to an aggregator One per branch, plus the merge Uneven branches; rate limits
Routing (13.3) Inputs fall into categories that need different handling A classifier node and a conditional edge, or Command One to classify, plus the handler's Silent misroutes
Orchestrator-worker (13.4) The subtasks depend on the input Send from a conditional edge; a reducer; fan-in One to plan, one per subtask, plus the merge Empty or oversized plans; workers without context
Evaluator-optimizer (13.5) Clear criteria, and feedback that improves the next attempt A conditional edge back to the generator Two per round Loops that never pass; unreliable judges

Choose by asking two questions. Are the steps known before the run? Then chain them, or run them in parallel when they don't depend on each other. If not, does the input decide the steps once (routing, orchestrator-worker) or does each result decide the next step? The last is an agent (lesson 8.1), the next level of autonomy, with the next level of cost and unpredictability. An evaluator loop can be added to any of them where quality matters more than latency.

Patterns nest

Each pattern is a few nodes and edges, so one pattern's node can hold another pattern:

  • Routing, then a chain per route: a support router sends refunds to a three-step chain (look up the order, check the policy, draft the reply) and general questions to a single call.
  • Parallel voting as a gate: three judges vote on a draft before a chain continues.
  • Workers that are chains or agents: each section writer first searches, then writes, then checks its facts; or a whole agent built with create_agent (lesson 9.4) is the worker node.
  • An evaluator after the merge: the synthesizer's result goes to a reviewer, the script below.

Each nesting multiplies calls, so count them before you build: the report writer below makes one call to plan, one per section, and two per review round.

The report writer in one script

The script below is the module as one terminal program, with Gemini as the model: read it to revise, and press Explain on it for every step. It needs GOOGLE_API_KEY in .env (lesson 6.1) and the packages of lesson 6.1's requirements.txt plus langgraph (lesson 10.2).

report_writer.pyPython
"""A report writer: a planner splits the topic into sections, writers draft them in parallel,
and a reviewer sends the report to an editor until it passes or three reviews are used up."""
import operator
from typing import Annotated, Literal

from dotenv import load_dotenv
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_google_genai import ChatGoogleGenerativeAI
from langgraph.graph import END, START, StateGraph
from langgraph.types import Send
from pydantic import BaseModel, Field
from typing_extensions import TypedDict

load_dotenv()  # GOOGLE_API_KEY from .env

MAX_REVIEWS = 3  # the reviewer may send the report back twice


# 1. Schemas for structured output: the plan and the review
class Section(BaseModel):
    name: str = Field(description="Name for this section of the report")
    description: str = Field(description="Brief overview of the main topics and concepts of the section")


class Sections(BaseModel):
    sections: list[Section] = Field(description="Sections of the report")


class Review(BaseModel):
    grade: Literal["pass", "revise"] = Field(description="pass if the report is accurate, clear and complete")
    feedback: str = Field(description="If the grade is revise, the specific changes the report needs")


# 2. State: the graph's, and the input each writer receives
class State(TypedDict):
    topic: str
    sections: list[Section]
    completed_sections: Annotated[list, operator.add]  # every writer adds its section here
    report: str
    grade: str
    feedback: str
    reviews: int


class WorkerState(TypedDict):
    topic: str
    section: Section


# 3. Model, and two structured views of it
llm = ChatGoogleGenerativeAI(model="gemini-3.5-flash-lite")
planner = llm.with_structured_output(Sections)
reviewer = llm.with_structured_output(Review)


# 4. Nodes: plan, write in parallel, join, review, edit
def orchestrator(state: State) -> dict:
    plan = planner.invoke([
        SystemMessage(content="Plan a short report of three to five sections."),
        HumanMessage(content=f"Report topic: {state['topic']}"),
    ])
    print("Plan:", ", ".join(section.name for section in plan.sections))
    return {"sections": plan.sections}


def assign_workers(state: State) -> list[Send]:
    return [Send("write_section", {"topic": state["topic"], "section": s}) for s in state["sections"]]


def write_section(state: WorkerState) -> dict:
    section = state["section"]
    reply = llm.invoke([
        SystemMessage(content="Write one section of a report in Markdown, starting with a '## ' heading. "
                              "At most 150 words, no preamble."),
        HumanMessage(content=f"Report topic: {state['topic']}\nSection: {section.name}\n"
                             f"Cover: {section.description}"),
    ])
    print("Wrote:", section.name)
    return {"completed_sections": [reply.text]}


def synthesizer(state: State) -> dict:
    return {"report": "\n\n".join(state["completed_sections"])}


def review(state: State) -> dict:
    verdict = reviewer.invoke([
        SystemMessage(content="You review reports. Pass a report that is accurate, clear and covers its topic; "
                              "otherwise list the specific changes it needs."),
        HumanMessage(content=f"Topic: {state['topic']}\n\n{state['report']}"),
    ])
    reviews = state["reviews"] + 1
    print(f"Review {reviews}: {verdict.grade}" + (f" - {verdict.feedback}" if verdict.grade == "revise" else ""))
    return {"grade": verdict.grade, "feedback": verdict.feedback, "reviews": reviews}


def after_review(state: State) -> Literal["edit", END]:
    if state["grade"] == "pass" or state["reviews"] >= MAX_REVIEWS:
        return END
    return "edit"


def edit(state: State) -> dict:
    reply = llm.invoke([
        SystemMessage(content="Revise the report to address the feedback. Keep its Markdown structure "
                              "and return only the revised report."),
        HumanMessage(content=f"Feedback: {state['feedback']}\n\nReport:\n{state['report']}"),
    ])
    return {"report": reply.text}


# 5. Graph: orchestrator -> writers in parallel -> synthesizer -> review, with edits until it passes
builder = StateGraph(State)
builder.add_node("orchestrator", orchestrator)
builder.add_node("write_section", write_section)
builder.add_node("synthesizer", synthesizer)
builder.add_node("review", review)
builder.add_node("edit", edit)
builder.add_edge(START, "orchestrator")
builder.add_conditional_edges("orchestrator", assign_workers, ["write_section"])
builder.add_edge("write_section", "synthesizer")
builder.add_edge("synthesizer", "review")
builder.add_conditional_edges("review", after_review)
builder.add_edge("edit", "review")
graph = builder.compile()


def main() -> None:
    topic = input("Report topic: ").strip() or "Agentic AI systems"
    result = graph.invoke({"topic": topic, "reviews": 0}, {"max_concurrency": 5})
    if "report" not in result:
        print("The planner returned no sections.")
        return
    verdict = "Accepted" if result["grade"] == "pass" else "Not accepted"
    print(f"{verdict} after {result['reviews']} review(s).\n")
    print(result["report"])


if __name__ == "__main__":
    main()

Run it

Terminalzsh
python report_writer.py
OutputIllustrative · reports and reviews vary per run; the report is cut after its first section here
Report topic: Agentic AI systems
Plan: What agentic AI systems are, How they work, Where they are used, Risks and limits
Wrote: How they work
Wrote: What agentic AI systems are
Wrote: Risks and limits
Wrote: Where they are used
Review 1: revise - Give one concrete example of an agent at work in "Where they are used", and define tool calling where it first appears.
Review 2: pass
Accepted after 2 review(s).

## What agentic AI systems are

An agentic AI system uses a language model to decide what to do next: which tool to call, which step to take, when the task is done. ...

The writers finished in their own order, and the report still follows the plan: LangGraph 1.2 adds the writers' sections in the order of the sends, though its documentation doesn't promise it (lesson 13.4 sorts by position to be safe). This run made eight model calls: one plan, four sections, two reviews and one edit.

Swap one piece

Piece In the script Alternatives
Model ChatGoogleGenerativeAI(...) for every step The other providers of lesson 13.1; a small model for the writers and a stronger one for the reviewer
Plan size Asked for in the planner's prompt Enforced in code: state["sections"][:5] in assign_workers
Writer One model call per section A chain per section (13.1), or an agent with a search tool (lesson 11.4)
Order The order LangGraph applies the writers' updates A position in each Send, sorted in the synthesizer (13.4)
Synthesizer Joins the sections A model call that adds an introduction and smooths the transitions
Reviewer One model call with a short rubric Code checks first (13.5, practice 2), a panel of judges (13.2), or a person (14.3)
Loop bound MAX_REVIEWS Plus a recursion_limit; keep the best-scored version, not the last
Progress Printed by the nodes graph.stream(...) with a stream mode (lesson 11.6)

Interview questions

Question 1A company wants to automate replies to customer emails. Which patterns would you combine, and where?Show answer

Routing first: classify each email (refund, technical, account, other) and send it to a handler with its own prompt and tools, with "other" going to a person. Inside a handler, a short chain: look up the order or account, draft the reply, then gates in code (no personal data leaked, required links present). Before sending, an evaluator checks tone and policy, with a limit on rewrites; for refunds above a threshold, a person approves (lesson 14.3). Parallel steps where checks are independent, such as policy and fact checks on the same draft. Measure the router and the evaluator separately on labelled emails.

Question 2How do you estimate and control the cost of a combined workflow?Show answer

Count model calls per run from the graph: one per chain step, one per parallel branch or worker, two per evaluator round, plus routers and merges, and multiply by tokens per call; the longest path and the loop limits give the worst case. Control it with caps (sections in the plan, rounds in loops, recursion_limit), cheaper models for routine steps, code instead of a model wherever code can decide, max_concurrency for rate limits, and traces that show where the tokens go (lesson 12.1).

Question 3Why not build every one of these as a single agent with tools?Show answer

An agent decides its own steps at run time, which costs more calls, makes runs harder to predict and test, and lets the model skip steps that must happen, such as a policy check. When the steps are known, a workflow guarantees them, runs cheaper and fails in fewer ways. Agents are for open-ended tasks whose steps can't be planned; many systems use workflows for the fixed parts and an agent inside one node for the open part (lesson 8.1).

Practice

Practice 1Wire the report writer without a model. Build the script's graph with stand-in functions: the same node names, edges and review limit, a fixed plan of three sections, and a reviewer that asks for changes once and then passes. Stream the run and print each node's update.Show solution
Notebook cellPython
import operator
from typing import Annotated, Literal

from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.types import Send


class State(TypedDict):
    topic: str
    sections: list[str]
    completed_sections: Annotated[list, operator.add]
    report: str
    grade: str
    reviews: int


verdicts = iter(["revise", "pass"])


def orchestrator(state: State):
    return {"sections": ["Intro", "Uses", "Risks"]}


def assign_workers(state: State):
    return [Send("write_section", {"section": s}) for s in state["sections"]]


def write_section(state: dict):
    return {"completed_sections": [f"## {state['section']}"]}


def synthesizer(state: State):
    return {"report": " | ".join(state["completed_sections"])}


def review(state: State):
    return {"grade": next(verdicts), "reviews": state["reviews"] + 1}


def after_review(state: State) -> Literal["edit", END]:
    return END if state["grade"] == "pass" or state["reviews"] >= 3 else "edit"


def edit(state: State):
    return {"report": state["report"] + " (edited)"}


builder = StateGraph(State)
for name, node in [("orchestrator", orchestrator), ("write_section", write_section),
                   ("synthesizer", synthesizer), ("review", review), ("edit", edit)]:
    builder.add_node(name, node)
builder.add_edge(START, "orchestrator")
builder.add_conditional_edges("orchestrator", assign_workers, ["write_section"])
builder.add_edge("write_section", "synthesizer")
builder.add_edge("synthesizer", "review")
builder.add_conditional_edges("review", after_review)
builder.add_edge("edit", "review")
wiring = builder.compile()

for update in wiring.stream({"topic": "agents", "reviews": 0}):
    for node, change in update.items():
        print(f"{node:<14}{change}")
OutputReal output · the three writers run in parallel and can finish in another order
orchestrator  {'sections': ['Intro', 'Uses', 'Risks']}
write_section {'completed_sections': ['## Intro']}
write_section {'completed_sections': ['## Uses']}
write_section {'completed_sections': ['## Risks']}
synthesizer   {'report': '## Intro | ## Uses | ## Risks'}
review        {'grade': 'revise', 'reviews': 1}
edit          {'report': '## Intro | ## Uses | ## Risks (edited)'}
review        {'grade': 'pass', 'reviews': 2}

Eight updates for eight node runs: one plan, three writers, the join, and the loop of review, edit and review. Stand-ins test the wiring, the fan-in and the loop's exit without a key or a cent; swapping each function for its model version changes what the updates contain, not the order of the nodes.

Further reading