如何在5分钟内搭建你的第一个LangGraph Swarm多智能体应用
【免费下载链接】langgraph-swarm-py 项目地址: https://gitcode.com/gh_mirrors/la/langgraph-swarm-py
LangGraph Swarm是一个强大的多智能体框架,能帮助开发者快速构建协作型AI应用。本文将带你在5分钟内完成第一个多智能体应用的搭建,无需复杂编程知识,让你轻松入门智能体协作开发。
📋 准备工作:环境搭建
首先确保你的开发环境满足以下要求:
- Python 3.8+
- pip或uv包管理器
- OpenAI API密钥(用于运行示例)
通过以下命令克隆项目并安装依赖:
git clone https://gitcode.com/gh_mirrors/la/langgraph-swarm-py
cd langgraph-swarm-py
pip install -e .
🧠 多智能体协作原理
LangGraph Swarm的核心优势在于实现智能体间的无缝协作。下图展示了一个典型的多智能体交互流程:
从图中可以看到,当用户请求"预订航班"时,系统会自动激活航班代理(Flight Agent)处理请求;完成后,通过"Handoff tool"将任务无缝转交给酒店代理(Hotel Agent),实现跨智能体的任务协作。
🚀 快速上手:客户支持多智能体示例
项目提供了完整的客户支持多智能体示例,位于examples/customer_support/src/agent/customer_support.py。这个示例创建了两个协作智能体:
- 航班代理(Flight Agent):处理航班查询和预订
- 酒店代理(Hotel Agent):处理酒店查询和预订
核心实现步骤
-
定义工具函数:创建搜索和预订的工具函数
def search_flights(departure_airport: str, arrival_airport: str, date: str) -> list[dict]: # 航班搜索逻辑 def book_flight(flight_id: str, config: RunnableConfig) -> str: # 航班预订逻辑 -
创建智能体:使用
create_agent函数定义智能体及其工具集flight_assistant = create_agent( model, tools=[search_flights, book_flight, transfer_to_hotel_assistant], system_prompt=make_prompt("You are a flight booking assistant"), name="flight_assistant", ) -
构建智能体集群:使用
create_swarm组合多个智能体builder = create_swarm( [flight_assistant, hotel_assistant], default_active_agent="flight_assistant" ) app = builder.compile()
🔬 进阶示例:研究型多智能体系统
另一个实用示例是研究型智能体系统,位于examples/research/src/agent/agent.py。这个示例展示了如何构建:
- 规划代理(Planner Agent):负责任务规划和需求分析
- 研究代理(Researcher Agent):负责执行具体研究任务
通过create_handoff_tool函数,实现智能体间的任务交接:
transfer_to_researcher_agent = create_handoff_tool(
agent_name="researcher_agent",
description="Transfer the user to the researcher_agent to perform research",
)
💡 运行与测试
要运行客户支持示例,执行以下命令:
cd examples/customer_support
python src/agent/customer_support.py
系统会启动一个交互式对话界面,你可以尝试输入:
- "帮我预订明天从BOS到JFK的航班"
- "然后帮我在纽约订个酒店"
智能体将自动完成航班预订,并无缝转交给酒店代理继续处理你的请求。
📚 深入学习资源
- 核心框架代码:
langgraph_swarm/swarm.py - 智能体交接工具:
langgraph_swarm/handoff.py - 更多示例:
examples/目录下包含多种应用场景
通过本文的步骤,你已经成功搭建了一个功能完整的多智能体应用。LangGraph Swarm的灵活性让你可以轻松扩展更多智能体类型,实现更复杂的协作任务。现在就开始探索构建你自己的智能体集群吧!
【免费下载链接】langgraph-swarm-py 项目地址: https://gitcode.com/gh_mirrors/la/langgraph-swarm-py
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考




