使用LangGraph构建一个RAG Agent

这篇文章来介绍下使用 LangGraph 构建 RAG Agent。

RAG通过引入外部知识库,将动态检索与生成能力结合,让LLM既能“博学”又能“可信”。它的核心逻辑是:
1️⃣ 检索 → 从知识库中精准拉取相关文档;
2️⃣ 增强 → 将检索结果融入提示(Prompt),辅助模型生成;
3️⃣ 生成 → 输出兼具准确性与透明度的答案。

1.预处理文档

使用WebBaseLoader工具加载web资源,读取文档

from langchain_community.document_loaders import WebBaseLoader

urls =[

"https://lilianweng.github.io/posts/2024-11-28-reward-hacking/",

"https://lilianweng.github.io/posts/2024-07-07-hallucination/",

"https://lilianweng.github.io/posts/2024-04-12-diffusion-video/",

]

docs =[WebBaseLoader(url).load()for url in urls]

2.创建检索工具

对文档数据进行切分:

from langchain_text_splitters import RecursiveCharacterTextSplitter

docs_list =[item for sublist in docs for item in sublist]

text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(

    chunk_size=100, chunk_overlap=50

)

doc_splits = text_splitter.split_documents(docs_list)

使用阿里QianWen的embedding模型将文档数据转化为向量,存储到内存向量数据库

from langchain_core.vectorstoresimportInMemoryVectorStore

from langchain_community.embeddingsimportDashScopeEmbeddings

vectorstore =InMemoryVectorStore.from_documents(

    documents=doc_splits, embedding=DashScopeEmbeddings(model="text-embedding-v3")

)

retriever = vectorstore.as_retriever()

创建检索工具:

from langchain.tools.retrieverimport create_retriever_tool

retriever_tool =create_retriever_tool(

    retriever,

"retrieve_blog_posts",

"Search and return information about Lilian Weng blog posts.",

)

3.生成查询

使用阿里QianWen模型作为LLM,构建 generate_query_or_respond 节点

from langgraph.graphimportMessagesState

response_model =ChatTongyi(model="qwen-plus")

def generate_query_or_respond(state:MessagesState):

"""Call the model to generate a response based on the current state.Given

    the question, it will decide to retrieve using the retriever tool, or simply respond to the user.

"""

    response =(

        response_model

.bind_tools([retriever_tool]).invoke(state["messages"])

)

return{"messages":[response]}

3.对文档评分

定义grade_documents节点: 定义GradeDocuments class,使用QianWen模型结构化输出(返回yes和no),对检索工具的结果进行评分,如果返回yes则返回generate_answer节点,否则返回rewrite_question节点。

from pydantic importBaseModel,Field

from typing importLiteral

GRADE_PROMPT=(

"You are a grader assessing relevance of a retrieved document to a user question. \n "

"Here is the retrieved document: \n\n {context} \n\n"

"Here is the user question: {question} \n"

"If the document contains keyword(s) or semantic meaning related to the user question, grade it as relevant. \n"

"Give a binary score 'yes' or 'no' score to indicate whether the document is relevant to the question."

)

classGradeDocuments(BaseModel):

"""Grade documents using a binary score for relevance check."""

binary_score: str =Field(

        description="Relevance score: 'yes' if relevant, or 'no' if not relevant"

)

grader_model =ChatTongyi(model="qwen-plus")

def grade_documents(

state:MessagesState,

)->Literal["generate_answer","rewrite_question"]:

"""Determine whether the retrieved documents are relevant to the question."""

for message in state["messages"]:

ifisinstance(message,HumanMessage):

            question = message.content

    context = state["messages"][-1].content

    prompt =GRADE_PROMPT.format(question=question, context=context)

    response =(

        grader_model

.with_structured_output(GradeDocuments).invoke(

[{"role":"user","content": prompt}]

)

)

    score = response.binary_score

if score =="yes":

return"generate_answer"

else:

return"rewrite_question"

4.重写问题

定义rewrite_question节点,如果文档评分不相关,则重新根据用户问题生成查询检索:

