🤖 LangGraph 多智能体群集

LangGraph 多智能体群集是一种 Python 库,用于创建基于 LangGraph 的多智能体系统。这种系统允许智能体根据其专业化动态地将控制权交给彼此,并记住最后活跃的智能体,以便在后续交互中继续对话。

基础概念

  • 多智能体协作:不同智能体可以合作并将上下文传递给彼此。
  • 可定制的交接工具:内置工具用于智能体之间的通信。

安装和快速开始

  1. 安装库

    bash 复制代码
    pip install langgraph-swarm langchain-openai
  2. 设置 OpenAI API

    bash 复制代码
    export OPENAI_API_KEY=
  3. 创建智能体

    python 复制代码
    from langchain_openai import ChatOpenAI
    from langgraph.checkpoint.memory import InMemorySaver
    from langgraph.prebuilt import create_react_agent
    from langgraph_swarm import create_handoff_tool, create_swarm
    
    # 创建模型
    model = ChatOpenAI(model="gpt-4o")
    
    # 定义加法函数
    def add(a: int, b: int) -> int:
        return a + b
    
    # 创建 Alice 智能体
    alice = create_react_agent(
        model,
        [add, create_handoff_tool(agent_name="Bob")],
        prompt="You are Alice, an addition expert.",
        name="Alice",
    )
    
    # 创建 Bob 智能体
    bob = create_react_agent(
        model,
        [create_handoff_tool(agent_name="Alice", description="Transfer to Alice, she can help with math")],
        prompt="You are Bob, you speak like a pirate.",
        name="Bob",
    )
    
    # 创建群集
    checkpointer = InMemorySaver()
    workflow = create_swarm([alice, bob], default_active_agent="Alice")
    app = workflow.compile(checkpointer=checkpointer)
    
    # 与智能体交互
    config = {"configurable": {"thread_id": "1"}}
    turn_1 = app.invoke({"messages": [{"role": "user", "content": "i'd like to speak to Bob"}]}, config)
    print(turn_1)
    turn_2 = app.invoke({"messages": [{"role": "user", "content": "what's 5 + 7?"}]}, config)
    print(turn_2)

内存管理

  • 短期内存 :使用 InMemorySaver 来维持对话状态。
  • 长期内存 :使用 InMemoryStore 来存储历史数据。

自定义

  1. 自定义交接工具

    python 复制代码
    from langchain_core.tools import tool, BaseTool
    from langchain_core.messages import ToolMessage
    from langgraph.types import Command
    
    def create_custom_handoff_tool(*, agent_name: str, tool_name: str, tool_description: str) -> BaseTool:
        @tool(name=tool_name, description=tool_description)
        def handoff_to_agent(task_description: str, state: dict, tool_call_id: str):
            tool_message = ToolMessage(
                content=f"Successfully transferred to {agent_name}",
                name=tool_name,
                tool_call_id=tool_call_id,
            )
            return Command(
                goto=agent_name,
                graph=Command.PARENT,
                update={
                    "messages": [state["messages"][-1], tool_message],
                    "active_agent": agent_name,
                    "task_description": task_description,
                },
            )
    
        return handoff_to_agent
  2. 自定义智能体实现

    python 复制代码
    from langchain_core.messages import AnyMessage
    from langgraph.graph import StateGraph
    
    class AliceState:
        alice_messages: list[AnyMessage]
    
    alice = (
        StateGraph(AliceState)
        .add_node("model", ...)
        .add_node("tools", ...)
        .add_edge(...)
        .compile()
    )
    
    def call_alice(state):
        response = alice.invoke({"alice_messages": state["messages"]})
        return {"messages": response["alice_messages"]}
    
    workflow = (
        StateGraph()
        .add_node("Alice", call_alice, destinations=("Bob",))
        .add_node("Bob", call_bob, destinations=("Alice",))
    )
    workflow = add_active_agent_router(workflow, route_to=["Alice", "Bob"], default_active_agent="Alice")
    app = workflow.compile()

总结

LangGraph 多智能体群集提供了一个灵活的框架,用于创建多智能体系统。通过自定义交接工具和智能体实现,可以满足不同应用场景的需求。同时,内存管理对于维持对话状态至关重要。

相关推荐
周先生FullStack17 分钟前
Mac + 容器本地 MySQL/Redis 环境搭建与网络原理实战
java·spring boot·微服务·容器·架构·个人开发
All for pursuit.22 分钟前
FastAPI+Ollama 部署本地AI大模型对话助手
python·github·aigc·ollama
林川~011 小时前
Unity 反射(Reflection)从原理到实战:一篇讲透原理、用法、实战案例与性能优化
面试·性能优化·反射·il2cpp·type
晚安日记wanna1 小时前
React 为何不做双端 diff?Vue 与 React 更新逻辑的三层差异
前端·react.js·面试
我滴老baby1 小时前
部署 Excalidraw:Docker 搭建手绘白板,再配置固定公网访问
数据库·人工智能·架构
u1301302 小时前
GitHub 热榜项目:日榜(2026-09-18)
人工智能·github
天空属于哈夫克32 小时前
企业微信群映射表怎么建:群名不能当主键
架构·企业微信
keke.shengfengpolang2 小时前
2026年资金分析岗校招技术栈拆解:Excel预测模型、SQL取数、SAP与Oracle资金模块,附2027届备考路线
面试
顶点多余2 小时前
9.16 面试总结
linux·面试·职场和发展