在这里插入图片描述

肖哥弹架构 跟大家“弹弹” 大模型Agent 设计与实战应用,需要代码关注

欢迎 关注,点赞,留言。

关注公号Solomon肖哥弹架构获取更多精彩内容

历史热点文章

⚠️ 原创不易 搬运必究

Reflexion框架通过"生成→评估→改进"的闭环机制,解决传统AI单轮问答在准确性、完整性和实用性方面的局限。本文完整解析其工作代理、反射代理、备用LLM的三角色协作架构,通过RAG技术详解的实际案例,展示从初稿到最终答案的完整多轮迭代过程。涵盖模板系统、解析器机制、控制流逻辑等核心技术细节,帮助构建具备自我修正能力的高质量AI问答系统。

一、 Reflexion技术背景

  • 单轮问答的局限:一次生成常出现事实偏差、覆盖不全、表达不清等问题,且难以自我修正。
  • 人类审稿的启发:先产出,再按标准审视与修改,逐轮趋近高质量答案。
  • 工程化需求:需要可控的轮次上限、结构化的评估/改进回路、可观测与可恢复。

Reflexion 通过“工作代理 → 反射代理 → 改进”的闭环,让答案在若干轮内可预测地提升质量,同时与 OxyGent 的权限、追踪、SSE、断点等机制协同。

1. Reflexion设计思路

在这里插入图片描述

二、 业务数据快照:从输入到最终答案(含多轮反射)

0) 用户输入

{
  "oxy_request": {
    "caller": "user",
    "callee": "reflexion_flow",
    "arguments": {
      "query": "解释 RAG 的核心流程,并给出一个简短示例"
    }
  }
}

1) 第1轮:工作代理 → 反射代理 → (可能)改进

{
  "worker_call": { "callee": "worker_agent", "arguments": { "query": "解释 RAG..." } },
  "worker_response": { "output": "RAG 是... (初稿)" },

  "evaluation_query": {
    "template": "评估模板(准确性/完整性/清晰度/相关性/实用性)...",
    "filled": "原始问题: 解释 RAG...\n答案: RAG 是..."
  },
  "reflexion_call": { "callee": "reflexion_agent", "arguments": { "query": "[filled]" } },
  "reflexion_response": {
    "output": {
      "is_satisfactory": false,
      "evaluation_reason": "缺少检索-重写-生成的细节",
      "improvement_suggestions": "补充检索召回与重写步骤,并提供代码示例"
    }
  },

  "improvement_query": {
    "template": "改进模板",
    "filled": "[加入改进建议及上一轮答案]"
  }
}

2) 第2轮:根据改进建议再次生成与评估

{
  "worker_response": { "output": "RAG 流程:检索->重写->生成;示例: ... (改进稿)" },
  "reflexion_response": {
    "output": {
      "is_satisfactory": true,
      "evaluation_reason": "覆盖要点且示例清晰",
      "improvement_suggestions": ""
    }
  },
  "final_oxy_response": {
    "state": "COMPLETED",
    "output": "通过 2 轮反射优化后的最终答案:\n\nRAG 流程...",
    "extra": { "reflexion_rounds": 2, "final_evaluation": { "is_satisfactory": true } }
  }
}

若达到 max_reflexion_rounds 仍不满意,将汇总最后一次答案与评估理由,请备用 LLM 收尾。

三、 Reflexion 思路与步骤

  • 核心思想:生成→评估→改进的闭环迭代,用结构化评估信号指导后续改写。
  • 参与角色:
    • worker_agent:给出当前答案草稿;
    • reflexion_agent:按模板评估答案(结构化输出 ReflectionEvaluation);
    • 备用 LLM:在轮次用尽时做“结合反馈的最终回答”。
  • 数据与状态:
    • original_query/current_query:原始/当前用于生成的提示;
    • current_answer:最新草稿;
    • evaluation:is_satisfactory/evaluation_reason/improvement_suggestions
  • 流程:
    1. 调用 worker 生成答案并解析;
    2. 按评估模板调用 reflexion 得到 ReflectionEvaluation
    3. 若满意则完成;否则根据建议构造改进提示进入下一轮;
    4. 超过 max_reflexion_rounds 用备用 LLM 收尾。

四、 Reflexion流程

