Skip to content

如何将LangGraph与AutoGen、CrewAI和其他框架集成

LangGraph是一个用于构建代理和多代理应用程序的框架。LangGraph可以轻松地与其他代理框架集成。

您可能希望将LangGraph与其他代理框架集成的主要原因:

集成其他框架中的代理最简单的方法是在LangGraph的节点中调用这些代理:

from langgraph.graph import StateGraph, MessagesState, START

autogen_agent = autogen.AssistantAgent(name="assistant", ...)
user_proxy = autogen.UserProxyAgent(name="user_proxy", ...)

def call_autogen_agent(state: MessagesState):
    response = user_proxy.initiate_chat(
        autogen_agent,
        message=state["messages"][-1],
        ...
    )
    ...

graph = (
    StateGraph(MessagesState)
    .add_node(call_autogen_agent)
    .add_edge(START, "call_autogen_agent")
    .compile()
)

graph.invoke({
    "messages": [
        {
            "role": "user",
            "content": "Find numbers between 10 and 30 in fibonacci sequence",
        }
    ]
})

在此指南中,我们将展示如何构建一个与AutoGen集成的LangGraph聊天机器人,但您也可以使用相同的方法与其他框架集成。

设置

%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")
OPENAI_API_KEY:  ········

定义AutoGen代理

在这里我们定义我们的AutoGen代理。改编自官方教程此处

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.",
)

创建图

我们现在将创建一个调用AutoGen代理的LangGraph聊天机器人图。

from langchain_core.messages import convert_to_openai_messages
from langgraph.graph import StateGraph, MessagesState, START
from langgraph.checkpoint.memory import MemorySaver


def call_autogen_agent(state: MessagesState):
    # convert to openai-style messages
    messages = convert_to_openai_messages(state["messages"])
    response = user_proxy.initiate_chat(
        autogen_agent,
        message=messages[-1],
        # pass previous message history as context
        carryover=messages[:-1],
    )
    # get the final response from the agent
    content = response.chat_history[-1]["content"]
    return {"messages": {"role": "assistant", "content": content}}


# add short-term memory for storing conversation history
checkpointer = MemorySaver()

builder = StateGraph(MessagesState)
builder.add_node(call_autogen_agent)
builder.add_edge(START, "call_autogen_agent")
graph = builder.compile(checkpointer=checkpointer)

API Reference: convert_to_openai_messages | StateGraph | START | MemorySaver

from IPython.display import display, Image

display(Image(graph.get_graph().draw_mermaid_png()))

运行图

我们现在可以运行这个图了。

# pass the thread ID to persist agent outputs for future interactions
config = {"configurable": {"thread_id": "1"}}

for chunk in graph.stream(
    {
        "messages": [
            {
                "role": "user",
                "content": "Find numbers between 10 and 30 in fibonacci sequence",
            }
        ]
    },
    config,
):
    print(chunk)
user_proxy (to assistant):

Find numbers between 10 and 30 in fibonacci sequence

--------------------------------------------------------------------------------
assistant (to user_proxy):

To find numbers between 10 and 30 in the Fibonacci sequence, we can generate the Fibonacci sequence and check which numbers fall within this range. Here's a plan:

1. Generate Fibonacci numbers starting from 0.
2. Continue generating until the numbers exceed 30.
3. Collect and print the numbers that are between 10 and 30.

Let's implement this in Python:

\`\`\`python
# filename: fibonacci_range.py

def fibonacci_sequence():
    a, b = 0, 1
    while a <= 30:
        if 10 <= a <= 30:
            print(a)
        a, b = b, a + b

fibonacci_sequence()
\`\`\`

This script will print the Fibonacci numbers between 10 and 30. Please execute the code to see the result.

--------------------------------------------------------------------------------

>>>>>>>> EXECUTING CODE BLOCK 0 (inferred language is python)...
user_proxy (to assistant):

exitcode: 0 (execution succeeded)
Code output: 
13
21


--------------------------------------------------------------------------------
assistant (to user_proxy):

The Fibonacci numbers between 10 and 30 are 13 and 21. 

These numbers are part of the Fibonacci sequence, which is generated by adding the two preceding numbers to get the next number, starting from 0 and 1. 

The sequence goes: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

As you can see, 13 and 21 are the only numbers in this sequence that fall between 10 and 30.

TERMINATE

--------------------------------------------------------------------------------
{'call_autogen_agent': {'messages': {'role': 'assistant', 'content': 'The Fibonacci numbers between 10 and 30 are 13 and 21. \n\nThese numbers are part of the Fibonacci sequence, which is generated by adding the two preceding numbers to get the next number, starting from 0 and 1. \n\nThe sequence goes: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...\n\nAs you can see, 13 and 21 are the only numbers in this sequence that fall between 10 and 30.\n\nTERMINATE'}}}
由于我们利用了LangGraph的持久性特性,我们现在可以继续使用相同的线程ID进行对话——LangGraph会自动将之前的对话历史传递给AutoGen代理:

for chunk in graph.stream(
    {
        "messages": [
            {
                "role": "user",
                "content": "Multiply the last number by 3",
            }
        ]
    },
    config,
):
    print(chunk)
user_proxy (to assistant):

Multiply the last number by 3
Context: 
Find numbers between 10 and 30 in fibonacci sequence
The Fibonacci numbers between 10 and 30 are 13 and 21. 

These numbers are part of the Fibonacci sequence, which is generated by adding the two preceding numbers to get the next number, starting from 0 and 1. 

The sequence goes: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

As you can see, 13 and 21 are the only numbers in this sequence that fall between 10 and 30.

TERMINATE

--------------------------------------------------------------------------------
assistant (to user_proxy):

The last number in the Fibonacci sequence between 10 and 30 is 21. Multiplying 21 by 3 gives:

21 * 3 = 63

TERMINATE

--------------------------------------------------------------------------------
{'call_autogen_agent': {'messages': {'role': 'assistant', 'content': 'The last number in the Fibonacci sequence between 10 and 30 is 21. Multiplying 21 by 3 gives:\n\n21 * 3 = 63\n\nTERMINATE'}}}

Comments