自定义工作流中的图结构与混合节点设计

介绍自定义工作流对图结构的完全控制能力,可混合确定性逻辑与智能体行为,支持顺序、条件分支、循环和并行执行,并以 RAG 流水线为例说明模型节点、确定性节点与智能体节点的分工。

在那个 **自定义工作流程** 结构中,您使用 [LangGraph](<https://docs.langchain.com/oss/python/langgraph/overview>)。您可以完全控制图表结构——包括顺序步骤、有条件的分支、循环和平行执行。 ## 关键特征 - 对图表结构的完全控制 - 将确定性逻辑与代理行为混合 - 支持顺序步骤、有条件的分支、循环和平行执行 - 将其他模式作为节点嵌入工作流程 ## 何时使用 使用自定义工作流程, 当标准模式( 助推器、 技能等) 不符合您的要求时, 您需要将确定性逻辑与代理行为混合, 或者您的使用大小写需要复杂的路由或多阶段处理。 您工作流程中的每个节点可以是简单的函数、 LLM 调用, 或是整个 [代理服务器](<https://docs.langchain.com/oss/python/langchain/agents>) 与 [工具](<https://docs.langchain.com/oss/python/langchain/tools>)。您也可以在一个自定义的工作流程中构建其他架构,例如,将一个多代理系统嵌入到一个单一的节点中。关于自定义工作流程的完整实例,请参见下面的教程。 ## 教程:构建多源知识库,并设置路由. 那个... [路由器图案](<https://docs.langchain.com/oss/python/langchain/multi-agent/router>) 是一个自定义工作流程的示例。 此教程通过构建一个路由器, 以并行查询 GitHub、 Notion 和 Slack, 然后合成结果 。 ## 基本执行情况 核心的洞察力是,你可以直接在任何LangGraph节点内调用一个LangChain代理,将自定义工作流程的灵活性与预建代理的方便性结合起来: ``` from langchain.agents import create_agent from langgraph.graph import StateGraph, START, END agent = create_agent(model="openai:gpt-6.1-sol", tools=[...]) def agent_node(state: State) -> dict: """A LangGraph node that invokes a LangChain agent.""" result = agent.invoke({ "messages": [{"role": "user", "content": state["query"]}] }) return {"answer": result["messages"][-1].content} # Build a simple workflow workflow = ( StateGraph(State) .add_node("agent", agent_node) .add_edge(START, "agent") .add_edge("agent", END) .compile() ) ``` ## 示例:RAG管道 一个常用的个案正在合并 [检索](<https://docs.langchain.com/oss/python/deepagents/retrieval>) 。此示例构建了 WNBA 统计助手,该助手从一个知识库中获取并可以获取现场新闻。 自定义 RAG 工作流程 工作流程显示有三种节点: - **模型节点** (重写):重写用户查询,以便使用 [结构化产出](<https://docs.langchain.com/oss/python/langchain/structured-output>). - **决定性节点** (检索):执行矢量相似性搜索——不涉及LLM. - **代理节点** (代理人):理由超出检索上下文,可以通过工具获取额外信息. 您可以使用 LangGraph 状态在工作流程步骤之间传递信息。 这允许您工作流程的每个部分读取并更新结构化字段, 从而便于在节点之间共享数据和上下文 。 ``` from typing import TypedDict from pydantic import BaseModel from langgraph.graph import StateGraph, START, END from langchain.agents import create_agent from langchain.tools import tool from langchain_openai import ChatOpenAI, OpenAIEmbeddings from langchain_core.vectorstores import InMemoryVectorStore class State(TypedDict): question: str rewritten_query: str documents: list[str] answer: str # WNBA knowledge base with rosters, game results, and player stats embeddings = OpenAIEmbeddings() vector_store = InMemoryVectorStore(embeddings) vector_store.add_texts([ # Rosters "New York Liberty 2024 roster: Breanna Stewart, Sabrina Ionescu, Jonquel Jones, Courtney Vandersloot.", "Las Vegas Aces 2024 roster: A'ja Wilson, Kelsey Plum, Jackie Young, Chelsea Gray.", "Indiana Fever 2024 roster: Caitlin Clark, Aliyah Boston, Kelsey Mitchell, NaLyssa Smith.", # Game results "2024 WNBA Finals: New York Liberty defeated Minnesota Lynx 3-2 to win the championship.", "June 15, 2024: Indiana Fever 85, Chicago Sky 79. Caitlin Clark had 23 points and 8 assists.", "August 20, 2024: Las Vegas Aces 92, Phoenix Mercury 84. A'ja Wilson scored 35 points.", # Player stats "A'ja Wilson 2024 season stats: 26.9 PPG, 11.9 RPG, 2.6 BPG. Won MVP award.", "Caitlin Clark 2024 rookie stats: 19.2 PPG, 8.4 APG, 5.7 RPG. Won Rookie of the Year.", "Breanna Stewart 2024 stats: 20.4 PPG, 8.5 RPG, 3.5 APG.", ]) retriever = vector_store.as_retriever(search_kwargs={"k": 5}) @tool def get_latest_news(query: str) -> str: """Get the latest WNBA news and updates.""" # Your news API here return "Latest: The WNBA announced expanded playoff format for 2025..." agent = create_agent( model="openai:gpt-6.1-sol", tools=[get_latest_news], ) model = ChatOpenAI(model="gpt-6.1-sol") class RewrittenQuery(BaseModel): query: str def rewrite_query(state: State) -> dict: """Rewrite the user query for better retrieval.""" system_prompt = """Rewrite this query to retrieve relevant WNBA information. The knowledge base contains: team rosters, game results with scores, and player statistics (PPG, RPG, APG). Focus on specific player names, team names, or stat categories mentioned.""" response = model.with_structured_output(RewrittenQuery).invoke([ {"role": "system", "content": system_prompt}, {"role": "user", "content": state["question"]} ]) return {"rewritten_query": response.query} def retrieve(state: State) -> dict: """Retrieve documents based on the rewritten query.""" docs = retriever.invoke(state["rewritten_query"]) return {"documents": [doc.page_content for doc in docs]} def call_agent(state: State) -> dict: """Generate answer using retrieved context.""" context = "\n\n".join(state["documents"]) prompt = f"Context:\n{context}\n\nQuestion: {state['question']}" response = agent.invoke({"messages": [{"role": "user", "content": prompt}]}) return {"answer": response["messages"][-1].content_blocks} workflow = ( StateGraph(State) .add_node("rewrite", rewrite_query) .add_node("retrieve", retrieve) .add_node("agent", call_agent) .add_edge(START, "rewrite") .add_edge("rewrite", "retrieve") .add_edge("retrieve", "agent") .add_edge("agent", END) .compile() ) result = workflow.invoke({"question": "Who won the 2024 WNBA Championship?"}) print(result["answer"]) ``` 在生产过程中,使用持久性矢量存储器,例如: [瓦基语Name](<https://docs.langchain.com/oss/python/integrations/vectorstores/valkey>), [数据砖矢量搜索](<https://docs.langchain.com/oss/python/integrations/vectorstores/databricks_vector_search>),或 [MongoDB 地图集](<https://docs.langchain.com/oss/python/integrations/vectorstores/mongodb_atlas>) 改为 `InMemoryVectorStore`。见 [所有向量存储](<https://docs.langchain.com/oss/python/integrations/vectorstores>). --- [连接这些文件](<https://docs.langchain.com/use-these-docs>) 通过 MCP 向您选择的代理提供实时答案。 [在 GitHub 上编辑此页面](<https://github.com/langchain-ai/docs/edit/main/src/oss/langchain/multi-agent/custom-workflow.mdx>) 或 时 间 [提交一个问题](<https://github.com/langchain-ai/docs/issues/new/choose>). 这页有用吗?

查看原始来源