用户 Reflexion流程 工作代理 反射代理 备用LLM 发起请求(query) 初始化(current_query=original_query) call(worker_agent, current_query) 返回答案(current_answer) call(reflexion_agent, evaluation_template.format(query, answer)) 返回ReflectionEvaluation COMPLETED(最终答案 + 评估摘要) 构造 improvement_query(模板 + 建议 + 上一稿) current_query = improvement_query alt [答案满意] [需要改进] loop [迭代至满意或达到上限] call(llm_model, 汇总最后答案与评估) 返回最终总结 COMPLETED(最终总结 + reached_max_rounds) alt [达到最大轮次] 用户 Reflexion流程 工作代理 反射代理 备用LLM

五、Reflexion架构与落地

1. 公开 API 与配置

  • 入口:Reflexion._execute(oxy_request) -> OxyResponse
  • 关键字段:max_reflexion_roundsworker_agentreflexion_agentllm_model
  • 解析扩展:func_parse_worker_responsefunc_parse_reflexion_responsepydantic_parser_reflexion
  • 模板:evaluation_templateimprovement_template

2. 角色契约

  • Worker:输入 query,输出可读答案文本;解析器可归一化。
  • Reflexion:输入 evaluation_query,输出 ReflectionEvaluation(结构化)。
  • LLM 收尾:输入“原问题+最新答案+评估理由”,输出最终总结。

3. 错误与超时策略

  • OxyRequest.call 统一处理:超时→FAILED,异常→FAILED,权限不足→SKIPPED。
  • 可选重试:参考 OxyRequest.retry_execute 的语义。

4. 可观测性与恢复

  • 建议记录:每轮的 current_answer 摘要与 evaluation;trace/node 消息写 ES。
  • 断点恢复:可基于 from_trace_id/restart_node_id 与历史节点输出,恢复到上一轮继续。

5. 性能与安全

  • 控制轮次与模板长度,避免提示过长;current_answer 做摘要。
  • 权限隔离评估代理,评估模板避免泄露敏感上下文。

6. 端到端最小示例

flow = Reflexion(worker_agent="worker_agent", reflexion_agent="reflexion_agent", max_reflexion_rounds=3)
resp = await flow.execute(OxyRequest(caller="user", callee="reflexion_flow", arguments={"query": "解释 RAG"}))

7. 测试清单

  • 工作代理多样输出能被解析;
  • 评估解析文本/Pydantic 两条路径;
  • 满意/不满意/上限收尾三分支覆盖;
  • 超时/异常/权限;SSE 流与取消;多会话并发不串线。

六、Reflexion与LLM 交互详解

详细展示 Reflexion 流程中每一步与大模型交互的完整请求与响应内容,分解其工作原理。

1. 场景示例

用户输入问题

"解释 RAG 的核心流程,并给出一个简短示例"

配置参数

  • max_reflexion_rounds = 3(最多迭代 3 轮)
  • worker_agent = "worker_agent"(负责生成答案)
  • reflexion_agent = "reflexion_agent"(负责评估答案)
  • llm_model = "gpt-4"(备用 LLM 用于最终收尾)

第 1 轮迭代
1.1 Worker Agent 调用(生成初稿)

请求构造

# 代码位置:_execute 方法中
worker_response = await oxy_request.call(
    callee=self.worker_agent,  # "worker_agent"
    arguments={"query": current_query}
)

完整请求内容

{
  "callee": "worker_agent",
  "caller": "reflexion_flow",
  "arguments": {
    "query": "解释 RAG 的核心流程,并给出一个简短示例"
  },
  "trace_id": "trace_abc123",
  "node_id": "node_worker_1"
}

LLM 实际收到的 Prompt(由 worker_agent 内部构造):

System: You are a helpful AI assistant.

User: 解释 RAG 的核心流程,并给出一个简短示例

完整响应内容

{
  "state": "COMPLETED",
  "output": "RAG(Retrieval-Augmented Generation)是一种结合检索和生成的技术。它的核心流程包括:\n\n1. 用户提出问题\n2. 系统从知识库中检索相关文档\n3. 将检索到的文档和问题一起输入到生成模型\n4. 生成最终答案\n\n这种方法可以让模型基于外部知识生成更准确的答案。",
  "extra": {
    "model": "gpt-4",
    "tokens": 156
  }
}

解析后的答案(通过 func_parse_worker_response):

