Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 18

Self-Critique for Autonomous Agents

Recommended resources

Introduction

In our previous lesson, we built a crucial piece of our agent's resilience: dynamic re-planning. By adding a Monitor, we gave the agent the ability to detect when its plan is invalidated by the real world—such as a tool failure or an unexpected outcome—and generate a new plan to adapt. This addresses the problem of failure.

This lesson tackles a different, more subtle challenge: the problem of quality. What if the agent's plan or output is technically successful but not very good? Simply re-planning won't help if the initial strategy itself is suboptimal. To address this, we will implement a self-critique loop, an advanced reasoning pattern where an agent iteratively evaluates and refines its own work. This moves the agent's capability from simply functioning to achieving excellence, a cornerstone of building production-grade systems.


The Principle of Iterative Refinement

Think about how you, as an engineer, approach a complex task like writing a new piece of software or a design document. You rarely produce the final, perfect version in one go. The process is almost always iterative:

  1. Create an initial draft.
  2. Review it for correctness, efficiency, and clarity.
  3. Identify areas for improvement.
  4. Refine the draft based on your critique.
  5. Repeat until the quality meets your standards.

We can engineer this same reflective process into our agents. The core idea is to use LLMs not just to generate content, but also to critique and refine it. This pattern, often called Reflection or Self-Refine, creates a feedback loop that can dramatically improve the quality of an agent's output.

Take a look at these two examples from the foundational "SELF-REFINE" paper.

In both sentiment transfer and code optimization, an initial output is generated. Then, feedback is provided, which is used to create a refined, higher-quality output. This illustrates the core cycle of generate-feedback-refine.

This iterative process is what allows an agent to move beyond a simplistic first attempt and produce more nuanced, correct, and optimized results.


Architecting the Self-Critique Loop

To implement this from first principles, we can model the loop with three distinct conceptual roles, each potentially handled by an LLM call with a specific prompt and purpose.

  1. The Writer: Generates the initial output (e.g., a plan, a report, a piece of code). This is the "drafter."
  2. The Critic: Evaluates the output from the Writer against a set of criteria. It identifies flaws, points out missing details, and checks for correctness. Its sole job is to provide constructive feedback.
  3. The Refiner: Receives the original input, the Writer's draft, and the Critic's feedback. Its task is to synthesize this information and produce an improved, revised output.

This entire process forms a "reflective loop" that can be run multiple times.

This diagram shows the flow of a self-critique loop. The "Writer Agent" creates an initial draft, which is passed to the "Critic Agent" for evaluation. If the quality is insufficient, the "Refiner Agent" uses the critique to generate a new version. This loop continues until a quality threshold is met.

Let's see how to build this architecture from scratch.


From Simple Reflection to Grounded Critique

The most effective critique is one based on objective evidence. A simple, ungrounded critique can sometimes be a matter of one LLM's "opinion" versus another's, leading to minimal or even negative improvement. A truly powerful self-critique system grounds its feedback in external validation.

A fantastic article, "Agentic AI from First Principles: Reflection," demonstrates this perfectly with a text-to-SQL agent. It's an excellent case study for our from-scratch approach.

Agentic AI from First Principles: Reflection | Towards Data Science

This article provides a step-by-step implementation of a reflection loop, clearly showing the difference between ungrounded and grounded critique.

First, read the section on direct generation to understand the baseline. Skim the code under direct generation to see how the initial SQL is created. Next, read the section Adding a reflection step. Pay close attention to the simple_reflection_user_prompt_template. The author finds that this approach, where the LLM critiques its own SQL without new information, provides little benefit. Finally, study the section Reflection with external feedback. This is the key insight. The author modifies the prompt (feedback_reflection_user_prompt_template) to include the actual output from the database (data or an error) and the results of a formatting check. By providing this external, objective feedback, the critique becomes grounded, and the LLM can make meaningful improvements, boosting accuracy from 70% to 85%.

The lesson here is fundamental for building reliable agents. Just as you would use unit test results or a linter's output to inform a code review, our Critic agent becomes far more effective when it receives concrete evidence from the execution environment. The critique is no longer just "I think this is wrong," but "This is wrong, and here is the error message to prove it."


The SELF-REFINE Algorithm

The practical approach we just saw is formalized in the research paper "SELF-REFINE". It provides a generic algorithm that we can adapt.

Reflection Agent From Scratch | Agentic Patterns Series

This video provides a clear, code-oriented walkthrough of the reflection pattern, encapsulating the logic into a reusable Python class.

