首页 / 文章

LangChain驱动的智能体AI——第5部分:结合ReAct的智能体RAG技术

LangChain驱动的代理型AI第五部分:代理型RAG,其中ReAct代理决定何时检索信息,而在返回答案之前会通过反思步骤对其进行检查。

发布者:REACTAPP.TOP阅读约 9 分钟2059 词

来源: Agentic AI with LangChain — Part 5: Agentic RAG with ReAct and Reflection

可将此内容视为《基于LangChain的智能体AI——第5部分:结合ReAct与Reflection的智能体RAG》中理念面向操作人员的重构版本:清晰的阶段划分、有序的代码模块,以及能在交接过程中保留的恢复说明。将概览视为可度量的指标会更有帮助,在扩大范围之前,先记录一份最佳案例、一个失败场景以及回滚说明。相比庞大的脚本,应优先选择小型且可测试的单元。当某一步骤失败时,故障应能指向单一责任点,而非复杂的流程链。

技术概念

对于技术概念,在修改代码之前需明确输入参数、该步骤的负责人以及终止标准。操作人员应能够从已知的检查点重新运行该步骤,而无需猜测隐藏状态。 将此阶段视为输入与经过验证的输出之间的契约。为相关成果命名,定义成功判定标准,并拒绝默许的半完成状态。 需引用实际作为答案依据的段落。没有引用的话,操作人员就无法区分是幻觉内容还是索引缺失导致的错误。

1. 系统配置

1. 系统配置方面,在修改代码之前需明确输入参数、该步骤的负责人以及终止标准。操作人员应能够从已知的检查点重新运行该步骤,而无需猜测隐藏状态。应在功能结果旁记录执行时间以及令牌或查询成本。提前显示成本信息,可避免在从演示环境切换到共享环境时出现意外费用。需注明实际作为答案依据的段落;若没有引用,操作人员就无法区分是幻觉内容还是索引缺失所致。

OPENAI_API_KEY="<Your OpenAI API Key>"
VECTOR_DB=pinecone
PINECONE_API_KEY=<your Pinecone API Key>
PINECONE_ENVIRONMENT=gcp-starter
LANGSMITH_TRACING=true
LANGSMITH_ENDPOINT="https://api.smith.langchain.com"
LANGSMITH_API_KEY="<Your LangSmith API Key"
LANGSMITH_PROJECT="agent-ai"
TAVILY_API_KEY=<Your TAVILY API Key>
class BaseConfig(BaseSettings):
    OPENAI_API_KEY: Optional[str]
    PINECONE_API_KEY: Optional[str]
    TAVILY_API_KEY: Optional[str]

model_config = SettingsConfigDict(env_file=".env", extra="ignore")

2. 项目结构

对于第2点“项目结构”,在修改代码之前需明确输入内容、各步骤的负责人以及终止标准。操作人员应能够从已知的检查点重新运行该步骤,而无需猜测隐藏状态。 配置信息应置于应用程序代码之外。环境文件、密钥存储以及功能开关应集中存放于一个位置,以便操作人员无需查看整个系统结构即可进行审核。 需引用实际作为答案依据的段落。若没有引用,操作人员就无法区分是虚假信息还是索引缺失导致的错误。

project/
├── rag_process/       # Pinecone RAG operations
│   ├── __init__.py
│   ├── extractor.py
|   └── service.py
│
├── graphs             # implement ReAct and Reflection StateGraph
│   ├── nodes.py       # graph nodes. Defined as Python functions
│   ├── graph.py       # graph workflow
│   ├── consts.py      # define node names as constants
│   └── state.py       # typed dictionary to store graph states
|
|
├── tools              # defines Pinecone retriever and get_weather tools
│   ├── retriever_tools.py    # Python function tool to retrieve Pinecone RAG
|   └── weather.py        # typed dictionary to store graph states
|
|── schemas.py          # pydantic data models
|── upload.py           # python functions to upload files asynchronously
├── main.py             # fastAPI app
├── config.py           # pydantic BaseConfig
│── dependencies.py     # dependency inject to fastAPI endpoint function
├── .env                # environment variable definition
├── client.py           # streamlit client
├── .gitignore
└── requirements.txt     # package requirements

3. ReAct模式集成