REWRITE_PROMPT=(

"Look at the input and try to reason about the underlying semantic intent / meaning.\n"

"Here is the initial question:"

"\n ------- \n"

"{question}"

"\n ------- \n"

"Formulate an improved question:"

)

def rewrite_question(state:MessagesState):

"""Rewrite the original user question."""

for message in state["messages"]:

ifisinstance(message,HumanMessage):

            question = message.content

    prompt =REWRITE_PROMPT.format(question=question)

    response = response_model.invoke([{"role":"user","content": prompt}])

return{"messages":[{"role":"user","content": response.content}]}

5.生成答案

定义generate_answer节点, 根据检索结果和用户问题生成答案:

GENERATE_PROMPT=(

"You are an assistant for question-answering tasks. "

"Use the following pieces of retrieved 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.\n"

"Question: {question} \n"

"Context: {context}"

)

def generate_answer(state:MessagesState):

"""Generate an answer."""

for message in state["messages"]:

ifisinstance(message,HumanMessage):

            question = message.content

    context = state["messages"][-1].content

    prompt =GENERATE_PROMPT.format(question=question, context=context)

    response = response_model.invoke([{"role":"user","content": prompt}])

return{"messages":[response]}

6.组装Graph

将所有节点组装为Graph图:

from langgraph.graphimportStateGraph,START,END

from langgraph.prebuiltimportToolNode

from langgraph.prebuiltimport tools_condition

workflow =StateGraph(MessagesState)

# Define the nodes we will cycle between

workflow.add_node(generate_query_or_respond)

workflow.add_node("retrieve",ToolNode([retriever_tool]))

workflow.add_node(rewrite_question)

workflow.add_node(generate_answer)

workflow.add_edge(START,"generate_query_or_respond")

# Decide whether to retrieve

workflow.add_conditional_edges(

"generate_query_or_respond",

    # AssessLLMdecision(call `retriever_tool` tool or respond to the user)

    tools_condition,

{

        # Translate the condition outputs to nodes in our graph

"tools":"retrieve",

END:END,

},

)

# Edges taken after the `action` node is called.

workflow.add_conditional_edges(

"retrieve",

    # Assess agent decision

    grade_documents,

)

workflow.add_edge("generate_answer",END)

workflow.add_edge("rewrite_question","generate_query_or_respond")

# Compile

graph = workflow.compile()

Github

完整代码已上传GitHub

https://github.com/Liu-Shihao/ai-agent-demo/tree/main/src/rag_agent

想入门 AI 大模型却找不到清晰方向?备考大厂 AI 岗还在四处搜集零散资料?别再浪费时间啦!2025 年 AI 大模型全套学习资料已整理完毕,从学习路线到面试真题,从工具教程到行业报告,一站式覆盖你的所有需求,现在全部免费分享

👇👇扫码免费领取全部内容👇👇

一、学习必备:100+本大模型电子书+26 份行业报告 + 600+ 套技术PPT,帮你看透 AI 趋势

想了解大模型的行业动态、商业落地案例?大模型电子书?这份资料帮你站在 “行业高度” 学 AI

1. 100+本大模型方向电子书

在这里插入图片描述

2. 26 份行业研究报告:覆盖多领域实践与趋势

报告包含阿里、DeepSeek 等权威机构发布的核心内容,涵盖:

  • 职业趋势:《AI + 职业趋势报告》《中国 AI 人才粮仓模型解析》;
  • 商业落地:《生成式 AI 商业落地白皮书》《AI Agent 应用落地技术白皮书》;
  • 领域细分:《AGI 在金融领域的应用报告》《AI GC 实践案例集》;
  • 行业监测:《2024 年中国大模型季度监测报告》《2025 年中国技术市场发展趋势》。

3. 600+套技术大会 PPT:听行业大咖讲实战

PPT 整理自 2024-2025 年热门技术大会,包含百度、腾讯、字节等企业的一线实践:

