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)


