跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客工具镜像开源精选AI社区
我的书AI 学习话题UI配色美学关于
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
博客列表
PythonAI算法

Reflexion 框架下 ReflectionAgent 工作流详解

Reflexion 框架通过引入自我反思机制改进 LLM Agent 的推理能力。文章分析了 ReactReflectAgent 的工作流程,包括 Prompt 设计、迭代逻辑及反思策略实现。重点探讨了如何在 ReAct 基础上增加记忆层防止循环推理,并讨论了 is_correct() 判断在不同任务场景下的适用性。此外,还补充了工程化落地中的 Token 预算控制、温度参数调整及验证机制优化等实践建议,展示了如何通过多次尝试和反思优化 Agent 的输出结果。

追风少年发布于 2025/2/6更新于 2026/12/2132 浏览
Reflexion 框架下 ReflectionAgent 工作流详解

Reflexion 框架下 ReflectionAgent 工作流详解

本文将深入探讨在 ReactAgent 上构建反思工作流的具体实现,重点分析 Reflexion 框架的核心机制、Prompt 设计策略以及工程化落地中的关键问题。

1. 如何设计反思

设计反思机制通常遵循'先 Prompt 设计,后流程设计'的原则。

1.1 Prompt 设计

与 ReAct 的 Prompt 设计类似,首先需要明确任务说明(给予强烈鼓励),然后定义任务的输入和输出,并提供高质量的样例。对于反思 Agent 来说,其核心输入是之前的尝试记录。

REFLECT_INSTRUCTION = """
你是一个能够通过自我反思来改进的高级推理代理。你将获得之前的推理测试流程,在之前的测试中你尝试访问 Docstore API 并回答了问题。由于你猜错了答案(使用了 Finish[<answer>]),或者用完了设定的推理步骤数,你未能成功回答问题。诊断失败的可能原因,并制定一个新的、简明的高级计划,旨在减轻同样的失败。要求必须使用完整的语句来回复。
这里有一些例子:
{examples}
之前的尝试:
问题:{question}{scratchpad}
反思:
"""

我认为一个好的示例同样重要,LLM 会按照你的设想进行回复。以下是具体的 Few-Shot 示例结构:

之前的尝试:
Question: The Rome Protocols were signed by three Prime Ministers one of which was assassinated as part of what?
Thought 1: I need to search Rome Protocols, find the three Prime 
....
Action 3: Finish[World War II]

反思:I searched one of the prime ministers involved in the signing, then attemted to answer right away. I should have searched each of the prime ministers, then looked up 'death' on each of their pages in order to get more information before answering.

1.2 流程设计

Reflect 机制也使用了 Scratchpad 来记录反思过程,并在 ReAct 的 Prompt 中加入了 reflection 字段。这有助于防止 Thought 在根据反思结果推理时陷入循环,反复推导出同一结果,相当于给 ReAct 加了一层记忆。接下来,我们深入 Reflexion 的 ReactReflectAgent 查看反思具体实现。

2. ReactReflectAgent.run 实现细节

在 ReactReflectAgent 的 run 方法中调用了 ReactAgent.run(self, reset) 进行迭代。上文我们有详细描述过 ReactAgent.run 这一迭代 TAO (Thought-Action-Observation) 的过程。在 ReactAgent 多次迭代仍无法获取正确答案时候,进入反思流程。

注意:在实际应用的时候,问答类任务往往无法知道结果到底正确与否,并不能知晓 self.is_correct(),这像是泄露答案一样。除非让用户主动参与进行互动表示不正确,但如果用户都知道了,还问你干啥呢?但如果是编程任务,可以设定输入输出并通过编写测试用例来对程序进行测试,从而确认结果是否正确。

def run(self, reset=True, reflect_strategy: ReflexionStrategy = ReflexionStrategy.REFLEXION) -> None:
    # 如果任务结束或停止,且未通过验证,则触发反思
    if (self.is_finished() or .is_halted())   .is_correct():
        .reflect(reflect_strategy)

    
    ReactAgent.run(, reset)
self
and
not
self
self
# 继续执行标准的 ReAct 迭代
self

在前文中我们最后有给出整个流程,设置 5 次尝试来调用 ReactReflectAgent.run。

