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โ
- Initial Writer Node: An agent that creates the first draft.
- 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")isTrue, or after at most 3 iterations.
- Critic Node (
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,
cdinto theadk-trainingproject 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.
- 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โ
- Start the Dev UI from your parent
adk-trainingdirectory:(Selectuv run adk webessay_refinerfrom the agent dropdown in the UI). - 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 noinputkeyword).
Self-Reflection Questionsโ
- Why is the
max_iterationslimit a crucial safety feature for an iterative workflow? What could go wrong without it? - In our pattern, the
refinerreturns 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โ
Official Solution Vault โ Module 20
Locked Challenge โ Active Pedagogical Socratic Gate
Step 1/3: Question 1 of 1