current_answer = """RAG(Retrieval-Augmented Generation)是一种结合检索和生成的技术。它的核心流程包括:

1. 用户提出问题
2. 系统从知识库中检索相关文档
3. 将检索到的文档和问题一起输入到生成模型
4. 生成最终答案

这种方法可以让模型基于外部知识生成更准确的答案。"""

1.2 Reflexion Agent 调用(评估答案)

请求构造

# 步骤1: 填充评估模板
evaluation_query = self.evaluation_template.format(
    query=original_query, 
    answer=current_answer
)

# 步骤2: 如果使用 Pydantic 解析器,加上格式指令
if self.pydantic_parser_reflexion:
    evaluation_query = self.pydantic_parser_reflexion.format(evaluation_query)

# 步骤3: 调用反射代理
reflexion_response = await oxy_request.call(
    callee=self.reflexion_agent,
    arguments={"query": evaluation_query}
)

完整请求内容

{
  "callee": "reflexion_agent",
  "caller": "reflexion_flow",
  "arguments": {
    "query": "Please evaluate the quality of the following answer:\n\nOriginal Question: 解释 RAG 的核心流程,并给出一个简短示例\n\nAnswer: RAG(Retrieval-Augmented Generation)是一种结合检索和生成的技术。它的核心流程包括:\n\n1. 用户提出问题\n2. 系统从知识库中检索相关文档\n3. 将检索到的文档和问题一起输入到生成模型\n4. 生成最终答案\n\n这种方法可以让模型基于外部知识生成更准确的答案。\n\nPlease evaluate based on these criteria:\n1. Accuracy: Is the information correct and factual?\n2. Completeness: Does it fully address the user's question?\n3. Clarity: Is it well-structured and easy to understand?\n4. Relevance: Does it stay focused on the user's needs?\n5. Helpfulness: Does it provide practical value to the user?\n\nReturn your evaluation in the following format:\n{\n  \"is_satisfactory\": boolean,\n  \"evaluation_reason\": \"string\",\n  \"improvement_suggestions\": \"string\"\n}\n\nYour response must be valid JSON matching the schema above."
  },
  "trace_id": "trace_abc123",
  "node_id": "node_reflexion_1"
}

LLM 实际收到的 Prompt(由 reflexion_agent 内部构造):

System: You are an expert evaluator responsible for assessing answer quality.

User: Please evaluate the quality of the following answer:

Original Question: 解释 RAG 的核心流程,并给出一个简短示例

Answer: RAG(Retrieval-Augmented Generation)是一种结合检索和生成的技术。它的核心流程包括:

1. 用户提出问题
2. 系统从知识库中检索相关文档
3. 将检索到的文档和问题一起输入到生成模型
4. 生成最终答案

这种方法可以让模型基于外部知识生成更准确的答案。

Please evaluate based on these criteria:
1. Accuracy: Is the information correct and factual?
2. Completeness: Does it fully address the user's question?
3. Clarity: Is it well-structured and easy to understand?
4. Relevance: Does it stay focused on the user's needs?
5. Helpfulness: Does it provide practical value to the user?

Return your evaluation in the following format:
{
  "is_satisfactory": boolean,
  "evaluation_reason": "string",
  "improvement_suggestions": "string"
}

Your response must be valid JSON matching the schema above.

完整响应内容

{
  "state": "COMPLETED",
  "output": "{\n  \"is_satisfactory\": false,\n  \"evaluation_reason\": \"答案解释了 RAG 的基本概念,但缺少关键技术细节。流程过于简化,没有说明检索的具体方法(如向量检索、BM25等),也没有提供用户要求的代码示例。完整性和实用性不足。\",\n  \"improvement_suggestions\": \"1. 详细说明检索步骤,包括向量化、相似度计算等技术细节\\n2. 补充一个具体的代码示例,展示如何实现简单的 RAG 系统\\n3. 说明检索到的文档如何与 prompt 结合输入到 LLM\"\n}",
  "extra": {
    "model": "gpt-4",
    "tokens": 203
  }
}

解析后的评估结果(通过 func_parse_reflexion_response):