n = 5
for i in range(n):
    for agent in [a for a in agents if not a.is_correct()]:
        agent.run(reflect_strategy=strategy)
        print(f'Answer: {agent.key}')

所以当 ReactAgent.run 执行完 5 次 step 结束之后,在外部的 for 循环 5 次尝试,会再次进入 ReactReflectAgent.run 方法。此次会判定出该 agent 的 self.is_finished() or self.is_halted() 就是 true 了。至于 self.is_correct(),只能说是提前知晓答案正确与否。假设 self.is_correct() 为 false,执行 reflect(reflect_strategy)。

def reflect(self, strategy: ReflexionStrategy) -> None:
    if ... 
    elif strategy == ReflexionStrategy.REFLEXION:
        # 将反思内容追加到列表中
        self.reflections += [self.prompt_reflection()]
        # 格式化反思字符串以便后续 Prompt 填充
        self.reflections_str = format_reflections(self.reflections)
    ....

def prompt_reflection(self) -> str:
    return format_step(self.reflect_llm(self._build_reflection_prompt()))

反思策略为 REFLEXION,构建反思 Prompt。注意这里将提取的 reflection 结果保存到 list self.reflections,并且将结果格式化为 reflection_str,在 ReAct 中构建 Prompt 会填入该反思结果,从而避免陷入相同的推理中,可以认为 self.reflections 就是 reflect 的 scratchpad。

其中 reflect_prompt 定义如下,然后给定一些 examples,并将之前错误的问题和推理步骤附上来:

REFLECT_INSTRUCTION = """You are an advanced reasoning agent that can improve based on self refection. You will be given a previous reasoning trial in which you were given access to an Docstore API environment and a question to answer. You were unsuccessful in answering the question either because you guessed the wrong answer with Finish[<answer>], or you used up your set number of reasoning steps. In a few sentences, Diagnose a possible reason for failure and devise a new, concise, high level plan that aims to mitigate the same failure. Use complete sentences.  
Here are some examples:
{examples}
Previous trial:
Question: {question}{scratchpad}
Reflection:"""

其中 reflect_examples 就是 REFLECTIONS 定义的 Prompt,该 Prompt 定义了两个案例:

REFLECTIONS = """
Previous Trial:
Question: Kam Heskin plays Paige Morgan in a 2004 film directed by who?
...
Observation 6: ....
Reflection: I got stuck in a loop where I kept trying to search 'The Prince & Me (2004 film)' but the page could not be found. Instead I should have tried to search the similar results that had a similar name to see and they were made in 2004.
"""

既然 Prompt 已经定义好,接下来就是调用 self.reflect_llm(self._build_reflection_prompt()),LLM 就会按照给定的 example 来反思并给出新的思路。

示例反思回复:I got stuck on the first search and kept trying to find information about VIVA Media AG, when I should have checked the similar results instead. The similar results that came up were not useful either, as they did not talk about a name change. I should have tried another initial search term instead of persevering with a dead end.

其中 reflect_llm 在初始化的时候,没有设定遇到换行停止,max token 也增加到 250,是因为反思不需要严格格式执行,并且应该让其尽可能的反思出具体的步骤。

AnyOpenAILLM(
   temperature=0,
   max_tokens=250,
   model_name="gpt-3.5-turbo",
   openai_api_key="sk"),
)

之后,使用 format_reflections 将反思的结果格式化。header + 'Reflections:\n- ' + '\n- '.join([r.strip() for r in reflections])。其中 header 为固定字符串,最终格式化后的输出就是:

You have attempted to answer following question before and failed. The following reflection(s) give a plan to avoid failing to answer the question in the same way you did previously. Use them to improve your strategy of correctly answering the given question.
Reflections:
I got stuck on the first search and kept trying to find information about VIVA Media AG, when I should have checked the similar results instead. The similar results that came up were not useful either, as they did not talk about a name change. I should have tried another initial search term instead of persevering with a dead end.

所以 ReactAgent.run 的 Prompt 会填充该段反思内容,重新迭代 TAO 的流程。由于反思尝试设置的是 5 次,我们看到最终输出的反思条例都装载到 Prompt 中,以便后面的推理能够吸取前面的教训。

