#379Reflexion Retry With FeedbackMediumAgentic AIAsked atOpenAI · Anthropic · Google
Reflexion Retry With Feedback
Background
Reflexion loops a critic over agent outputs and feeds the critique back into the next attempt. The agent gets to "see" its prior failures plus the critique notes, leading to iterative improvement. The standard pattern from the agentic-AI critic + retry lesson.
Problem statement
Implement reflexion_loop(agent, critic, query, max_attempts=3):
- Maintain a growing list of
feedbackstrings (initially empty). - For up to
max_attemptsiterations: callagent(query, feedback); pass the result tocritic; ifpassed, return early; otherwise append the critic's feedback and retry. - If max attempts exhausted, return failure with the last answer.
Input
agent(query, feedback)— callable.feedbackis alist[str]of prior critique notes.critic(answer)— callable returning(passed: bool, feedback_str: str).query—str, the user's request.max_attempts—int >= 1, retry cap.
Output
Returns (passed: bool, attempts: int, final_answer: Any). attempts counts how many times the agent ran.
Examples
Example 1 — passes immediately
Input: critic always passes
Output: (True, 1, ...)
Example 2 — improves after one round
Input: agent returns "v1" first; "v2" once it sees the critic's note
critic passes "v2"
Output: (True, 2, "v2")
Example 3 — exhausts max attempts
Input: critic always fails
Output: (False, max_attempts, last_answer)
Constraints
- Feedback is passed as a list, not concatenated. The agent decides how to integrate.
max_attempts >= 1.- Return the last answer even on failure (useful for debugging).
Notes
- Critic quality dominates. A well-prompted critic that points at specific gaps gives much better retry behaviour than a generic "answer was wrong".
- Cost vs gain. Each retry is another agent + critic call. Production setups cap at 2–3 retries and fall back to human review if still failing.
Python
Loading...
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Worked example: passes on the first attempt
- •Reference case: improves after one round of feedback
- •Sample: exhausts all attempts and returns the last answer