对于第3点“ReAct模式集成”,在修改代码之前需明确输入参数、该步骤的负责人以及终止条件。操作人员应能够从已知的检查点重新运行该步骤,而无需猜测隐藏状态。 需同时记录正常流程和异常恢复流程。重试机制、人工审核环节以及错误消息处理都是产品本身的组成部分,而非后续需要补充的功能。 必须引用实际作为答案依据的段落。如果没有引用,操作人员就无法区分是幻觉内容还是索引缺失导致的错误。

3.1. RAG检索工具

对于3.1版RAG检索工具,在修改代码之前需明确输入参数、该步骤的负责人以及终止标准。操作人员应能够从已知的检查点重新运行该步骤,而无需猜测隐藏状态。相比冗长的脚本,更应采用小型且可测试的单元。当某个步骤失败时,故障原因应能指向单一责任模块,而非复杂的流程链。必须注明实际作为答案依据的段落;若没有引用,操作人员就无法区分是幻觉内容还是索引缺失所致。

@tool
async def search_agentic_docs(query: str) -> str:
    """
    Good for questions about generative agents, prompt engineering, and adversarial attacks.
    Pass a natural language search query to retrieve context from the agentic ai database.
    """
    # Simply invoke your existing vector service retriever
    docs = await vector_service.retriever.ainvoke(query)

    # Flatten the document content into a single string for the LLM
    return "\n\n".join([d.page_content for d in docs])

3.2. GraphState

对于3.2版GraphState,在修改代码之前需明确输入参数、该步骤的负责人以及终止条件。操作员应能够从已知的检查点重新运行该步骤,而无需猜测隐藏状态。 将此阶段视为输入与已验证输出之间的契约。为相关成果命名,定义成功判定标准,并拒绝默许的半完成状态。 需引用实际作为答案依据的段落。没有引用的话,操作员就无法区分幻觉内容与索引缺失问题。

class GraphState(TypedDict):
    """
    Represents the state of our graphs.

    Attributes:
        question: question
        generation: LLM generation
        acceptable: whether the answer is qualified to be acceptable
        messages: list of messages
    """

    question: str
    generation: str
    acceptable: bool
    messages: Annotated[list[AnyMessage], add_messages]
    loop_count: int

3.3. ReAct节点

对于3.3节中的ReAct节点,在修改代码之前需明确输入参数、该步骤的负责人以及终止条件。操作员应能够从已知的检查点重新运行该步骤,而无需猜测隐藏状态。应在功能结果旁记录执行时间以及令牌或查询成本。提前显示成本信息,可避免在从演示环境切换到共享环境时出现意外费用。需注明实际作为答案依据的段落;若没有引用,操作员就无法区分是幻觉内容还是索引缺失导致的错误。

4. 反思模式集成

关于4. 反射模式集成,在修改代码之前需明确输入参数、该步骤的负责人以及终止标准。操作员应能够从已知的检查点重新运行该步骤,而无需猜测隐藏状态。 配置信息应置于应用程序代码之外。环境文件、密钥存储以及功能标志应集中存放于一个位置,以便操作员无需查看整个系统结构即可进行审计。 需引用实际作为答案依据的段落。没有引用的话,操作员就无法区分是幻觉内容还是索引缺失导致的错误。 关于4. 反射模式集成,在修改代码之前需明确输入参数、该步骤的负责人以及终止标准。操作员应能够从已知的检查点重新运行该步骤,而无需猜测隐藏状态。 相较于庞大的脚本,更应优先使用小型且可测试的单元。当某个步骤失败时,故障原因应能指向单一责任模块,而非复杂的依赖关系。

eline。

4.1. 反射机制的工作原理

在学习4.1节“反射机制的工作原理”时,首先列出相关规范:所需的输入参数、成功信号以及部分失败时的处理方式。这样的清单能确保后续的代码修改保持一致性。 将此阶段视为输入与验证后输出之间的契约。为相关成果命名,明确成功判定标准,杜绝无声的半完成状态。 在调整提示词之前,先使用固定的问题集测试召回率。仅仅更换提示词很难改善较差的检索效果。

4.2. 提示词

在处理4.2节“提示”内容时,首先写下相关约定:所需输入、成功信号以及部分失败时的处理方式。这样的清单能确保后续的代码修改保持一致性。 在功能结果旁记录执行时间以及令牌或查询成本。提前了解成本情况,可避免在从演示环境过渡到共享环境时出现意外费用。 缓存稳定的系统指令和工具结构。重复发送相同的开头信息是导致资源浪费的常见原因。