在这里插入图片描述

  • 安全方向:《端侧大模型的安全建设》《大模型驱动安全升级(腾讯代码安全实践)》;
  • 产品与创新:《大模型产品如何创新与创收》《AI 时代的新范式:构建 AI 产品》;
  • 多模态与 Agent:《Step-Video 开源模型(视频生成进展)》《Agentic RAG 的现在与未来》;
  • 工程落地:《从原型到生产:AgentOps 加速字节 AI 应用落地》《智能代码助手 CodeFuse 的架构设计》。

二、求职必看:大厂 AI 岗面试 “弹药库”,300 + 真题 + 107 道面经直接抱走

想冲字节、腾讯、阿里、蔚来等大厂 AI 岗?这份面试资料帮你提前 “押题”,拒绝临场慌!

1. 107 道大厂面经:覆盖 Prompt、RAG、大模型应用工程师等热门岗位

面经整理自 2021-2025 年真实面试场景,包含 TPlink、字节、腾讯、蔚来、虾皮、中兴、科大讯飞、京东等企业的高频考题,每道题都附带思路解析

2. 102 道 AI 大模型真题:直击大模型核心考点

针对大模型专属考题,从概念到实践全面覆盖,帮你理清底层逻辑:

3. 97 道 LLMs 真题:聚焦大型语言模型高频问题

专门拆解 LLMs 的核心痛点与解决方案,比如让很多人头疼的 “复读机问题”:


三、路线必明: AI 大模型学习路线图,1 张图理清核心内容

刚接触 AI 大模型,不知道该从哪学起?这份「AI大模型 学习路线图」直接帮你划重点,不用再盲目摸索!

在这里插入图片描述

路线图涵盖 5 大核心板块,从基础到进阶层层递进:一步步带你从入门到进阶,从理论到实战。

img

L1阶段:启航篇丨极速破界AI新时代

L1阶段:了解大模型的基础知识,以及大模型在各个行业的应用和分析,学习理解大模型的核心原理、关键技术以及大模型应用场景。

img

L2阶段:攻坚篇丨RAG开发实战工坊

L2阶段:AI大模型RAG应用开发工程,主要学习RAG检索增强生成:包括Naive RAG、Advanced-RAG以及RAG性能评估,还有GraphRAG在内的多个RAG热门项目的分析。

img

L3阶段:跃迁篇丨Agent智能体架构设计

L3阶段:大模型Agent应用架构进阶实现,主要学习LangChain、 LIamaIndex框架,也会学习到AutoGPT、 MetaGPT等多Agent系统,打造Agent智能体。

img

L4阶段:精进篇丨模型微调与私有化部署

L4阶段:大模型的微调和私有化部署,更加深入的探讨Transformer架构,学习大模型的微调技术,利用DeepSpeed、Lamam Factory等工具快速进行模型微调,并通过Ollama、vLLM等推理部署框架,实现模型的快速部署。

img

L5阶段:专题集丨特训篇 【录播课】

img
四、资料领取:全套内容免费抱走,学 AI 不用再找第二份

不管你是 0 基础想入门 AI 大模型,还是有基础想冲刺大厂、了解行业趋势,这份资料都能满足你!
现在只需按照提示操作,就能免费领取:

👇👇扫码免费领取全部内容👇👇

2025 年想抓住 AI 大模型的风口?别犹豫,这份免费资料就是你的 “起跑线”!

