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.

python
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.

Diagram

Reflection Flow

Needs improvement

Satisfied

๐Ÿ“ Draft Response

๐Ÿ” Self-Review

โœ๏ธ Refine

โœ… Final Response

Quick Start

  1. 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.")
  2. Level 2 โ€” Config class (tune iterations and LLM)

    Use ReflectionConfig to 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.")
  3. Level 3 โ€” Config with a custom review prompt

    Pass a domain-specific prompt to 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

Diagram
ReflectionAgentUserReflectionAgentUserloop[Reflection iterations]RequestGenerate initial responseEvaluate response qualityCritique and suggestionsImprove responsePolished final response
PhaseWhat happens
1. DraftAgent generates initial response
2. EvaluateReflection checks quality against criteria
3. ImproveAgent rewrites based on self-critique
4. DeliverFinal 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

  1. Call the agent

    You call agent.chat("...") on an agent with reflection=True.

  2. Draft and critique

    The agent generates a draft, then asks its reflection LLM to critique it.

  3. Reflection cannot parse

    The reflection LLM returns a structured-output refusal (or the response is filtered / truncated), so parsing raises.

  4. Retry, bounded

    The agent logs Error in parsing self-reflection json ... Retrying and tries again โ€” up to max_iterations times.

  5. Terminate and return

    After max_iterations failed passes, the agent logs Maximum reflection count reached after repeated parse errors, returning current response and returns the current draft. If a guardrail rejects that draft, chat() returns None and the chat history is rolled back.


Configuration Options

Card

Full list of options, types, and defaults โ€” ReflectionConfig

OptionTypeDefaultDescription
min_iterationsint1Minimum reflection passes (always runs at least once)
max_iterationsint3Maximum reflection passes
llm`str \None`NoneLLM for reflection (defaults to agent’s LLM)
prompt`str \None`NoneCustom reflection evaluation prompt

Common Patterns

Pattern 1 โ€” Quality-focused writing

python
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

python
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.


Related