Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 45/ 160
03. AI Agents

Reflection

Self-critique loops that catch errors, improve drafts, and reduce silent failures.

IntermediateSelf-Critique · Retry3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

The AI looks over its own work, checks it with a test if possible, and fixes mistakes before handing it in.

Think of it like…

Proofreading your own essay, ideally with a checklist and a spell-checker: you catch typos and missing sections (external checks), but you may not notice a flawed argument you wrote yourself without a second reader.

Where you’ve seen it

A coding agent writes a function, then runs the test suite as a verifier. Two tests fail with a traceback; the agent reads the error, fixes the off-by-one bug, and re-runs: all pass on the second attempt. A separate critic prompt that only "reviewed" the code without running it approved the buggy version, which shows why executable feedback beats self-opinion. The loop is capped at three attempts, after which the agent reports what failed.

Words you’ll hear

Self-critique
The model reviews its own output against a rubric or goal and proposes fixes.
Verifier
An external check producing objective feedback: tests, schema validation, retrieval of evidence.
Reflexion
Storing a short verbal lesson from a failed attempt to guide the next try.
Retry budget
The maximum number of revise-and-check iterations.

Visual diagram

Loading interactive diagram

Theory & deep dive

What reflection can and can't do

Research on intrinsic self-correction (a model revising its answer without any outside feedback) shows mixed or negative results on reasoning tasks: models often can't tell their answer is wrong and may change correct answers to incorrect ones. Reflection works best when feedback carries new information: compiler and test output, a SQL error, a failing schema validation, a retrieval check that finds no supporting evidence, a calculator, a human comment, or a critic given a precise rubric and the original source material.

Good uses: code generation with tests, SQL with execution and row-count sanity checks, structured extraction validated against a schema and business rules, long-form writing against a checklist of requirements, and RAG answers checked for support in the retrieved passages. Poor uses: subtle reasoning errors with no external check, where a second pass mostly reinforces the first.

A rubric-based critic

"Check the draft against these requirements: (1) mentions the refund window, (2) cites a policy section, (3) no promises about timelines. List each requirement as met or not met with a quote, then say REVISE or OK." Specific rubrics beat "is this good?".

Key takeaway: Reflect with external feedback or a precise rubric, not vague self-review.

Designing reflection loops

Structure the loop: generate; run the cheapest effective verifier; if it fails, give the generator the specific feedback (error text, failed requirement) and ask for a targeted fix; repeat up to a small cap (two or three attempts); then stop and either deliver or explain what remains unresolved. Use a separate critic prompt, and for important checks a different (or stronger) model, to avoid the generator rubber-stamping its own output. Keep a short "lessons learned" note across attempts so the same mistake isn't repeated.

Measure it. Compare quality, cost and latency with and without reflection on a labelled set: reflection should raise pass rates enough to justify an extra 1 to 3 model calls. Watch for regressions (a revision that breaks something that worked), reward hacking (the model editing tests to make them pass: protect the tests), and endless loops. For user-facing flows, prefer silent verification with a fallback ("I wasn't able to verify this; here's what I found") over unverified confidence.

Protecting the verifier

In a code-fixing agent, run tests from a read-only directory and forbid edits to test files; otherwise the agent may "pass" by deleting or weakening the failing test.

Key takeaway: Cap retries, separate critic and generator, protect the verifier, and measure the gain.

How it works, step by step

Step 1 of 4
Design

1. Choose the strongest available verifier

Prefer executable or objective checks (tests, schema, evidence lookup); use a rubric critic only for subjective quality.

pytest · JSON Schema · evidence check
Key numbers at this step
Objective
beats opinion

When to use it & trade-offs

What it is

Reflection adds a self-critique step to an agent: after producing a draft, plan or answer, the system evaluates it (against the task, a rubric, or tool feedback), then revises and retries within a limit. Forms include a generator-critic pair (one prompt writes, another reviews), Reflexion-style retries that store the lesson from a failure and use it on the next attempt, and verifier-driven loops where an external check (unit tests, a schema validator, a database query) supplies the feedback. The strongest reflection uses external signals, not just the model's opinion of itself.

Why it matters: Agents fail silently: a plausible but wrong SQL query, code that doesn't compile, a summary that drops a requirement. Reflection can catch many of these before the user sees them, trading extra calls for quality. But models are often poor at finding their own reasoning mistakes without outside feedback, and unbounded reflection loops cost money and sometimes make good answers worse, so design matters.

When to reach for it

  • Code agents running tests
  • SQL agents checking results and row counts
  • RAG answers checked against retrieved evidence

When to avoid or be careful

  • Open-ended "are you sure?" prompts as the only check
  • Unlimited revision loops
  • Letting the agent edit its own tests or validators

Reflection approaches

External verifier loop (tests, validators)
Best for: Code, SQL, structured outputs

Strengths: Objective, reliable feedback.

Watch out: Needs a runnable check.

Generator + rubric critic
Best for: Writing and policy-compliance checks

Strengths: Catches missing requirements.

Watch out: Critic can share the generator's blind spots.

Pure self-reflection
Best for: Light polish only

Strengths: No infrastructure.

Watch out: May not find real errors or may break correct answers.

Interview signals & numbers to know

When this topic comes up

  • “The agent's output looks plausible but is wrong”
  • “Self-correction”
  • “Reflexion”
  • Verifier loops
  • Evaluator–optimizer pattern

Benchmarks & rules of thumb

2 – 3 -
typical retry cap
+1 – 3 calls -
extra model calls per reflection loop
external > intrinsic -
feedback quality ranking

Common mistakes & follow-ups

Common interview mistakes

  • Asking the same model "is this correct?" and trusting a yes.
  • Allowing the code agent to modify the failing test.
  • Running reflection on every request even where first-pass accuracy is already high.

Likely interviewer follow-ups

  • Why is intrinsic self-correction unreliable?
  • How would you add reflection to a SQL-generating agent?
  • How do you decide whether reflection is worth its cost?
Interview tip: Lead with "external feedback beats self-opinion". Then give a code-and-tests example and the retry cap.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Reflection with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Planning
Next topic
Short-term Memory