AI Agents & LLMsMedium
What is reflection or self-critique in agents?
Learning path, stage 4 of 5: Agents, tools and MCP · question 9 of 10Reflection has the model (or a second model) review its own output or trajectory, find mistakes and try again with that feedback. It works best when the feedback is grounded in something real, such as failing tests, errors or a rubric. Pure "are you sure?" self-review can make the model second-guess correct answers.
Variants
- Self-Refine: generate → critique → refine, repeated a few times.
- Reflexion: after a failed attempt, write a short verbal lesson ("I didn't check edge cases"), store it, and use it in the next attempt.
- Evaluator–optimizer: a separate judge prompt or model scores against criteria, and the generator revises until it passes.
When it pays off
- There's a clear quality bar and a way to check it (tests, linters, schema, rubric).
- The first drafts are usually close but imperfect: writing, code, translation.
Watch-outs
- Each round adds cost and latency. Cap the iterations at 2–3.
- A model judging itself shares its own blind spots. Prefer external signals: run the code, check the facts.
Sources
Code example
tsx
1// Grounded reflection: generate code, run tests, feed failures back.2declare function llm(prompt: string): Promise<string>;3declare function runTests(code: string): Promise<{ passed: boolean; failures: string }>;45export async function codeWithReflection(spec: string, maxRounds = 3) {6 let code = await llm(`Write a TypeScript function for this spec. Code only.\n${spec}`);7 const lessons: string[] = [];89 for (let round = 0; round < maxRounds; round++) {10 const result = await runTests(code); // external, objective feedback11 if (result.passed) return { code, rounds: round + 1 };1213 lessons.push(await llm(`Tests failed:\n${result.failures}\nIn one sentence, what was the mistake?`));14 code = await llm(15 `Spec:\n${spec}\n\nPrevious attempt:\n${code}\n\nFailures:\n${result.failures}\n` +16 `Lessons so far:\n- ${lessons.join("\n- ")}\n\nReturn a corrected version. Code only.`,17 );18 }19 throw new Error("Still failing after reflection rounds");20}
To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod @modelcontextprotocol/sdk, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.