GENERATE_SYSTEM_PROMPT = f"""You are an assistant for question-answering tasks with access to multiple tools.
    use these tools to retrieve context to answer the question. If you don't know the answer,
    just say that you don't know. Use three sentences maximum and keep the answer concise.

    Tool Use Instructions:

    - Use tools as much as possible.
    - Chain tools when needed (e.g., search for info, then use that to search
      for relevant hotels)
    - Be conversational and helpful
    - If you choose to answer a question using your internal knowledge instead of a tool,
      you must be completely certain of the facts. If there is any ambiguity,
      or if the question requires up-to-date or highly specific details, you MUST use a tool to verify.

    """
GRADER_SYSTEM_PROMPT = """""You are a grader assessing whether an LLM generation addresses/resolves a
      question using the context. Generate critique and recommendations for LLM that generated the answer.
      always provide detailed recommendations, including requests for search more relevant context, generate
      answer based on context to reduce hallucination, and generate answer relevant to the question.

      The LLM generating this answer has the access to the following tools to obtain context:
      **get_weather**: search for weather information given a city name
      **search_agentic_docs**:  Good for questions about generative agents, prompt engineering, and adversarial attacks
      **TavilySearch**: General search tool from the internet.

      INSTRUCTIONS:
      (a) Evaluate if the context is relevant to the question
      Provide recommendation if context is not relevant to the question. You can suggest the LLM to use an
      appropriate tool. If there is no context, you must be completely certain of the facts. If the question is
      covered by provided tools, or there is any ambiguity,
      or if the question requires up-to-date or highly specific details, you MUST suggest to use a tool to verify answer.

      (b) Evaluate if the answer is based on the context
      if the answer is not based on the context, it is a hallucination. You should suggest to regenerate the answer
      based on the context.
      (c) Evaluate if the answer resolves the question
      if the answer does not resolves the question, suggest to regenerate the answer

      The LLM generated this answer is strictly instructed to keep its answer CONCISE (maximum of 3 sentences).
      Do NOT penalize the answer for omitting minor details if the core question is answered accurately.
      If all the evaluations are passed, no suggestions should be provided.

      CRITERIA FOR ACCEPTABLE (True):
      - If the answer is accurate, addresses the user's question using the context, and does not hallucinate,
        you MUST set acceptable to True, even if it missed some details from the context.
      - Only set acceptable to False if there is a fundamental flaw (hallucination, wrong information,
        or completely missing the point).

      OUTPUT REQUIREMENTS:

        You must return a structured output with the following fields:

        - acceptable (boolean): True if the answer passed all evaluation,
          False if any of the evaluation fails and recommendations are provided
        - recommendations (string): recommendations you provide

        INPUTS:

        question: {question}
        answer: {answer}
        context: {context}
    """

4.3. 反射节点

在学习4.3节“反射节点”时,首先需明确相关规范:所需的输入参数、成功信号以及部分失败时的处理方式。这份清单能确保后续的代码修改保持一致性。 应将配置信息与应用程序代码分开存放。环境文件、密钥存储以及功能开关应集中于一个位置,这样操作人员无需查看整个系统结构即可进行审计。 在调整提示词之前,先使用固定的问题集来测试召回率。仅仅更换提示词往往无法解决检索效果不佳的问题。 在学习4.3节“反射节点”时,首先需明确相关规范:所需的输入参数、成功信号以及部分失败时的处理方式。这份清单能确保后续的代码修改保持一致性。 相比庞大的脚本,更应优先使用小型且可测试的单元。当某个步骤出现故障时,故障点应能指向单一的责任模块,而非复杂的流程链。

5. 完整工作流程

  1. 将完整工作流程视为可度量的对象才能发挥最佳效果。在扩大范围之前,先记录一份理想的处理结果、一个失败案例以及回滚说明。 将此阶段视为输入与经过验证的输出之间的契约。为相关成果命名,明确成功标准,杜绝默许的半完成状态。 将分块策略与检索策略分开。当质量指标发生变化时,调整其中一项不应强制要求重写另一项。

6. 智能体可靠性权衡

7. 总结

操作检查清单