Skip to content

如何使用 LangGraph 平台部署 CrewAI、AutoGen 和其他框架

LangGraph 平台 提供了用于部署代理的基础设施。它与 LangGraph 无缝集成,也可以与其他框架一起使用。实现这一点的方法是将代理封装在一个单独的 LangGraph 节点中,并让该节点成为整个图。

这样做将允许你将应用部署到 LangGraph 平台,并获得许多 优势。你可以获得水平可扩展的基础设施、一个任务队列来处理突发操作、一个持久化层以支持短期记忆,以及长期记忆的支持。

在本指南中,我们将展示如何使用 AutoGen 代理实现这一点,但这种方法也适用于使用其他框架(如 CrewAI、LlamaIndex 等)定义的代理。

设置

%pip install autogen langgraph
import getpass
import os


def _set_env(var: str):
    if not os.environ.get(var):
        os.environ[var] = getpass.getpass(f"{var}: ")


_set_env("OPENAI_API_KEY")

定义 autogen 代理

在此我们定义我们的 AutoGen 代理。来自 https://github.com/microsoft/autogen/blob/0.2/notebook/agentchat_web_info.ipynb

import autogen
import os

config_list = [{"model": "gpt-4o", "api_key": os.environ["OPENAI_API_KEY"]}]

llm_config = {
    "timeout": 600,
    "cache_seed": 42,
    "config_list": config_list,
    "temperature": 0,
}

autogen_agent = autogen.AssistantAgent(
    name="assistant",
    llm_config=llm_config,
)

user_proxy = autogen.UserProxyAgent(
    name="user_proxy",
    human_input_mode="NEVER",
    max_consecutive_auto_reply=10,
    is_termination_msg=lambda x: x.get("content", "").rstrip().endswith("TERMINATE"),
    code_execution_config={
        "work_dir": "web",
        "use_docker": False,
    },  # Please set use_docker=True if docker is available to run the generated code. Using docker is safer than running the generated code directly.
    llm_config=llm_config,
    system_message="Reply TERMINATE if the task has been solved at full satisfaction. Otherwise, reply CONTINUE, or the reason why the task is not solved yet.",
)

用 LangGraph 包装

我们现在将 AutoGen 代理包装成一个单独的 LangGraph 节点,并使其成为整个图。 这主要涉及为该节点定义输入和输出模式,如果你手动部署此节点,也需要进行这样的操作,因此不会有额外的工作。

API Reference: StateGraph

from langgraph.graph import StateGraph, MessagesState


def call_autogen_agent(state: MessagesState):
    last_message = state["messages"][-1]
    response = user_proxy.initiate_chat(autogen_agent, message=last_message.content)
    # get the final response from the agent
    content = response.chat_history[-1]["content"]
    return {"messages": {"role": "assistant", "content": content}}


graph = StateGraph(MessagesState)
graph.add_node(call_autogen_agent)
graph.set_entry_point("call_autogen_agent")
graph = graph.compile()

使用 LangGraph 平台部署

你现在可以像平常一样使用 LangGraph 平台进行部署。如需更多细节,请参阅这些说明