evaluation = ReflectionEvaluation(
    is_satisfactory=False,
    evaluation_reason="答案解释了 RAG 的基本概念,但缺少关键技术细节。流程过于简化,没有说明检索的具体方法(如向量检索、BM25等),也没有提供用户要求的代码示例。完整性和实用性不足。",
    improvement_suggestions="1. 详细说明检索步骤,包括向量化、相似度计算等技术细节\n2. 补充一个具体的代码示例,展示如何实现简单的 RAG 系统\n3. 说明检索到的文档如何与 prompt 结合输入到 LLM"
)

判断结果is_satisfactory = False,需要进入第 2 轮改进。


1.3 构造改进 Query(准备第 2 轮)

代码逻辑

if evaluation.improvement_suggestions:
    current_query = self.improvement_template.format(
        original_query=original_query,
        improvement_suggestions=evaluation.improvement_suggestions,
        previous_answer=current_answer
    )

改进后的 Query

解释 RAG 的核心流程,并给出一个简短示例

Please improve your previous answer based on the following feedback:
1. 详细说明检索步骤,包括向量化、相似度计算等技术细节
2. 补充一个具体的代码示例,展示如何实现简单的 RAG 系统
3. 说明检索到的文档如何与 prompt 结合输入到 LLM

Previous answer: RAG(Retrieval-Augmented Generation)是一种结合检索和生成的技术。它的核心流程包括:

1. 用户提出问题
2. 系统从知识库中检索相关文档
3. 将检索到的文档和问题一起输入到生成模型
4. 生成最终答案

这种方法可以让模型基于外部知识生成更准确的答案。

第 2 轮迭代
2.1 Worker Agent 调用(生成改进稿)

完整请求内容

{
  "callee": "worker_agent",
  "caller": "reflexion_flow",
  "arguments": {
    "query": "解释 RAG 的核心流程,并给出一个简短示例\n\nPlease improve your previous answer based on the following feedback:\n1. 详细说明检索步骤,包括向量化、相似度计算等技术细节\n2. 补充一个具体的代码示例,展示如何实现简单的 RAG 系统\n3. 说明检索到的文档如何与 prompt 结合输入到 LLM\n\nPrevious answer: RAG(Retrieval-Augmented Generation)是一种结合检索和生成的技术。它的核心流程包括:\n\n1. 用户提出问题\n2. 系统从知识库中检索相关文档\n3. 将检索到的文档和问题一起输入到生成模型\n4. 生成最终答案\n\n这种方法可以让模型基于外部知识生成更准确的答案。"
  },
  "trace_id": "trace_abc123",
  "node_id": "node_worker_2"
}

完整响应内容

{
  "state": "COMPLETED",
  "output": "# RAG 核心流程详解\n\nRAG(Retrieval-Augmented Generation)结合了信息检索与生成模型的优势,核心流程如下:\n\n## 1. 文档预处理与索引\n- 将知识库文档分块(chunking)\n- 使用 Embedding 模型(如 OpenAI embeddings)将文档向量化\n- 存储到向量数据库(如 FAISS、Pinecone)\n\n## 2. 用户查询处理\n- 用户提出问题\n- 将问题向量化(使用相同的 embedding 模型)\n- 通过余弦相似度或其他距离度量在向量库中检索 Top-K 相关文档\n\n## 3. 上下文组装与生成\n- 将检索到的文档片段与用户问题组合成 prompt\n- 输入到 LLM(如 GPT-4)生成答案\n- LLM 基于检索到的上下文生成准确回答\n\n## 简短代码示例\n\n```python\nfrom langchain.embeddings import OpenAIEmbeddings\nfrom langchain.vectorstores import FAISS\nfrom langchain.llms import OpenAI\n\n# 1. 构建向量库\nembeddings = OpenAIEmbeddings()\ndocs = [\"文档1内容\", \"文档2内容\", \"文档3内容\"]\nvectorstore = FAISS.from_texts(docs, embeddings)\n\n# 2. 检索相关文档\nquery = \"用户的问题\"\nrelevant_docs = vectorstore.similarity_search(query, k=3)\n\n# 3. 组装 prompt 并生成\ncontext = \"\\n\".join([doc.page_content for doc in relevant_docs])\nprompt = f\"基于以下上下文回答问题:\\n{context}\\n\\n问题:{query}\"\n\nllm = OpenAI()\nanswer = llm(prompt)\nprint(answer)\n```\n\n这个示例展示了 RAG 的完整流程:向量化存储、相似度检索、上下文注入生成。",
  "extra": {
    "model": "gpt-4",
    "tokens": 487
  }
}

