综合介绍
LangGraph Supervisor是一个基于LangGraph框架的Python库,专为创建和管理多智能体系统而设计。该库通过一个中央监督代理协调多个专门代理的工作,确保通信流和任务分配的高效管理。LangGraph Supervisor支持路由器和协调器模式,提供工具化的代理交接机制,灵活的消息历史管理,适用于流式处理、短期和长期记忆以及人类在环的应用场景。
功能列表
- 创建监督代理以协调多个专门代理
- 支持路由器和协调器模式
- 工具化的代理交接机制
- 灵活的消息历史管理
- 支持流式处理、短期和长期记忆
- 人类在环的应用场景支持
使用帮助
安装流程
- 确保已安装Python环境。
- 使用pip安装LangGraph Supervisor库:
pip install langgraph-supervisor
- 安装LangChain和OpenAI库:
pip install langchain-openai
- 设置OpenAI API密钥:
export OPENAI_API_KEY=<your_api_key>
使用示例
以下是一个简单的示例,展示如何使用LangGraph Supervisor管理两个专门代理:
- 导入必要的库和模块:
from langchain_openai import ChatOpenAI
from langgraph_supervisor import create_supervisor
from langgraph.prebuilt import create_react_agent
- 创建专门代理:
def add(a: float, b: float) -> float:
"""Add two numbers."""
return a + b
def multiply(a: float, b: float) -> float:
"""Multiply two numbers."""
return a * b
def web_search(query: str) -> str:
"""Search the web for information."""
return "Here are the headcounts for each of the FAANG companies in 2024:..."
model = ChatOpenAI(model="gpt-4o")
math_agent = create_react_agent(model=model, tools=[add, multiply], name="math_expert", prompt="You are a math expert. Always use one tool at a time.")
research_agent = create_react_agent(model=model, tools=[web_search], name="research_expert", prompt="You are a world class researcher with access to web search. Do not do any math.")
- 创建监督代理并编译运行:
workflow = create_supervisor([research_agent, math_agent], model=model, prompt="You are a team supervisor managing a research expert and a math expert.")
app = workflow.compile()
result = app.invoke({
"messages": [
{"role": "user", "content": "what's the combined headcount of the FAANG companies in 2024?"}
]
})
详细功能操作流程
- 创建监督代理:通过
create_supervisor
函数创建一个监督代理,负责协调多个专门代理的工作。 - 定义专门代理:使用
create_react_agent
函数定义不同功能的专门代理,如数学计算代理和网络搜索代理。 - 编译和运行工作流:通过
workflow.compile()
编译工作流,并使用app.invoke()
运行工作流,处理用户输入的消息并返回结果。
LangGraph Supervisor提供了灵活的多智能体系统管理方案,适用于各种复杂任务的自动化处理和协调。