用路由机制构建多源知识库

介绍一种多智能体路由方案,将查询分类后并行分发给代码、文档、讨论等专用智能体,再统一汇总为连贯回答,并说明分类与合成两个阶段的作用。

## 概览 那个... **路由器图案** 是一个 [multi-agent](<https://docs.langchain.com/oss/python/langchain/multi-agent>) 将投入分类并引导给专门人员,并将结果综合成一个综合反应的架构。 **垂直数** (将每个领域都需要自己的代理人具有专门工具和提示的知识领域分开。)在这个教程中,您将建立一个多来源的知识库路由器,通过现实的企业方案展示这些好处。该系统将协调三名专家: - A **GitHub 代理服务器** 搜索代码、问题和调用请求。 - A **名称代理** 搜索内部文档和维基文库 - A **私密代理商** 搜索相关的线索和讨论。 当用户问到“我如何认证API请求?” 时,路由器将查询分解成针对源的子问题,将它们平行地引导到相关代理,并将结果合成一个连贯的答案。 ### 为什么要用路由器? 路由器模式提供了几个优点: - **并行执行**:同时查询多种来源,与相继方法相比降低耐久性. - **专门代理商**:每个垂直都有针对其域的焦点工具和提示优化. - **选择路径**:不是每个查询都需要每个来源——路由器明智地选择了相关的垂直. - **目标分问题**:每个代理都收到适合其领域的问题,提高结果质量. - **清洁合成**: 多个来源的结果合并为一个单一、连贯的反应。 ### 概念 我们将涵盖以下概念: - [多代理系统](<https://docs.langchain.com/oss/python/langchain/multi-agent>) - [StateGraph](<https://docs.langchain.com/oss/python/langgraph/graph-api>) 用于工作流程协调 - [发送 API](<https://docs.langchain.com/oss/python/langgraph/graph-api#send>) 并行执行 **路由器对子代理**编号: [子剂图案](<https://docs.langchain.com/oss/python/langchain/multi-agent/subagents>) 当您需要专门的预处理、自定义的路由逻辑或者想要对并行执行进行明确的控制时,使用路由器模式。如果您想要使用 LLM 决定哪些代理动态调用,则使用子代理模式。 ## 设置 ### 安装 此教程要求 `langchain` 财务报告和财务报告 `langgraph` 软件包 : ``` pip install langchain langgraph ``` ``` uv add langchain langgraph ``` ``` conda install langchain langgraph -c conda-forge ``` 详细情况请见我们 [安装指南](<https://docs.langchain.com/oss/python/langchain/install>). ### LangSmith 设置 [LangSmith](<https://smith.langchain.com/?utm_source=docs&utm_medium=cta&utm_campaign=langsmith-signup&utm_content=oss-langchain-multi-agent-router-knowledge-base>) 以检查您的代理服务器内发生的情况。然后设置以下环境变量: ``` export LANGSMITH_TRACING="true" export LANGSMITH_API_KEY="..." ``` ``` import getpass import os os.environ["LANGSMITH_TRACING"] = "true" os.environ["LANGSMITH_API_KEY"] = getpass.getpass() ``` ### 选择一个 LLM 从 LangChain 的整合套件中选择聊天模式 : - OpenAI - 人类 - 阿苏雷 - 谷歌双子座 - AWS 贝德洛克 - HuggingFace - OpenRouter 读吧 [OpenAI 聊天模式集成文件](<https://docs.langchain.com/oss/python/integrations/chat/openai/>) ``` pip install -U "langchain[openai]" ``` ``` uv add "langchain[openai]" ``` ``` import os from langchain.chat_models import init_chat_model os.environ["OPENAI_API_KEY"] = "sk-..." model = init_chat_model("gpt-6.1-sol") ``` ``` import os from langchain_openai import ChatOpenAI os.environ["OPENAI_API_KEY"] = "sk-..." model = ChatOpenAI(model="gpt-6.1-sol") ``` 读吧 [Anthropic 聊天模式集成文件](<https://docs.langchain.com/oss/python/integrations/chat/anthropic/>) ``` pip install -U "langchain[anthropic]" ``` ``` uv add "langchain[anthropic]" ``` ``` import os from langchain.chat_models import init_chat_model os.environ["ANTHROPIC_API_KEY"] = "sk-..." model = init_chat_model("claude-sonnet-4-6") ``` ``` import os from langchain_anthropic import ChatAnthropic os.environ["ANTHROPIC_API_KEY"] = "sk-..." model = ChatAnthropic(model="claude-sonnet-4-6") ``` 读吧 [Azure 聊天模式集成文件](<https://docs.langchain.com/oss/python/integrations/chat/azure_chat_openai/>) ``` pip install -U "langchain[openai]" ``` ``` uv add "langchain[openai]" ``` ``` import os from langchain.chat_models import init_chat_model os.environ["AZURE_OPENAI_API_KEY"] = "..." os.environ["AZURE_OPENAI_ENDPOINT"] = "..." os.environ["OPENAI_API_VERSION"] = "2025-03-01-preview" model = init_chat_model( "azure_openai:gpt-6.1-sol", azure_deployment=os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"], ) ``` ``` import os from langchain_openai import AzureChatOpenAI os.environ["AZURE_OPENAI_API_KEY"] = "..." os.environ["AZURE_OPENAI_ENDPOINT"] = "..." os.environ["OPENAI_API_VERSION"] = "2025-03-01-preview" model = AzureChatOpenAI( model="gpt-6.1-sol", azure_deployment=os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"] ) ``` 读吧 [Google GenAI 聊天模式集成文件](<https://docs.langchain.com/oss/python/integrations/chat/google_generative_ai/>) ``` pip install -U "langchain[google-genai]" ``` ``` uv add "langchain[google-genai]" ``` ``` import os from langchain.chat_models import init_chat_model os.environ["GOOGLE_API_KEY"] = "..." model = init_chat_model("google_genai:gemini-4-hydrogen") ``` ``` import os from langchain_google_genai import ChatGoogleGenerativeAI os.environ["GOOGLE_API_KEY"] = "..." model = ChatGoogleGenerativeAI(model="gemini-4-hydrogen") ``` 读吧 [AWS Bedrock 聊天模式集成文件](<https://docs.langchain.com/oss/python/integrations/chat/bedrock/>) ``` pip install -U "langchain[aws]" ``` ``` uv add "langchain[aws]" ``` ``` from langchain.chat_models import init_chat_model # Follow the steps here to configure your credentials: # https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html model = init_chat_model( "us.anthropic.claude-sonnet-4-6", model_provider="bedrock_converse", ) ``` ``` from langchain_aws import ChatBedrock model = ChatBedrock(model="us.anthropic.claude-sonnet-4-6") ``` 读吧 [HuggingFace 聊天模式集成文件](<https://docs.langchain.com/oss/python/integrations/chat/huggingface/>) ``` pip install -U "langchain[huggingface]" ``` ``` uv add "langchain[huggingface]" ``` ``` import os from langchain.chat_models import init_chat_model os.environ["HUGGINGFACEHUB_API_TOKEN"] = "hf_..." model = init_chat_model( "microsoft/Phi-3-mini-4k-instruct", model_provider="huggingface", temperature=0.7, max_tokens=1024, ) ``` ``` import os from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint os.environ["HUGGINGFACEHUB_API_TOKEN"] = "hf_..." llm = HuggingFaceEndpoint( repo_id="microsoft/Phi-3-mini-4k-instruct", temperature=0.7, max_length=1024, ) model = ChatHuggingFace(llm=llm) ``` 读吧 [OpenRouter 聊天模式集成文件](<https://docs.langchain.com/oss/python/integrations/chat/openrouter/>) ``` pip install -U "langchain-openrouter" ``` ``` uv add "langchain-openrouter" ``` ``` import os from langchain.chat_models import init_chat_model os.environ["OPENROUTER_API_KEY"] = "sk-..." model = init_chat_model( "auto", model_provider="openrouter", ) ``` ``` import os from langchain_openrouter import ChatOpenRouter os.environ["OPENROUTER_API_KEY"] = "sk-..." model = ChatOpenRouter(model="auto") ``` ## 1. 定义状态 首先,定义国家计划。我们使用三种类型: - **`AgentInput`**: 简单状态传递给每个子代理( 只是查询) - **`AgentOutput`**: 每个子代理返回的结果(来源名称+结果) - **`RouterState`**: 主要工作流程状态跟踪查询、分类、结果和最后答案 ``` from typing import Annotated, Literal, TypedDict import operator class AgentInput(TypedDict): """Simple input state for each subagent.""" query: str class AgentOutput(TypedDict): """Output from each subagent.""" source: str result: str class Classification(TypedDict): """A single routing decision: which agent to call with what query.""" source: Literal["github", "notion", "slack"] query: str class RouterState(TypedDict): query: str classifications: list[Classification] results: Annotated[list[AgentOutput], operator.add] # Reducer collects parallel results final_answer: str ``` 那个... `results` 字段使用 a **减号** (`operator.add` 在 Python 中, JS 中的一种 concat函数,用于将并行代理处决的输出收集到一个单一的列表中. ## 2. 为每个垂直定义工具 为每个知识域创建工具。 在生产系统中, 这些工具将调用实际的 API。 对于此教程, 我们使用返回模拟数据的 stub 执行。 我们定义了 7 工具, 横跨 3 垂直: GitHub( 搜索代码、 问题、 PRs) 、 Notion( 搜索文件, 获取页面) 和 Slack( 搜索消息, 获取线索) 。 ``` from langchain.tools import tool @tool def search_code(query: str, repo: str = "main") -> str: """Search code in GitHub repositories.""" return f"Found code matching '{query}' in {repo}: authentication middleware in src/auth.py" @tool def search_issues(query: str) -> str: """Search GitHub issues and pull requests.""" return f"Found 3 issues matching '{query}': #142 (API auth docs), #89 (OAuth flow), #203 (token refresh)" @tool def search_prs(query: str) -> str: """Search pull requests for implementation details.""" return f"PR #156 added JWT authentication, PR #178 updated OAuth scopes" @tool def search_notion(query: str) -> str: """Search Notion workspace for documentation.""" return f"Found documentation: 'API Authentication Guide' - covers OAuth2 flow, API keys, and JWT tokens" @tool def get_page(page_id: str) -> str: """Get a specific Notion page by ID.""" return f"Page content: Step-by-step authentication setup instructions" @tool def search_slack(query: str) -> str: """Search Slack messages and threads.""" return f"Found discussion in #engineering: 'Use Bearer tokens for API auth, see docs for refresh flow'" @tool def get_thread(thread_id: str) -> str: """Get a specific Slack thread.""" return f"Thread discusses best practices for API key rotation" ``` ## 3. 创建专门代理 为每个垂直创建代理。 每个代理都有特定域的工具, 并且对其知识源进行了快速优化。 这三个代理都遵循相同的模式—— 只有工具和系统提示不同 。 ``` from langchain.agents import create_agent from langchain.chat_models import init_chat_model model = init_chat_model("openai:gpt-6.1-sol") github_agent = create_agent( model, tools=[search_code, search_issues, search_prs], system_prompt=( "You are a GitHub expert. Answer questions about code, " "API references, and implementation details by searching " "repositories, issues, and pull requests." ), ) notion_agent = create_agent( model, tools=[search_notion, get_page], system_prompt=( "You are a Notion expert. Answer questions about internal " "processes, policies, and team documentation by searching " "the organization's Notion workspace." ), ) slack_agent = create_agent( model, tools=[search_slack, get_thread], system_prompt=( "You are a Slack expert. Answer questions by searching " "relevant threads and discussions where team members have " "shared knowledge and solutions." ), ) ``` ## 4. 构建路由器工作流程 现在使用 StateGraph 构建路由器工作流程。该工作流程有四个主要步骤: 1. **分类**: 分析查询并确定哪些代理人可与什么子问题一起引用 2. **路线**: 平行向选定的代理显示 `Send` 3. **查询代理**: 每个代理都收到一个简单的 `AgentInput` 返回一个 `AgentOutput` 4. **合成大小**:将收集的成果综合成协调一致的对策 ``` from pydantic import BaseModel, Field from langgraph.graph import StateGraph, START, END from langgraph.types import Send router_llm = init_chat_model("openai:gpt-5.4-mini") # Define structured output schema for the classifier class ClassificationResult(BaseModel): """Result of classifying a user query into agent-specific sub-questions.""" classifications: list[Classification] = Field( description="List of agents to invoke with their targeted sub-questions" ) def classify_query(state: RouterState) -> dict: """Classify query and determine which agents to invoke.""" structured_llm = router_llm.with_structured_output(ClassificationResult) result = structured_llm.invoke([ { "role": "system", "content": """Analyze this query and determine which knowledge bases to consult. For each relevant source, generate a targeted sub-question optimized for that source. Available sources: - github: Code, API references, implementation details, issues, pull requests - notion: Internal documentation, processes, policies, team wikis - slack: Team discussions, informal knowledge sharing, recent conversations Return ONLY the sources that are relevant to the query. Each source should have a targeted sub-question optimized for that specific knowledge domain. Example for "How do I authenticate API requests?": - github: "What authentication code exists? Search for auth middleware, JWT handling" - notion: "What authentication documentation exists? Look for API auth guides" (slack omitted because it's not relevant for this technical question)""" }, {"role": "user", "content": state["query"]} ]) return {"classifications": result.classifications} def route_to_agents(state: RouterState) -> list[Send]: """Fan out to agents based on classifications.""" return [ Send(c["source"], {"query": c["query"]}) for c in state["classifications"] ] def query_github(state: AgentInput) -> dict: """Query the GitHub agent.""" result = github_agent.invoke({ "messages": [{"role": "user", "content": state["query"]}] }) return {"results": [{"source": "github", "result": result["messages"][-1].content}]} def query_notion(state: AgentInput) -> dict: """Query the Notion agent.""" result = notion_agent.invoke({ "messages": [{"role": "user", "content": state["query"]}] }) return {"results": [{"source": "notion", "result": result["messages"][-1].content}]} def query_slack(state: AgentInput) -> dict: """Query the Slack agent.""" result = slack_agent.invoke({ "messages": [{"role": "user", "content": state["query"]}] }) return {"results": [{"source": "slack", "result": result["messages"][-1].content}]} def synthesize_results(state: RouterState) -> dict: """Combine results from all agents into a coherent answer.""" if not state["results"]: return {"final_answer": "No results found from any knowledge source."} # Format results for synthesis formatted = [ f"**From {r['source'].title()}:**\n{r['result']}" for r in state["results"] ] synthesis_response = router_llm.invoke([ { "role": "system", "content": f"""Synthesize these search results to answer the original question: "{state['query']}" - Combine information from multiple sources without redundancy - Highlight the most relevant and actionable information - Note any discrepancies between sources - Keep the response concise and well-organized""" }, {"role": "user", "content": "\n\n".join(formatted)} ]) return {"final_answer": synthesis_response.content} ``` ## 5. 编译工作流程 现在通过将节点与边缘连接来组装工作流程。 关键是使用 `add_conditional_edges` 带有可允许并行执行的路由函数: ``` workflow = ( StateGraph(RouterState) .add_node("classify", classify_query) .add_node("github", query_github) .add_node("notion", query_notion) .add_node("slack", query_slack) .add_node("synthesize", synthesize_results) .add_edge(START, "classify") .add_conditional_edges("classify", route_to_agents, ["github", "notion", "slack"]) .add_edge("github", "synthesize") .add_edge("notion", "synthesize") .add_edge("slack", "synthesize") .add_edge("synthesize", END) .compile() ) ``` 那个... `add_conditional_edges` 调用将分类节点通过 `route_to_agents` 函数。何时 `route_to_agents` 返回多个 `Send` 对象,这些节点平行执行。 ## 6. 使用路由器 用跨多个知识域的查询测试您的路由器 : ``` result = workflow.invoke({ "query": "How do I authenticate API requests?" }) print("Original query:", result["query"]) print("\nClassifications:") for c in result["classifications"]: print(f" {c['source']}: {c['query']}") print("\n" + "=" * 60 + "\n") print("Final Answer:") print(result["final_answer"]) ``` 预期产出: ``` Original query: How do I authenticate API requests? Classifications: github: What authentication code exists? Search for auth middleware, JWT handling notion: What authentication documentation exists? Look for API auth guides ============================================================ Final Answer: To authenticate API requests, you have several options: 1. **JWT Tokens**: The recommended approach for most use cases. Implementation details are in `src/auth.py` (PR #156). 2. **OAuth2 Flow**: For third-party integrations, follow the OAuth2 flow documented in Notion's 'API Authentication Guide'. 3. **API Keys**: For server-to-server communication, use Bearer tokens in the Authorization header. For token refresh handling, see issue #203 and PR #178 for the latest OAuth scope updates. ``` 路由器对查询进行了分析,将其分类以确定要引用的物剂(GitHub和Notion,但对于这个技术问题没有Slack),同时询问了这两个物剂,并将结果合成一个连贯的答案. ## 7. 理解结构 路由器工作流程遵循一个明确的模式: ### 分类阶段 那个... `classify_query` 函数用途 **结构化产出** 用于分析用户的查询和确定要引用的代理商。这里是路径智能的居住地点 : - 使用 Pydan 模型( Python) 或 Zod schema( JS) 以确保有效输出 - 返回一个列表 `Classification` 对象,每个对象有一个 `source` 目标 `query` - 仅包括相关来源——不相关来源被略去 这种结构化的方法比自由形态的JSON解析更可靠,并使路由逻辑清晰. ### 与发送并行执行 那个... `route_to_agents` 函数映射分类到 `Send` 对象。 `Send` 指定要通过的目标节点和状态: ``` # Classifications: [{"source": "github", "query": "..."}, {"source": "notion", "query": "..."}] # Becomes: [Send("github", {"query": "..."}), Send("notion", {"query": "..."})] # Both agents execute simultaneously, each receiving only the query it needs ``` 每个代理节点都收到一个简单的 `AgentInput` 只需要一个 `query` 字段——不是完整的路由器状态。这样可以使界面保持干净和清晰。 ### 使用还原器收集结果 代理结果通过 a 返回主状态 **减号**。每个代理返回: ``` {"results": [{"source": "github", "result": "..."}]} ``` 减者(减者.`operator.add` 在 Python 中)将这些列表组合起来,将所有平行结果收集到 `state["results"]`. ### 综合阶段 在所有的特工完成后,我们... `synthesize_results` 函数对所收集结果的延展: - 等待所有平行分支完成( LangGraph 自动处理此功能) - 引用原始查询以确保答案地址是用户询问的 - 将来自所有来源的信息合并而不重复 **部分结果**:在这个教程中,所有选定的剂必须在合成前完成. ## 8. 完整实例 这些都用可操作的脚本来表达: 显示视图完整代码 ``` """ Multi-Source Knowledge Router Example This example demonstrates the router pattern for multi-agent systems. A router classifies queries, routes them to specialized agents in parallel, and synthesizes results into a combined response. """ import operator from typing import Annotated, Literal, TypedDict from langchain.agents import create_agent from langchain.chat_models import init_chat_model from langchain.tools import tool from langgraph.graph import StateGraph, START, END from langgraph.types import Send from pydantic import BaseModel, Field # State definitions class AgentInput(TypedDict): """Simple input state for each subagent.""" query: str class AgentOutput(TypedDict): """Output from each subagent.""" source: str result: str class Classification(TypedDict): """A single routing decision: which agent to call with what query.""" source: Literal["github", "notion", "slack"] query: str class RouterState(TypedDict): query: str classifications: list[Classification] results: Annotated[list[AgentOutput], operator.add] final_answer: str # Structured output schema for classifier class ClassificationResult(BaseModel): """Result of classifying a user query into agent-specific sub-questions.""" classifications: list[Classification] = Field( description="List of agents to invoke with their targeted sub-questions" ) # Tools @tool def search_code(query: str, repo: str = "main") -> str: """Search code in GitHub repositories.""" return f"Found code matching '{query}' in {repo}: authentication middleware in src/auth.py" @tool def search_issues(query: str) -> str: """Search GitHub issues and pull requests.""" return f"Found 3 issues matching '{query}': #142 (API auth docs), #89 (OAuth flow), #203 (token refresh)" @tool def search_prs(query: str) -> str: """Search pull requests for implementation details.""" return f"PR #156 added JWT authentication, PR #178 updated OAuth scopes" @tool def search_notion(query: str) -> str: """Search Notion workspace for documentation.""" return f"Found documentation: 'API Authentication Guide' - covers OAuth2 flow, API keys, and JWT tokens" @tool def get_page(page_id: str) -> str: """Get a specific Notion page by ID.""" return f"Page content: Step-by-step authentication setup instructions" @tool def search_slack(query: str) -> str: """Search Slack messages and threads.""" return f"Found discussion in #engineering: 'Use Bearer tokens for API auth, see docs for refresh flow'" @tool def get_thread(thread_id: str) -> str: """Get a specific Slack thread.""" return f"Thread discusses best practices for API key rotation" # Models and agents model = init_chat_model("openai:gpt-6.1-sol") router_llm = init_chat_model("openai:gpt-5.4-mini") github_agent = create_agent( model, tools=[search_code, search_issues, search_prs], system_prompt=( "You are a GitHub expert. Answer questions about code, " "API references, and implementation details by searching " "repositories, issues, and pull requests." ), ) notion_agent = create_agent( model, tools=[search_notion, get_page], system_prompt=( "You are a Notion expert. Answer questions about internal " "processes, policies, and team documentation by searching " "the organization's Notion workspace." ), ) slack_agent = create_agent( model, tools=[search_slack, get_thread], system_prompt=( "You are a Slack expert. Answer questions by searching " "relevant threads and discussions where team members have " "shared knowledge and solutions." ), ) # Workflow nodes def classify_query(state: RouterState) -> dict: """Classify query and determine which agents to invoke.""" structured_llm = router_llm.with_structured_output(ClassificationResult) result = structured_llm.invoke([ { "role": "system", "content": """Analyze this query and determine which knowledge bases to consult. For each relevant source, generate a targeted sub-question optimized for that source. Available sources: - github: Code, API references, implementation details, issues, pull requests - notion: Internal documentation, processes, policies, team wikis - slack: Team discussions, informal knowledge sharing, recent conversations Return ONLY the sources that are relevant to the query.""" }, {"role": "user", "content": state["query"]} ]) return {"classifications": result.classifications} def route_to_agents(state: RouterState) -> list[Send]: """Fan out to agents based on classifications.""" return [ Send(c["source"], {"query": c["query"]}) for c in state["classifications"] ] def query_github(state: AgentInput) -> dict: """Query the GitHub agent.""" result = github_agent.invoke({ "messages": [{"role": "user", "content": state["query"]}] }) return {"results": [{"source": "github", "result": result["messages"][-1].content}]} def query_notion(state: AgentInput) -> dict: """Query the Notion agent.""" result = notion_agent.invoke({ "messages": [{"role": "user", "content": state["query"]}] }) return {"results": [{"source": "notion", "result": result["messages"][-1].content}]} def query_slack(state: AgentInput) -> dict: """Query the Slack agent.""" result = slack_agent.invoke({ "messages": [{"role": "user", "content": state["query"]}] }) return {"results": [{"source": "slack", "result": result["messages"][-1].content}]} def synthesize_results(state: RouterState) -> dict: """Combine results from all agents into a coherent answer.""" if not state["results"]: return {"final_answer": "No results found from any knowledge source."} formatted = [ f"**From {r['source'].title()}:**\n{r['result']}" for r in state["results"] ] synthesis_response = router_llm.invoke([ { "role": "system", "content": f"""Synthesize these search results to answer the original question: "{state['query']}" - Combine information from multiple sources without redundancy - Highlight the most relevant and actionable information - Note any discrepancies between sources - Keep the response concise and well-organized""" }, {"role": "user", "content": "\n\n".join(formatted)} ]) return {"final_answer": synthesis_response.content} # Build workflow workflow = ( StateGraph(RouterState) .add_node("classify", classify_query) .add_node("github", query_github) .add_node("notion", query_notion) .add_node("slack", query_slack) .add_node("synthesize", synthesize_results) .add_edge(START, "classify") .add_conditional_edges("classify", route_to_agents, ["github", "notion", "slack"]) .add_edge("github", "synthesize") .add_edge("notion", "synthesize") .add_edge("slack", "synthesize") .add_edge("synthesize", END) .compile() ) if __name__ == "__main__": result = workflow.invoke({ "query": "How do I authenticate API requests?" }) print("Original query:", result["query"]) print("\nClassifications:") for c in result["classifications"]: print(f" {c['source']}: {c['query']}") print("\n" + "=" * 60 + "\n") print("Final Answer:") print(result["final_answer"]) ``` ## 9. 高级: 状态路由器 目前我们建造的路由器是: **无国籍人** (每个请求都是独立处理的,在呼叫之间没有内存。)对于多回合对话,您需要一个 **状态** 办法。 ### 工具包装方法 加入对话记忆的最简单方式是将无国籍的路由器包起来,作为对话代理人可以使用的工具: ``` from langgraph.checkpoint.memory import InMemorySaver @tool def search_knowledge_base(query: str) -> str: """Search across multiple knowledge sources (GitHub, Notion, Slack). Use this to find information about code, documentation, or team discussions. """ result = workflow.invoke({"query": query}) return result["final_answer"] conversational_agent = create_agent( model, tools=[search_knowledge_base], system_prompt=( "You are a helpful assistant that answers questions about our organization. " "Use the search_knowledge_base tool to find information across our code, " "documentation, and team discussions." ), checkpointer=InMemorySaver(), ) ``` 这种方法使路由器处于无国籍状态,而对话代理则处理内存和上下文. 用户可以进行多回合对话,代理商会根据需要调用路由器工具. ``` config = {"configurable": {"thread_id": "user-123"}} result = conversational_agent.invoke( {"messages": [{"role": "user", "content": "How do I authenticate API requests?"}]}, config ) print(result["messages"][-1].content) result = conversational_agent.invoke( {"messages": [{"role": "user", "content": "What about rate limiting for those endpoints?"}]}, config ) print(result["messages"][-1].content) ``` 工具包装方法被推荐给大多数使用的案例. 它提供干净的分离:路由器处理多源查询,而对话代理则处理上下文和内存. ### 完全坚持不懈的做法 如果您需要路由器本身来维持状态——例如,在路由决定中使用先前的搜索结果——使用 [持久性](<https://docs.langchain.com/oss/python/langchain/short-term-memory>) 以将消息历史存储在路由器级别。 **状态路由器增加了复杂性.** 如果代理商有不同的音调或提示,在向不同的代理商传送时,对话可能会感到不一致。 [交割模式](<https://docs.langchain.com/oss/python/langchain/multi-agent/handoffs>) 或 时 间 [子剂图案](<https://docs.langchain.com/oss/python/langchain/multi-agent/subagents>) 相反,两者都为与不同代理人的多回合对话提供了更明确的语义。 ## 10. 关键外卖 路由器图案在您有时优异 : - **区分的垂直**: 各自需要专门工具和提示的单独知识领域 - **并行查询需要**: 同时查询多个来源而有好处的问题 - **综合要求**· 需要将多种来源的成果纳入协调一致的应对措施 模式分三个阶段: **分解** (分析查询并生成有针对性的子问题), **路径** (并行执行询问),和 **合成** (压缩结果). **何时使用路由器模式**当您拥有多个独立知识源,需要低常态并行查询,并需要明确控制路由逻辑时,使用路由器模式。对于带有动态工具选择的更简单的情况,请考虑 [子剂图案](<https://docs.langchain.com/oss/python/langchain/multi-agent/subagents>)。对于代理商需要依次与用户交谈的工作流程,请考虑 [分发](<https://docs.langchain.com/oss/python/langchain/multi-agent/handoffs>). ## 今后的步骤 - 学习关于 [分发](<https://docs.langchain.com/oss/python/langchain/multi-agent/handoffs>) 用于 agent-to-agent 对话 - 探索 [子剂图案](<https://docs.langchain.com/oss/python/langchain/multi-agent/subagents-personal-assistant>) 用于集中管弦乐 - 读读 [多代理概览](<https://docs.langchain.com/oss/python/langchain/multi-agent>) 比较不同的模式 - 使用( U) [LangSmith](<https://smith.langchain.com/?utm_source=docs&utm_medium=cta&utm_campaign=langsmith-signup&utm_content=oss-langchain-multi-agent-router-knowledge-base>) 调试并监视您的路由器 --- [连接这些文件](<https://docs.langchain.com/use-these-docs>) 通过 MCP 向您选择的代理提供实时答案。 [在 GitHub 上编辑此页面](<https://github.com/langchain-ai/docs/edit/main/src/oss/langchain/multi-agent/router-knowledge-base.mdx>) 或 时 间 [提交一个问题](<https://github.com/langchain-ai/docs/issues/new/choose>). 这页有用吗?

查看原始来源