897. Reflexion retry loop with episodic memory
Why it matters Reflexion-style retries (try, critique, retry with notes) are in most coding agents. The memory window decides whether the agent can learn across tries.
Paper: "Reflexion: Language Agents with Verbal Reinforcement Learning", Shinn et al., 2023 (NeurIPS 2023), arXiv 2303.11366.
A Reflexion agent tries a task, an evaluator checks the result, and on failure the agent writes a short self-reflection into memory before the next try. Here the actor is a lookup table so the run is deterministic.
Write reflexion_run(answers, expected, max_trials, memory_size).
- answers: dict mapping an int k to the answer the actor gives when its memory holds k reflections. If k is not a key, use the value for the largest key below k (key 0 always exists).
- For trial i = 1 .. max_trials: get the answer for k = len(memory). If it equals expected, stop with success. Otherwise append the string "trial i: answer <answer> was wrong" (with i and the answer filled in, using str(answer)) to memory, and if memory is longer than memory_size, drop the oldest entries.
Inputs: max_trials >= 1, memory_size >= 0 (0 means nothing is remembered).
Return a dict {"success": bool, "trials": number of trials run, "answers": list of answers in order, "memory": final list of reflections}.
def reflexion_run(answers, expected, max_trials, memory_size)Example 1
Input: reflexion_run({0: 'A', 1: 'B', 2: 'C'}, 'C', 5, 3)
Output: {'success': True, 'trials': 3, 'answers': ['A', 'B', 'C'], 'memory': ['trial 1: answer A was wrong', 'trial 2: answer B was wrong']}
Example 2
Input: answers = {0: 'A', 1: 'B', 2: 'C'}, expected = 'C', max_trials = 5, memory_size = 1
Output: {'success': False, 'trials': 5, 'answers': ['A', 'B', 'B', 'B', 'B'], 'memory': ['trial 5: answer B was wrong']}
Example 3
Input: answers = {0: 42}, expected = 42, max_trials = 3, memory_size = 2
Output: {'success': True, 'trials': 1, 'answers': [42], 'memory': []}
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 5 tests to be accepted.
Hint 1
Look up the answer by the current memory length, falling back to the largest smaller key.
Hint 2
On failure, append the reflection, then trim to memory_size.
Hint 3
Return as soon as an answer matches.
Common mistakes
- Trimming before appending.
- Counting trials from 0.
- Slicing
memory[-0:], which keeps everything instead of nothing.
Understand the idea
The agent improves only through what it remembers. With a memory of 3 it reaches the answer that needs 2 reflections on trial 3. With a memory of 1 it can never hold 2 reflections, so it keeps giving B and fails. This is why real agents summarise old reflections instead of only keeping the last one.
Shapes and data flow
Dict and scalars in, dict out.