跳到内容

如何使用 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 参考: 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 平台部署它。有关更多详细信息,请参阅这些说明