0
Phase 9

Reflection Loop

~3 min read

Concept & How It Works

    Why Does It Exist?

    Agents make mistakes: wrong tool arguments, misinterpreted results, incomplete answers. Without reflection, these errors propagate to the final output. Reflection adds a self-correction loop — the agent reviews its work before returning to the user.

    Real-World Analogy

    Reflection is like a writer reviewing their draft before submitting — catching typos, logical gaps, and unclear sections that seemed fine during writing.
    Loading diagram...

    Visual Workflows

    What is Reflection Loop?

    Loading diagram...

    Example

    Scenario

    Agent drafts email to client. Reflection: 'The email mentions Q3 revenue but I never queried the database for Q3 data — I hallucinated the number.' Agent re-enters loop, queries DB, drafts corrected email.

    Solution

    In Agent Design Patterns, apply Reflection Loop to this scenario: Agent drafts email to client. Identify the inputs, run the technique, validate the output, and note one thing you would monitor in production.

    Practice Task

    Do this before moving to the next module — reading alone is not enough.

    Open the Code Walkthrough below and run it locally. Change one parameter related to Reflection Loop (e.g. model, temperature, top_k, or tool name), observe the difference in output, and write 2–3 sentences explaining what changed.

    Code Walkthrough

    Highlighted lines show where Reflection Loop happens in the code.

    Reflection Loop
    1REFLECTION_PROMPT = """Review this agent output for errors:  # key line for Reflection Loop2
    3Task: {task}4Agent actions: {actions}5Draft answer: {draft}6
    7Check:81. Is every claim supported by tool results?92. Are there hallucinated facts?103. Is the task fully completed?114. What should be improved?12
    13Return JSON: {"pass": bool, "issues": [...], "suggestion": "..."}"""14
    15def reflect(task, actions, draft) -> dict:  # define a reusable function16    response = client.chat.completions.create(  # call the API17        model="gpt-4o",18        messages=[{"role": "user", "content": REFLECTION_PROMPT.format(  # key line for Reflection Loop19            task=task, actions=actions, draft=draft)}],20        response_format={"type": "json_object"},21        temperature=0,22    )23    return json.loads(response.choices[0].message.content)  # return the result

    Commands to Remember

    Commands to Remember

    • pip install langchain langchain-openai # patterns work with any LLM SDK
    • python react_agent.py # run a ReAct-style agent loop
    • pip install tenacity # retry logic for agent steps

    Common Mistakes

    • Reflection on every task — unnecessary latency and cost
    • Self-critique only — misses errors the same model makes
    • Not storing reflection insights for future tasks
    • Infinite reflection loops — need max retry limit
    • Reflecting on format but not factual accuracy

    Cheat Sheet

    Quick recap — the most important points from this module.

    Cheat Sheet

    quick ref
    • Review before returning
    • Self-critique = same LLM
    • Verifier = separate LLM
    • Skip for simple tasks
    • Store lessons in memory
    • Re-enter loop on fail