Solve a question answering task with interleaving Thought, Action, Observation steps. Thought can reason about the current situation, and Action must be one of the three types: 
...
(END OF EXAMPLES)
You have attempted to answer following question before and failed....
Reflections:
- The search results ...
- I should have read the question more carefully and noticed that it ...
Question: {question}{scratchpad} 

3. 实践建议与注意事项

在实际部署 Reflexion 框架时,除了代码逻辑的实现,还需要关注以下几个工程化细节:

  1. Token 预算控制:随着反思次数增加,Prompt 长度会线性增长。需要监控上下文窗口,必要时截断最早的反思记录,保留最近的反思信息。
  2. 温度参数调整:反思阶段建议使用较低的温度(如 0),以确保反思内容的确定性和一致性;而主推理阶段可以适当提高温度以增加探索性。
  3. 验证机制优化:对于无法自动验证正确性的场景(如开放式问答),可以考虑引入外部校验工具或人类反馈回路(Human-in-the-loop)作为 is_correct 的判断依据。
  4. 循环检测:虽然反思机制旨在打破循环,但在极端情况下仍需加入最大步数限制,防止 Agent 在错误的反思路径上无限消耗资源。

4. 总结

Reflexion 是在 React 5 轮 TAO 迭代之后的总结和反思,给出下一步的思考方向。同时尝试多次反思,并将每次反思的内容给到 LLM,使之避免再次走入已经反思过的方向。综合来看,反思 Reflect 是一种通过自动化迭代 LLM,不断试错,从而得出更好的结果的思路。

比如在编写代码的任务中,通过 LLM 编写代码,再编写测试代码,这样我们就能够通过 TAO 得到编写的代码是否正确,从而决定是否需要再次循环 TAO 或者进一步的反思来优化提升代码。这种机制显著提升了复杂任务下的成功率,是构建可靠 AI Agent 的关键技术之一。

目录

  1. Reflexion 框架下 ReflectionAgent 工作流详解
  2. 1. 如何设计反思
  3. 1.1 Prompt 设计
  4. 1.2 流程设计
  5. 2. ReactReflectAgent.run 实现细节
  6. 3. 实践建议与注意事项
  7. 4. 总结

更多推荐文章

查看全部
  • Neo4j 访问方式实战:嵌入式模式与远程 Server 对比及 Java 示例
  • AI 领域新概念 Skill 的核心原理与工作机制
  • Git 基础:认识三大区域与文件修改提交流程
  • 基于 DeepSeek 和 Cursor 构建智能代码审查工具:AI 编程实践
  • AI 产品经理入门指南与进阶路线图
  • Python wxauto 安装失败解决方案
  • Neo4j 图数据库入门与 Python 集成实战
  • MySQL 表约束核心指南:从基础到外键实战
  • Chambolle-Pock 算法在医学影像重建中的应用
  • Linux 系统安装、卸载与更新 Node.js 及 Git 指南
  • 文心一言多线程批量写作辅助工具开发实践
  • AI 面试辅助工具即答侠技术架构与功能解析
  • Blazor + .NET MAUI 跨平台桌面应用开发实战
  • Java 基于 Tomcat 9 与 Flexmark 实现 Markdown 中 Mermaid 图表渲染
  • Naiz AI:从语义到像素,全链路重构视频数字孪生
  • 金仓 KES V9 兼容 MongoDB 的运维替代思路
  • Python EXE 解包工具使用指南与逆向工程解析
  • PostgreSQL 高可用实战:主从流复制搭建与配置详解
  • OpenClaw 钉钉群聊多机器人配置指南
  • Python 环境下安装 pydbg 及依赖库配置指南

相关免费在线工具

  • 加密/解密文本

    使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online

  • RSA密钥对生成器

    生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online

  • Mermaid 预览与可视化编辑

    基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online

  • 随机西班牙地址生成器

    随机生成西班牙地址(支持马德里、加泰罗尼亚、安达卢西亚、瓦伦西亚筛选),支持数量快捷选择、显示全部与下载。 在线工具,随机西班牙地址生成器在线工具,online

  • Gemini 图片去水印

    基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online

  • curl 转代码

    解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online