解析后的答案

current_answer = """# RAG 核心流程详解

RAG(Retrieval-Augmented Generation)结合了信息检索与生成模型的优势,核心流程如下:

## 1. 文档预处理与索引
- 将知识库文档分块(chunking)
- 使用 Embedding 模型(如 OpenAI embeddings)将文档向量化
- 存储到向量数据库(如 FAISS、Pinecone)

## 2. 用户查询处理
- 用户提出问题
- 将问题向量化(使用相同的 embedding 模型)
- 通过余弦相似度或其他距离度量在向量库中检索 Top-K 相关文档

## 3. 上下文组装与生成
- 将检索到的文档片段与用户问题组合成 prompt
- 输入到 LLM(如 GPT-4)生成答案
- LLM 基于检索到的上下文生成准确回答
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import FAISS
from langchain.llms import OpenAI

# 1. 构建向量库
embeddings = OpenAIEmbeddings()
docs = ["文档1内容", "文档2内容", "文档3内容"]
vectorstore = FAISS.from_texts(docs, embeddings)

# 2. 检索相关文档
query = "用户的问题"
relevant_docs = vectorstore.similarity_search(query, k=3)

# 3. 组装 prompt 并生成
context = "\\n".join([doc.page_content for doc in relevant_docs])
prompt = f"基于以下上下文回答问题:\\n{context}\\n\\n问题:{query}"

llm = OpenAI()
answer = llm(prompt)
print(answer)

这个示例展示了 RAG 的完整流程:向量化存储、相似度检索、上下文注入生成。

2.2 Reflexion Agent 调用(再次评估)

完整请求内容

{
  "callee": "reflexion_agent",
  "caller": "reflexion_flow",
  "arguments": {
    "query": "Please evaluate the quality of the following answer:\n\nOriginal Question: 解释 RAG 的核心流程,并给出一个简短示例\n\nAnswer: # RAG 核心流程详解\n\nRAG(Retrieval-Augmented Generation)结合了信息检索与生成模型的优势,核心流程如下:\n\n## 1. 文档预处理与索引\n- 将知识库文档分块(chunking)\n- 使用 Embedding 模型(如 OpenAI embeddings)将文档向量化\n- 存储到向量数据库(如 FAISS、Pinecone)\n\n## 2. 用户查询处理\n- 用户提出问题\n- 将问题向量化(使用相同的 embedding 模型)\n- 通过余弦相似度或其他距离度量在向量库中检索 Top-K 相关文档\n\n## 3. 上下文组装与生成\n- 将检索到的文档片段与用户问题组合成 prompt\n- 输入到 LLM(如 GPT-4)生成答案\n- LLM 基于检索到的上下文生成准确回答\n\n## 简短代码示例\n\n```python\nfrom langchain.embeddings import OpenAIEmbeddings\nfrom langchain.vectorstores import FAISS\nfrom langchain.llms import OpenAI\n\n# 1. 构建向量库\nembeddings = OpenAIEmbeddings()\ndocs = [\"文档1内容\", \"文档2内容\", \"文档3内容\"]\nvectorstore = FAISS.from_texts(docs, embeddings)\n\n# 2. 检索相关文档\nquery = \"用户的问题\"\nrelevant_docs = vectorstore.similarity_search(query, k=3)\n\n# 3. 组装 prompt 并生成\ncontext = \"\\n\".join([doc.page_content for doc in relevant_docs])\nprompt = f\"基于以下上下文回答问题:\\n{context}\\n\\n问题:{query}\"\n\nllm = OpenAI()\nanswer = llm(prompt)\nprint(answer)\n```\n\n这个示例展示了 RAG 的完整流程:向量化存储、相似度检索、上下文注入生成。\n\nPlease evaluate based on these criteria:\n1. Accuracy: Is the information correct and factual?\n2. Completeness: Does it fully address the user's question?\n3. Clarity: Is it well-structured and easy to understand?\n4. Relevance: Does it stay focused on the user's needs?\n5. Helpfulness: Does it provide practical value to the user?\n\nReturn your evaluation in the following format:\n{\n  \"is_satisfactory\": boolean,\n  \"evaluation_reason\": \"string\",\n  \"improvement_suggestions\": \"string\"\n}\n\nYour response must be valid JSON matching the schema above."
  },
  "trace_id": "trace_abc123",
  "node_id": "node_reflexion_2"
}

完整响应内容

{
  "state": "COMPLETED",
  "output": "{\n  \"is_satisfactory\": true,\n  \"evaluation_reason\": \"答案全面覆盖了 RAG 的核心流程,包括文档预处理、向量化、检索和生成四个关键步骤。技术细节充分(embedding、向量数据库、相似度计算),并提供了一个清晰完整的代码示例。结构清晰,使用 Markdown 格式易于阅读。完全满足用户需求。\",\n  \"improvement_suggestions\": \"\"\n}",
  "extra": {
    "model": "gpt-4",
    "tokens": 178
  }
}

解析后的评估结果

evaluation = ReflectionEvaluation(
    is_satisfactory=True,
    evaluation_reason="答案全面覆盖了 RAG 的核心流程,包括文档预处理、向量化、检索和生成四个关键步骤。技术细节充分(embedding、向量数据库、相似度计算),并提供了一个清晰完整的代码示例。结构清晰,使用 Markdown 格式易于阅读。完全满足用户需求。",
    improvement_suggestions=""
)

判断结果is_satisfactory = True,答案满意,流程结束!


2.3 返回最终结果

代码逻辑

if evaluation.is_satisfactory:
    logger.info(f"Answer satisfactory after {current_round + 1} rounds")
    return OxyResponse(
        state=OxyState.COMPLETED,
        output=f"Final answer optimized through {current_round + 1} rounds of reflexion:\n\n{current_answer}",
        extra={
            "reflexion_rounds": current_round + 1,
            "final_evaluation": evaluation.dict(),
        },
    )

完整返回内容

{
  "state": "COMPLETED",
  "output": "Final answer optimized through 2 rounds of reflexion:\n\n# RAG 核心流程详解\n\nRAG(Retrieval-Augmented Generation)结合了信息检索与生成模型的优势,核心流程如下:\n\n## 1. 文档预处理与索引\n- 将知识库文档分块(chunking)\n- 使用 Embedding 模型(如 OpenAI embeddings)将文档向量化\n- 存储到向量数据库(如 FAISS、Pinecone)\n\n## 2. 用户查询处理\n- 用户提出问题\n- 将问题向量化(使用相同的 embedding 模型)\n- 通过余弦相似度或其他距离度量在向量库中检索 Top-K 相关文档\n\n## 3. 上下文组装与生成\n- 将检索到的文档片段与用户问题组合成 prompt\n- 输入到 LLM(如 GPT-4)生成答案\n- LLM 基于检索到的上下文生成准确回答\n\n## 简短代码示例\n\n```python\nfrom langchain.embeddings import OpenAIEmbeddings\nfrom langchain.vectorstores import FAISS\nfrom langchain.llms import OpenAI\n\n# 1. 构建向量库\nembeddings = OpenAIEmbeddings()\ndocs = [\"文档1内容\", \"文档2内容\", \"文档3内容\"]\nvectorstore = FAISS.from_texts(docs, embeddings)\n\n# 2. 检索相关文档\nquery = \"用户的问题\"\nrelevant_docs = vectorstore.similarity_search(query, k=3)\n\n# 3. 组装 prompt 并生成\ncontext = \"\\n\".join([doc.page_content for doc in relevant_docs])\nprompt = f\"基于以下上下文回答问题:\\n{context}\\n\\n问题:{query}\"\n\nllm = OpenAI()\nanswer = llm(prompt)\nprint(answer)\n```\n\n这个示例展示了 RAG 的完整流程:向量化存储、相似度检索、上下文注入生成。",
  "extra": {
    "reflexion_rounds": 2,
    "final_evaluation": {
      "is_satisfactory": true,
      "evaluation_reason": "答案全面覆盖了 RAG 的核心流程,包括文档预处理、向量化、检索和生成四个关键步骤。技术细节充分(embedding、向量数据库、相似度计算),并提供了一个清晰完整的代码示例。结构清晰,使用 Markdown 格式易于阅读。完全满足用户需求。",
      "improvement_suggestions": ""
    }
  }
}

2. 特殊情况:达到最大轮次仍不满意

假设经过 3 轮迭代后,is_satisfactory 仍然是 False,则会触发备用 LLM 收尾机制。

2.1 备用 LLM 调用

代码逻辑

# 构造最终汇总 prompt
final_query = f"""
Original user question: {original_query}

