Reflection
Let agents critique and improve their own responses before delivering them
Reflection makes agents review and refine their own answers, catching mistakes and improving quality automatically.
from praisonaiagents import Agent
agent = Agent(
name="Assistant",
instructions="You are a precise technical writer.",
reflection=True,
)
agent.start("Explain how TCP/IP handshakes work.")The user asks a question; the agent drafts, self-reviews, and refines before returning the final answer.
Quick Start
- Level 1 โ Bool (simplest)
Turn on self-review with a single flag.
python from praisonaiagents import Agent agent = Agent( name="Writer", instructions="You are a technical writer.", reflection=True, ) agent.start("Write clear documentation for a REST API authentication flow.") - Level 2 โ Config class (tune iterations and LLM)
Use
ReflectionConfigto control how many review passes run and which LLM critiques.python from praisonaiagents import Agent, ReflectionConfig agent = Agent( name="Writer", instructions="You are a technical writer.", reflection=ReflectionConfig( min_iterations=1, max_iterations=3, llm="gpt-4o", ), ) agent.start("Write a detailed security review of OAuth 2.0.") - Level 3 โ Config with a custom review prompt
Pass a domain-specific
promptto steer what the self-review checks for.python from praisonaiagents import Agent, ReflectionConfig agent = Agent( name="Reviewer", instructions="You are a code reviewer.", reflection=ReflectionConfig( max_iterations=2, prompt="Evaluate your response for: accuracy, completeness, and clarity. Improve if needed.", ), ) agent.start("Review this Python function for bugs and performance issues.")
How It Works
| Phase | What happens |
|---|---|
| 1. Draft | Agent generates initial response |
| 2. Evaluate | Reflection checks quality against criteria |
| 3. Improve | Agent rewrites based on self-critique |
| 4. Deliver | Final polished response returned to user |
If a reflection response cannot be parsed (for example, an OpenAI structured-output refusal, a content-filter block, or a truncation), the agent retries that pass. Retries are bounded by max_iterations โ after that many failed passes, the agent returns the current draft un-reflected instead of continuing to retry.
Troubleshooting
Persistent parse failures terminate cleanly at max_iterations instead of looping forever.
What you see if reflection cannot parse
- Call the agent
You call
agent.chat("...")on an agent withreflection=True. - Draft and critique
The agent generates a draft, then asks its reflection LLM to critique it.
- Reflection cannot parse
The reflection LLM returns a structured-output refusal (or the response is filtered / truncated), so parsing raises.
- Retry, bounded
The agent logs
Error in parsing self-reflection json ... Retryingand tries again โ up tomax_iterationstimes. - Terminate and return
After
max_iterationsfailed passes, the agent logsMaximum reflection count reached after repeated parse errors, returning current responseand returns the current draft. If a guardrail rejects that draft,chat()returnsNoneand the chat history is rolled back.
Configuration Options
CardFull list of options, types, and defaults โ ReflectionConfig
| Option | Type | Default | Description | |
|---|---|---|---|---|
min_iterations | int | 1 | Minimum reflection passes (always runs at least once) | |
max_iterations | int | 3 | Maximum reflection passes | |
llm | `str \ | None` | None | LLM for reflection (defaults to agent’s LLM) |
prompt | `str \ | None` | None | Custom reflection evaluation prompt |
Common Patterns
Pattern 1 โ Quality-focused writing
from praisonaiagents import Agent, ReflectionConfig
agent = Agent(
instructions="You are a professional copywriter.",
reflection=ReflectionConfig(min_iterations=2, max_iterations=3),
)
response = agent.start("Write an engaging product description for a smart home speaker.")
print(response)Pattern 2 โ Factual accuracy check
from praisonaiagents import Agent, ReflectionConfig
agent = Agent(
instructions="You are a fact-checking assistant.",
reflection=ReflectionConfig(
max_iterations=2,
prompt="Check for factual inaccuracies, missing context, or ambiguous statements.",
),
)
agent.start("Summarize the key events of the Apollo 11 mission.")Best Practices
When to use reflection
Enable reflection for writing tasks, technical explanations, and any output where quality matters more than speed. Skip it for simple lookups, calculations, or real-time applications.
Set max_iterations to control cost
Each reflection pass costs an additional LLM call. Set max_iterations=1 for light review, 2 for thorough review, and only go to 3 for high-stakes content. The default is 3. max_iterations also bounds parse-error retries โ not just “not-yet-good-enough” passes โ so a reflection LLM that keeps refusing can’t loop forever.
Use a custom prompt for domain-specific review
Default reflection uses general quality criteria. Pass a prompt tailored to your domain โ e.g., “Check for HIPAA compliance language” for medical agents or “Verify all code is PEP 8 compliant” for coding agents.