Reflection

The reflection pattern has an LLM critique its own output and produce an improved version. It's like having a built-in editor: generate a draft, review it for problems, then rewrite. This loop can repeat until the output meets quality standards.

Reflection loop

Generate, critique, and improve in a loop until quality is sufficient.

Typically 2-3 iterations. After that, improvements plateau and you are just burning tokens. Set a quality threshold or a max iteration limit so the loop always terminates.

patterns/04_reflection.py
python
def generate_content(topic, llm):
    """Generate initial content."""
    prompt = f"Write a short article about: {topic}"
    return llm.generate(prompt).content

def reflect_and_improve(content, llm):
    """Reflect on content and suggest improvements."""
    prompt = f"""
    Review this content critically:
    {content}

    Identify:
    1. What's good about it
    2. What could be improved
    3. Any errors or issues

    Then provide an improved version.
    """
    return llm.generate(prompt).content

# Reflection loop
content = generate_content("AI safety", llm)
for i in range(2):  # 2 rounds of reflection
    content = reflect_and_improve(content, llm)

Two-step reflection: generate content then critique and improve it.

Usually 2-3 rounds is the sweet spot. After that you get diminishing returns and the AI tends to over-edit or flip-flop between changes. Set a maximum iteration count and add a quality threshold so the loop stops when the output is good enough.

AI prompt: Try it with AI

Loading practice…

Quiz: Quiz

Loading practice…

Ordering exercise: Order the reflection loop

Loading practice…

Flashcards: Flashcards

Loading practice…

Reflection gives your agents the ability to self-improve without any human intervention. This generate-critique-improve loop is one of the most powerful patterns you will use. Next, we will give our agents access to external tools so they can interact with the real world.