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 inspectReflection Cycle Inspector
# 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 CycleReflection Pattern Workbench (Actor ➔ Critic ➔ Reviser)
Witness how automated self-critique transforms weak 1-shot drafts into publication-grade outputs
Generates initial fast draft
Grades clarity, metrics & tone
Rewrites draft to fix critiques
"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."
Common Engineering Traps
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.
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.
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.