First, watch the conceptual overview from the beginning. This will solidify your understanding of the generate-reflect loop. Next, see it in action. Watch how an initial merge sort implementation is generated. Then, observe the reflection step, where a separate "Karpathy-like" persona provides a critique. Finally, see how the critique is incorporated to produce a revised version. The video then shows how this entire process is encapsulated in a ReflectionAgent class (view class), which is exactly the kind of robust, reusable component we aim to build.

The core algorithm, which the video implements, relies on a few key components you can build yourself.

[PDF] Iterative Refinement with Self-Feedback - OpenReview

The original paper formalizes the self-refine loop into a clear algorithm.

Read Section 2, "Iterative Refinement with SELF-REFINE", focusing on Algorithm 1 and the descriptions of the Initial generation, FEEDBACK, and REFINE steps. This provides the formal blueprint for the code you would write. Notice the distinct prompts (p_gen, p_fb, p_refine) for each stage, mapping directly to our Writer, Critic, and Refiner roles. Also, note how the history of previous attempts (y0, fb0, ... yt, fbt) is passed to the REFINE step, preventing the agent from repeating mistakes.

The implementation of Algorithm 1 would look conceptually like this in Python:

def self_refine(initial_prompt: str, max_iterations: int = 3) -> str:



    # 1. Initial Generation (Writer)
    current_output = writer_agent.run(initial_prompt)
    



    # Store history of outputs and feedback
    history = [("initial_output", current_output)]

    for i in range(max_iterations):
        print(f"--- Iteration {i+1} ---")
        



        # 2. Feedback (Critic)
        # Note: We can add external feedback here (e.g., from tool execution)
        critique = critic_agent.run(
            prompt=initial_prompt, 
            output_to_review=current_output
        )
        history.append(("critique", critique))
        



        # 3. Stopping Condition
        if "no further improvements needed" in critique.lower():
            print("Critique indicates no further refinement needed. Stopping.")
            break
            



        # 4. Refine (Refiner)
        refined_output = refiner_agent.run(
            prompt=initial_prompt,
            previous_output=current_output,
            critique=critique
        )
        
        current_output = refined_output
        history.append(("refined_output", current_output))

    return current_output




# You would need to implement the run methods for each agent,
# which primarily involve calling an LLM with the correct system and user prompts.

Engineering and Architectural Considerations

As a systems architect, simply implementing the loop isn't enough. You must consider the engineering trade-offs.

  • Cost and Latency: Each step in the loop (Critique, Refine) is an additional LLM call. A 3-iteration loop could mean at least 5 LLM calls instead of 1. This increases both monetary cost and the time-to-first-token for the user. As the "Agentic AI from First Principles" article notes, you must decide if the quality gain justifies the expense.

  • Stopping Conditions: An agent could get stuck in a refinement loop, or the quality might plateau. You need robust stopping conditions. The two most common are:

    1. Max Iterations: A simple circuit breaker (e.g., max_iterations=3) to prevent runaways.
    2. Quality Threshold: The Critic agent can be prompted to output a specific token (e.g., "STOP") or a JSON object with a score/flag indicating that the output is now satisfactory.
  • Actionable Feedback: The quality of the critique is paramount. A vague critique like "make it better" is useless. The Critic's prompt must instruct it to be specific and actionable.

[PDF] Iterative Refinement with Self-Feedback - OpenReview

The paper's analysis section quantifies the importance of high-quality feedback.

Read the subsection The impact of feedback quality in Section 4. Table 2 shows that using specific, actionable feedback significantly outperforms generic feedback or no feedback at all. This reinforces the need for careful prompt engineering in your Critic agent.


Conclusion

Today, we've elevated our agent's reasoning capabilities from reactive adaptation to proactive quality improvement. By implementing a self-critique loop, we've given our agent the ability to reflect on and iteratively refine its own work, a hallmark of advanced intelligence.

Here are your key takeaways:

  • The self-critique pattern consists of a Writer, Critic, and Refiner. This architectural model separates the tasks of generation, evaluation, and improvement into a robust loop.
  • Grounded critique is essential. A Critic agent is most effective when its feedback is based on objective, external information, such as the output of a tool, a database query, or a static code analyzer.
  • The SELF-REFINE algorithm provides a formal blueprint. It defines the iterative process of generating feedback and refining output, which you can implement from first principles using structured prompts.
  • Self-critique involves engineering trade-offs. The significant gains in output quality must be balanced against the increased latency and cost of multiple LLM calls.

We now have an agent that can plan, adapt its plan to failures, and refine its work for quality. But how does an agent decide which strategy to use? When is a single, quick response sufficient, and when is a multi-step, iterative refinement process necessary? In our next lesson, we will explore this decision-making process, learning to distinguish between tasks that require single-pass generation and those that benefit from the more powerful, iterative patterns we've built.