Latest answer attempt: {current_answer}

Latest evaluation feedback: {evaluation.evaluation_reason}

Please provide the best possible final answer considering all the feedback above.
"""

final_messages = [
    Message.system_message(
        "You are tasked with providing the best possible answer based on previous attempts and feedback."
    ),
    Message.user_message(final_query),
]

final_response = await oxy_request.call(
    callee=self.llm_model,  # "gpt-4"
    arguments={"messages": [msg.to_dict() for msg in final_messages]},
)

完整请求内容

{
  "callee": "gpt-4",
  "caller": "reflexion_flow",
  "arguments": {
    "messages": [
      {
        "role": "system",
        "content": "You are tasked with providing the best possible answer based on previous attempts and feedback."
      },
      {
        "role": "user",
        "content": "\nOriginal user question: 解释 RAG 的核心流程,并给出一个简短示例\n\nLatest answer attempt: [第3轮的答案内容]\n\nLatest evaluation feedback: 答案虽然详细,但代码示例过于依赖特定框架,缺乏通用性。\n\nPlease provide the best possible final answer considering all the feedback above.\n"
      }
    ]
  },
  "trace_id": "trace_abc123",
  "node_id": "node_finalizer"
}

完整响应内容

{
  "state": "COMPLETED",
  "output": "# RAG(检索增强生成)完整指南\n\n## 核心流程\n\nRAG 是一种将外部知识检索与大语言模型生成能力结合的技术架构:\n\n### 1. 离线准备阶段\n- **文档分割**:将知识库切分为适当大小的文本块\n- **向量化**:使用 embedding 模型转换为向量表示\n- **索引构建**:存储到向量数据库便于快速检索\n\n### 2. 在线查询阶段\n- **查询向量化**:将用户问题转为向量\n- **相似度检索**:找出最相关的 Top-K 文档片段\n- **上下文增强**:将检索结果与问题组合\n- **LLM 生成**:基于增强上下文生成准确答案\n\n## 通用实现示例(不依赖特定框架)\n\n```python\nimport numpy as np\nfrom openai import OpenAI\n\nclient = OpenAI()\n\n# 1. 构建知识库向量索引\ndef build_index(documents):\n    embeddings = []\n    for doc in documents:\n        response = client.embeddings.create(\n            input=doc,\n            model=\"text-embedding-ada-002\"\n        )\n        embeddings.append(response.data[0].embedding)\n    return np.array(embeddings), documents\n\n# 2. 检索相关文档\ndef retrieve(query, embeddings, documents, top_k=3):\n    query_response = client.embeddings.create(\n        input=query,\n        model=\"text-embedding-ada-002\"\n    )\n    query_vec = np.array(query_response.data[0].embedding)\n    \n    # 计算余弦相似度\n    similarities = np.dot(embeddings, query_vec)\n    top_indices = np.argsort(similarities)[-top_k:][::-1]\n    \n    return [documents[i] for i in top_indices]\n\n# 3. RAG 生成\ndef rag_generate(query, knowledge_base):\n    embeddings, documents = build_index(knowledge_base)\n    relevant_docs = retrieve(query, embeddings, documents)\n    \n    context = \"\\n---\\n\".join(relevant_docs)\n    prompt = f\"\"\"根据以下参考资料回答问题:\n\n{context}\n\n问题:{query}\n\n请基于上述资料提供准确答案。\"\"\"\n    \n    response = client.chat.completions.create(\n        model=\"gpt-4\",\n        messages=[\n            {\"role\": \"system\", \"content\": \"你是一个基于提供资料回答问题的助手。\"},\n            {\"role\": \"user\", \"content\": prompt}\n        ]\n    )\n    \n    return response.choices[0].message.content\n\n# 使用示例\nknowledge = [\n    \"Python 是一种高级编程语言\",\n    \"RAG 结合了检索和生成技术\",\n    \"向量数据库用于高效相似度搜索\"\n]\n\nanswer = rag_generate(\"什么是 RAG?\", knowledge)\nprint(answer)\n```\n\n这个示例使用原生 API 实现,展示了 RAG 的完整数据流:文档向量化 → 查询检索 → 上下文注入 → 生成答案。",
  "extra": {
    "model": "gpt-4",
    "tokens": 612
  }
}

最终返回

{
  "state": "COMPLETED",
  "output": "Answer after 4 rounds of reflexion attempts:\n\n[备用 LLM 生成的最终答案]",
  "extra": {
    "reflexion_rounds": 4,
    "final_evaluation": {
      "is_satisfactory": false,
      "evaluation_reason": "答案虽然详细,但代码示例过于依赖特定框架,缺乏通用性。",
      "improvement_suggestions": "使用更通用的实现方式"
    },
    "reached_max_rounds": true
  }
}

3. 关键技术点总结

3.1. Worker Agent 的作用
  • 负责生成答案草稿
  • 接收 query 参数(第一轮是原始问题,后续轮是改进 query)
  • 输出可读的答案文本
  • 可通过 func_parse_worker_response 自定义解析逻辑
3.2. Reflexion Agent 的作用
  • 负责评估答案质量
  • 接收填充好的 evaluation_template(包含问题和答案)
  • 输出结构化的 ReflectionEvaluation 对象
  • 关键字段:
    • is_satisfactory:布尔值,决定是否继续迭代
    • evaluation_reason:评估理由
    • improvement_suggestions:改进建议(用于下一轮)
3.3. 模板系统

evaluation_template

  • 用途:评估答案质量
  • 变量:{query}, {answer}
  • 输出:指导 reflexion agent 返回结构化评估

improvement_template

  • 用途:构造改进 query
  • 变量:{original_query}, {improvement_suggestions}, {previous_answer}
  • 输出:让 worker agent 理解需要改进的方向
3.4. 解析器系统

Pydantic Parser

  • 自动在 prompt 中添加 JSON schema 说明
  • 自动解析 LLM 返回的 JSON 字符串
  • 提供类型验证和错误处理

自定义解析器

  • func_parse_worker_response:处理 worker 返回(如提取特定格式)
  • func_parse_reflexion_response:处理 reflexion 返回(如文本格式评估)
3.5. 控制流逻辑
for round in range(max_rounds + 1):
    # 1. Worker 生成答案
    answer = worker_agent(current_query)
    
    # 2. Reflexion 评估答案
    evaluation = reflexion_agent(evaluation_template.format(query, answer))
    
    # 3. 判断是否满意
    if evaluation.is_satisfactory:
        return answer  # 提前结束
    
    # 4. 构造改进 query
    if round < max_rounds:
        current_query = improvement_template.format(...)
    else:
        # 达到上限,调用备用 LLM
        return finalizer_llm(original_query, answer, evaluation)
3.6. 数据流转
用户问题
   ↓
[Round 1]
   ↓ current_query (原始问题)
Worker Agent → answer_1
   ↓
Reflexion Agent → evaluation_1 (不满意)
   ↓ 生成 improvement_query_1
[Round 2]
   ↓ current_query (包含改进建议)
Worker Agent → answer_2
   ↓
Reflexion Agent → evaluation_2 (满意)
   ↓
返回最终答案

4. 可观测性建议

为了更好地理解和调试 Reflexion 流程,建议记录以下内容:

# 每一轮的完整追踪
{
  "round": 2,
  "worker": {
    "request": {"query": "..."},
    "response": {"output": "..."},
    "parsed_answer": "..."
  },
  "reflexion": {
    "request": {"query": "...评估模板..."},
    "response": {"output": "{\"is_satisfactory\": true, ...}"},
    "parsed_evaluation": {
      "is_satisfactory": true,
      "evaluation_reason": "...",
      "improvement_suggestions": ""
    }
  },
  "decision": "COMPLETED"
}

这样可以清晰地看到每一轮的输入输出,便于分析哪个环节出现问题。

5. 小结总结

Reflexion 的核心价值在于:

  1. 结构化迭代:不是简单重试,而是基于评估反馈进行有针对性的改进
  2. 可控收敛:通过 max_reflexion_rounds 限制成本和延迟
  3. 可扩展性:通过模板、解析器、自定义 agent 适配不同场景
  4. 可观测性:每一步的输入输出都可被追踪和记录

通过理解完整的 LLM 交互过程,你可以:

  • 优化模板提示词以提高评估准确性
  • 调整解析器以支持不同的输出格式
  • 定制 worker/reflexion agent 以适配特定领域
  • 监控和分析每轮迭代的效果
Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