Skip to main content

Lab 20: Building an Essay Refinement System

Goalโ€‹

In this lab, you will build a self-improving agent system that uses a Dynamic Workflow to iteratively refine an essay. You will implement the powerful "Critic -> Refiner" pattern using a standard Python loop.

The Architectureโ€‹

  1. Initial Writer Node: An agent that creates the first draft.
  2. Refinement Loop Node (@node): A function that orchestrates the iteration:
    • Critic Node (output_schema=CritiqueResult): Evaluates the draft using a structured Pydantic schema (approved: bool, feedback: str) so termination is 100% deterministic rather than relying on brittle string matching.
    • Refiner Node: Applies review.get("feedback", "") to improve the draft.
    • Termination: The loop breaks immediately when review.get("approved") is True, or after at most 3 iterations.

Step 1: Create the Project Structureโ€‹

Environment setup:

  • 1-Click Launch (Browser): Open in GitHub CodespacesOpen in Google Cloud Shell
  • Local machine: If you're continuing the course in sequence, cd into the adk-training project you created in Module 2 and skip the block below -- your environment and dependencies already carry forward. If you're starting fresh at this module, create that project first:
    uv init adk-training --python 3.10 && cd adk-training
    uv add "google-adk>=2.1.0" python-dotenv
  • DevContainer / Codespaces (Alternative): If you opened this repository in a DevContainer or GitHub Codespaces, Python 3.11, uv, gcloud, and all core ADK dependencies are pre-installed in your container environment.
  1. Create the project:
    uv run adk create essay_refiner

Step 2: Define the Structured Schema, Nodes, and Orchestratorโ€‹

Exercise: Open essay_refiner/agent.py. Your task is to define the CritiqueResult Pydantic schema, the three specialist agents (each with rerun_on_resume=True), and the @node(rerun_on_resume=True) function that runs the bounded loop.

# In agent.py (Starter Code)

from pydantic import BaseModel, Field
from google.adk import Agent, Context, Workflow
from google.adk.workflow import node

# 1. Define Structured Critique Schema
class CritiqueResult(BaseModel):
approved: bool = Field(
description="True ONLY when the draft satisfies all criteria and needs no further edits."
)
feedback: str = Field(
description="Specific actionable revision notes if not approved, or brief praise if approved."
)

# 2. Define the Specialist Agents
# IMPORTANT:
# - Every child Agent invoked via ctx.run_node() inside @node(rerun_on_resume=True)
# MUST also set rerun_on_resume=True!
# - Write instructions in plain language describing the input, not with {template}
# placeholders -- ctx.run_node()'s second argument becomes the node's input
# content directly (not session state).

# TODO: Define the initial writer agent (model="gemini-3.8-flash", rerun_on_resume=True).
writer = ...

# TODO: Define the critic agent (model="gemini-3.8-flash", rerun_on_resume=True, output_schema=CritiqueResult).
critic = ...

# TODO: Define the refiner agent (model="gemini-3.8-flash", rerun_on_resume=True).
# It must rewrite the story based on the critique feedback.
refiner = ...

# 3. Define the Iterative Orchestrator
# rerun_on_resume=True is required on both @node and every child Agent called via ctx.run_node().
@node(rerun_on_resume=True)
async def refinement_orchestrator(ctx: Context, node_input: str):
# Step A: Get the initial draft from 'writer' via await ctx.run_node().
# Note: ctx.run_node()'s second argument is positional (there is no `input=` keyword).
current_story = ... # TODO: Call writer with f"Topic: {node_input}"

# Step B: Run the loop (max 3 times)
# 1. Call 'critic' with review = await ctx.run_node(critic, current_story).
# Remember: when output_schema=CritiqueResult is set, ctx.run_node() returns a
# validated Python dict (review["approved"], review["feedback"]), NOT a JSON
# string and NOT a BaseModel instance!
# 2. Check `if review.get("approved"): break`
# 3. Pass `review.get("feedback", "")` along with `current_story` into 'refiner'

# TODO: Implement the bounded for-loop here

return current_story

root_agent = Workflow(
name="EssayRefiner",
edges=[("START", refinement_orchestrator)]
)

Step 3: Run and Testโ€‹

  1. Start the Dev UI from your parent adk-training directory:
    uv run adk web
    (Select essay_refiner from the agent dropdown in the UI).
  2. Observe the Trace: Notice how each call to ctx.run_node() appears in the trace. You can see the story evolving iteration by iteration.

Lab Summaryโ€‹

You have successfully built an iterative system!

  • You used a Dynamic Workflow (@node) to manage execution logic.
  • You used a standard Python loop to implement max_iterations.
  • You learned how to pass data between nodes manually by passing the node's input as the positional second argument to ctx.run_node() (there is no input keyword).

Self-Reflection Questionsโ€‹

  • Why is the max_iterations limit a crucial safety feature for an iterative workflow? What could go wrong without it?
  • In our pattern, the refiner returns a new version of the story. How would you modify the loop to keep track of all versions in the session state?
  • Can you think of another problem, besides writing an essay, that could be solved effectively using a Dynamic Workflow loop?

๐Ÿ” Reference Solution Vaultโ€‹

๐Ÿงช

20: Cyclic Workflows & Loops(Challenge Lab)

Part 3: Multi-Agent Systems โ€ข Module 20