<think>我们正在讨论如何将RAGFlowAgent集成到LangGraphAgent中。根据引用[1]和[2],LangGraph一个用于构建复杂任务规划与执行Agent的框架,而RAGFlow则是一个专注于RAG(检索增强生成)的Agent。集成的主要目的是让LangGraphAgent能够利用RAGFlow的检索能力来获取外部知识,从而更好地完成复杂任务。步骤概述:1.**理解LangGraphRAGFlow的架构**:-LangGraph基于状态机(statemachine)协调多个Agent或工具,通过节点(nodes)和边(edges)定义工作流[^1]。-RAGFlowAgent提供文档检索能力,通过向量库查询返回与用户问题相关的文档片段。2.**设计集成方案**:-将RAGFlowAgent封装为LangGraph一个工具(Tool)或节点(Node),使其可以被LangGraph的工作流调用。-在LangGraph的状态中设计一个字段(例如`knowledge`)来存储RAGFlow检索的结果。3.**具体步骤**:**步骤1:封装RAGFlowAgentLangGraph工具**-使用LangGraph的`ToolNode`或自定义节点,将RAGFlow的检索功能封装成一个可调用的函数。例如:```pythonfromlanggraph.prebuiltimportToolNodedefragflow_retriever(query:str)->str:#调用RAGFlow的API或SDK进行检索results=ragflow_client.query(query)returnresults[0].content#返回最相关的片段```然后将其包装为ToolNode:```pythonragflow_tool=ToolNode([ragflow_retriever])```**步骤2:在LangGraph工作流中定义节点和边**-创建两个节点:一个Agent节点(负责规划)和RAGFlow工具节点。-根据任务需求,设计边(条件边或普通边)来决定何时调用RAGFlow工具。例如,工作流可以这样设计:```mermaidgraphLRA(开始)-->B[主Agent]B-->C{是否需要知识?}C-->|是|D[RAGFlow工具节点]C-->|否|F[其他工具节点]D-->E[更新状态中的知识字段]E-->BF-->B```**步骤3:状态设计**-定义LangGraph的状态(State),其中包含当前任务信息、历史消息、以及检索到的知识。例如:```pythonfromtypingimportTypedDict,List,Annotatedfromlanggraph.graph.messageimportadd_messagesclassState(TypedDict):messages:Annotated[List[dict],add_messages]#对话消息历史knowledge:str#存储RAGFlow检索到的知识```**步骤4:主Agent的提示词设计**-在主Agent的提示词中,加入指令,使其在需要外部知识时主动调用RAGFlow工具。例如:"当你需要查询特定文档(如产品手册、技术文档)时,请调用RAGFlow检索工具。"**步骤5:处理RAGFlow返回结果**-在RAGFlow工具节点被调用后,将检索结果更新到状态中,并作为上下文传递给主Agent的下一次调用。4.**关键问题处理**:-**多跳检索**:如果任务需要多次检索(例如先查A文档再查B文档),LangGraph的状态机可以循环调用RAGFlow节点,每次根据前一次的结果调整查询。-**错误处理**:在边条件中设置超时或重试机制,避免RAGFlow服务不可用导致整个工作流中断。5.**部署与测试**:-使用LangGraph的`compile`方法编译工作流,并部署为API服务。-设计测试用例:验证简单检索任务和需要多步检索的复杂任务。注意:实际集成时,需要根据RAGFlow提供的API或SDK调整调用方式。如果RAGFlow有特定的认证或参数,需要在封装函数中处理。通过以上步骤,LangGraphAgent就可以在复杂任务执行过程中,动态调用RAGFlowAgent获取外部知识,从而增强其回答的准确性和信息量。相关问题:1.如何在LangGraph中处理RAGFlow检索失败的情况?2.LangGraphAgent如何协调多个RAGFlow实例进行并行检索?3.如何优化RAGFlow在LangGraph工作流中的调用频率以避免性能瓶颈?4.在LangGraph中如何实现RAGFlow检索结果的缓存机制?5.如何评估集成RAGFlow后LangGraphAgent的性能提升?</think>### LangGraph Agent 集成 RAGFlow Agent 的方法与步骤 #### 一、核心集成原理 通过 LangGraph 的**状态机架构**协调 RAGFlow 作为工具节点,实现: 1. **知识检索**:RAGFlow 作为专用检索节点处理文档查询 2. **任务编排**:LangGraph 控制多步骤工作流$$ \text{State} \rightarrow \text{Decision} \rightarrow \text{Action} $$ 3. **数据传递**:LangGraph 状态对象传递检索结果$ \text{state}[\text{"knowledge"}] = \text{RAGFlow\_output} $[^1] #### 二、详细集成步骤 ```mermaid graph TB A[LangGraph初始化] --> B[定义状态机] B --> C[创建RAGFlow工具节点] C --> D[构建工作流决策逻辑] D --> E[配置异常处理] E --> F[部署集成系统] ``` ##### 步骤1:环境准备 ```python # 安装核心库 pip install langgraph ragflow-sdk # 环境变量配置(RAGFlow API密钥) import os os.environ["RAGFLOW_API_KEY"] = "your_api_key" ``` ##### 步骤2:定义状态对象 ```python from typing import TypedDict, Annotated from langgraph.graph.message import add_messages class AgentState(TypedDict): user_query: str knowledge: Annotated[list, add_messages] # 存储RAGFlow检索结果 tool_calls: dict # 工具调用记录 ``` ##### 步骤3:创建RAGFlow工具节点 ```python from langgraph.prebuilt import ToolNode from ragflow import RAGClient def ragflow_retriever(query: str): client = RAGClient(endpoint="https://api.ragflow.com") return client.query( query=query, top_k=3, score_threshold=0.7 ) # 封装为LangGraph节点 ragflow_node = ToolNode([ragflow_retriever]) ``` ##### 步骤4:构建工作流 ```python from langgraph.graph import END, StateGraph # 初始化状态机 workflow = StateGraph(AgentState) # 添加节点 workflow.add_node("retriever", ragflow_node) # RAGFlow节点 workflow.add_node("llm_processor", llm_agent) # 假设已定义LLM处理节点 # 设置边条件 def should_retrieve(state): return "需要文档检索" in state["user_query"] # 基于语义判断 workflow.add_conditional_edges( "start", should_retrieve, { True: "retriever", False: "llm_processor" } ) # 连接节点 workflow.add_edge("retriever", "llm_processor") # 检索结果传递给LLM workflow.add_edge("llm_processor", END) # 编译工作流 app = workflow.compile() ``` ##### 步骤5:执行集成系统 ```python # 运行示例 inputs = {"user_query": "解析2024年Q3财报中的$EBITDA$数据"} result = app.invoke(inputs) # 输出结构 { "user_query": "...", "knowledge": [ {"document": "2024_Q3_Report.pdf", "text": "EBITDA达到$5.2B...", "score": 0.85}, ... ], "tool_calls": {"retriever_calls": 1} } ``` #### 三、关键优化点 1. **混合检索策略**: ```python # 在ragflow_retriever中增加关键词过滤 client.query(..., filter_rules={"date": "2024-07~2024-09"}) ``` 2. **结果缓存机制**: ```python from langgraph.checkpoint import MemorySaver workflow = StateGraph(AgentState, checkpoint=MemorySaver()) ``` 3. **动态分块控制**: ```python # 根据查询类型调整分块策略 if "表格" in query: chunk_mode = "TABLE" elif "公式" in query: chunk_mode = "LATEX" ``` #### 四、常见问题解决方案 | 问题类型 | 解决方案 | |---------|----------| | 检索超时 | 设置`timeout=10.0`并添加重试机制 | | 结果碎片化 | 在LLM节点添加结果聚合提示词 | | 权限控制 | 集成前校验`state["user_role"]` | | 版本冲突 | 使用容器化部署隔离环境 | #### 五、性能评估指标 $$ \text{Acc} = \frac{\text{正确检索次数}}{\text{总调用次数}} \times 100\% $$ $$ \text{Latency} = t_{\text{ragflow}} + t_{\text{langgraph}} $$ 建议基准: - 准确率 > 85% - 平均延迟 < 2.5s --- ### 相关问题 1. 如何优化 LangGraphRAGFlow 节点的检索精度? 2. 在资源受限环境下如何降低 RAGFlow+LangGraph 的内存消耗? 3. LangGraph 如何协调多个 RAGFlow 实例实现负载均衡? 4. 如何设计 RAGFlow 检索结果的缓存策略以提升性能? 5. LangGraph 工作流中如何处理 RAGFlow 的增量更新需求?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值