Mod 3.9Implementing the Reflection Pattern
Level 3›Module 3.9
Level 3: Advanced Patterns & System DesignModule 3.9

Implementing the Reflection Pattern

the Reflection

Level 3 • Advanced Patterns & System Design
Est. ~12 mins
4 Key Topics
🎁 Free Learner Perk

Unlock Verified Certificate & Daily Streak Tracker

Ready to master Implementing the Reflection Pattern? Enable cloud sync to record your daily streak 🔥 and earn your Informational Completion Badge for your study milestones.

Day 1 Streak ActiveFree Completion BadgeSync Laptop & Phone
Module 3.9 • Cognitive Patterns~20 min interactive

Implementing the Reflection Pattern

Allow your agents to look in the mirror. In this lesson, we build a self-correcting Reflection agent in LangGraph: orchestrating Generator, Critic, and Reviser nodes to dramatically improve output accuracy and polish.

1. The Reflection Triad Architecture

Select a role to inspect

Reflection Cycle Inspector

reflection_pattern.py • generator
# 1. INITIAL GENERATOR NODE
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate

generator_llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.7)

def generator_node(state: ReflectionState) -> dict:
    """Generates initial draft based on user request."""
    user_topic = state["topic"]
    prompt = f"Write an initial technical guide on: {user_topic}"
    draft = generator_llm.invoke(prompt).content
    return {"draft": draft, "revision_count": 0}

2. Interactive Reflection Engine Studio

Generator-Critic-Reviser Live Cycle

Reflection Pattern Workbench (Actor ➔ Critic ➔ Reviser)

Witness how automated self-critique transforms weak 1-shot drafts into publication-grade outputs

"Write a concise executive briefing on why our database migrated from MongoDB to PostgreSQL."
Node 1generator_actor

Generates initial fast draft

Node 2evaluator_critic

Grades clarity, metrics & tone

Node 3reviser_polisher

Rewrites draft to fix critiques

Iteration 1 (Raw 1-Shot Draft)

"We moved to PostgreSQL because MongoDB was bad for ACID transactions. Postgres is relational and has SQL which our team likes. It also supports JSONB so we don't lose NoSQL capabilities. The migration was good."

Iteration 2 (Reflected & Polished)
Awaiting reflection feedback...
📌 Model Persona Separation: Never ask the same model prompt to 'write and critique simultaneously'. LLMs suffer from cognitive confirmation bias on their own text. Splitting the persona into a Generator node and a distinct Critic node yields 40% higher defect detection!

Common Engineering Traps

TRAP #1: The Hyper-Critical Perfectionist Loop

An overly aggressive critic prompt can find stylistic nits on every single iteration, causing the reflection cycle to loop indefinitely until max tokens are burned. Always enforce a hard ceiling on revision_count <= 3.

TRAP #2: Vague Non-Actionable Critiques

If the critic says "Make it better and more professional", the reviser produces random semantic variations without actually fixing flaws. Force the critic to use a structured schema with itemized defect bullets.

Key Architectural Takeaways

  • 1.Decoupled Cognitive Roles: Isolating drafting from evaluating breaks the LLM's natural confirmation bias, yielding higher quality.
  • 2.Strict Structured Feedback: Pydantic output parsing for the critic ensures the reviser receives precise, itemized instructions.
  • 3.Guaranteed Convergence: Enforcing both quality score criteria AND maximum revision ceilings ensures reliable, bounded latency in production.
Up Next • Module 3.10

Managing Conversation History in a Database

In-memory state vanishes on server restart. Learn how to connect LangGraph to PostgreSQL and Redis checkpointers for durable multi-tenant session persistence.

Continue to Module 3.10