#379Reflexion Retry With FeedbackMedium

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):

  1. Maintain a growing list of feedback strings (initially empty).
  2. For up to max_attempts iterations: call agent(query, feedback); pass the result to critic; if passed, return early; otherwise append the critic's feedback and retry.
  3. If max attempts exhausted, return failure with the last answer.

Input

  • agent(query, feedback) — callable. feedback is a list[str] of prior critique notes.
  • critic(answer) — callable returning (passed: bool, feedback_str: str).
  • querystr, the user's request.
  • max_attemptsint >= 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