跳至主要内容

AutoGen 教程:构建多智能体 AI 应用

学习如何使用 Autogen Studio、Autogen AgentChat、Autogen Core 和 Autogen Extensions 构建多智能体 AI 应用。
· 7分钟 阅读

使用 AI 探索

现代 AI 源于大型语言模型(LLM),随后引入了用于结构化输出的函数调用,接着发展出智能体与工具,进而催生了MCP 服务器。当下的重点是多智能体系统。各家公司都在寻找方案,利用多种工具构建智能自动化系统,而 AutoGen 是其中最受欢迎的选择。

在本教程中,我们将探索 AutoGen、其生态、各类用例,以及如何使用该生态中的各个组件。需要特别说明的是,AutoGen 不只是像 LangChain 那样的典型语言模型编排工具;它的能力远不止于此。

如果您是 AI 新手,请先完成AI 基础技能路径,再继续本教程。您也可以在另一篇文章中了解Agentic AI。

什么是 AutoGen?

AutoGen 是一个开源框架,用于创建可半自动或全自动运行的多智能体 AI 应用。它为开发者提供了构建系统的工具,使多个 AI 智能体能够相互通信、协作并共同完成任务。

AutoGen 支持广泛的用例,包括自动化工作流、多智能体协作和动态任务求解。它允许开发者创建这样一些系统:智能体可以通过自然语言交互、执行代码、检索信息,并适应复杂的工作流。

AutoGen 生态由四个主要组件构成:

  1. AutoGen Studio: 一个零代码图形界面,用于构建和测试多智能体工作流。
  2. AutoGent AgentChat: 一个简化的 API,用于构建对话式的单智能体和多智能体应用。
  3. AutoGen Core:构建可扩展多智能体 AI 系统的基础 API。
  4. AutoGen Extension: 官方与第三方扩展库,用于拓展框架能力。

AutoGen 生态系统示意图

来源:microsoft/AutoGen

AutoGen 的优势体现在:

  • 简化复杂 LLM 工作流的编排与优化。
  • 提升 LLM 的表现,同时弥补其局限。
  • 无缝创建整合 LLM、工具与人类输入的多智能体系统。

其可扩展与模块化特性,使其成为跨行业开发者的强大工具,从金融、医疗到教育与机器人领域皆适用。

阅读理解 AI 智能体:自主系统的未来,了解如何在项目中利用 AI 智能体推动创新与效率。

开始使用 AutoGen 生态

本节将通过本地安装与运行,带您了解 AutoGen 生态的四个主要组件。

1. AutoGen Studio

AutoGen Studio 是一款低代码界面,助您快速原型化 AI 智能体。它提供友好的拖放界面,用于创建多智能体系统并实时测试。

1. 使用 pip 命令安装 Studio。

pip install -U AutoGenstudio

2. 安装完成后,您可以通过指定端口和应用目录(用于存储所有智能体与模板)来启动 AutoGen Studio 的 UI。

AutoGenstudio ui --port 8080 --appdir ./app

运行命令后,您应在终端看到如下输出:

INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
2025-05-09 15:15:22.825 | INFO     | AutoGenstudio.web.app:lifespan:39 - Application startup complete. Navigate to http://127.0.0.1:8080

3. 在浏览器中访问 http://127.0.0.1:8080 以打开 AutoGen Studio 仪表盘。

应用启动后,您将看到简洁直观的用户界面。

AutoGen Studio 提供多项关键功能,帮助您构建与管理多智能体工作流:

  1. Team Builder:用于创建智能体团队的拖放界面。
  2. Playground:用于测试与运行智能体工作流的交互环境。
  3. Gallery:发现与导入社区创建组件的中心。
  4. Labs:AutoGen Studio 的实验性功能,允许用户探索高级工作流并原型化前沿想法。
  5. Deploy:将智能体工作流导出并以 Python 代码运行。

AutogGen Studio

AutoGen Studio 是一款低代码应用,这意味着您几乎无需编码即可构建工作流。同时,它也提供使用 Python 代码自定义智能体与工作流的灵活性。

在 AutoGen Studio 中编辑组件

2. AutoGen AgentChat

AgentChat 是一个用于创建多智能体对话式工作流的高级框架。它简化了构建多智能体(AI、工具或人类)协作解决任务类应用的过程。

首先,安装所需软件包:

pip install -U "AutoGen-agentchat" "AutoGen-ext[openai]"

接下来我们将设置三个智能体——一位用户、一名编码器和一名代码执行器——在轮询式群聊中协作生成、执行并讲解 Python 代码。该系统旨在促进动态的代码生成与执行,同时支持人类交互与终止条件。

在本示例中,我们使用 gpt-4.1-mini 模型进行代码生成,使用 CodeExecutorAgent 进行命令行代码执行,UserProxyAgent 用于将人类保持在闭环中。

import asyncio
from pathlib import Path

from AutoGen_agentchat.agents import AssistantAgent, CodeExecutorAgent, UserProxyAgent
from AutoGen_agentchat.conditions import TextMentionTermination
from AutoGen_agentchat.teams import RoundRobinGroupChat
from AutoGen_agentchat.ui import Console
from AutoGen_ext.code_executors.local import LocalCommandLineCodeExecutor
from AutoGen_ext.models.openai import OpenAIChatCompletionClient

async def main() -> None:
    model_client = OpenAIChatCompletionClient(model="gpt-4.1-mini")

    coder = AssistantAgent(
        "coder",
        model_client=model_client,
        system_message=(
            "You are a senior engineer. Think step-by-step, then output ONLY runnable "
            "Python inside ```pythonthon``` blocks—no commentary."
        ),
    )

    executor = CodeExecutorAgent(
        "executor",
        model_client=model_client,  # lets it narrate results
        code_executor=LocalCommandLineCodeExecutor(work_dir=Path.cwd() / "runs"),
    )

    user = UserProxyAgent("user")  # human in the loop

    termination = TextMentionTermination("exit", sources=["user"])
    team = RoundRobinGroupChat(
        [user, coder, executor], termination_condition=termination
    )

    try:
        await Console(
            team.run_stream()
        )
    finally:
        await model_client.close()

if __name__ == "__main__":
    asyncio.run(main())

将上述代码保存为 chat_app.py,并通过以下命令运行:

python chat_app.py 

我们让该智能体应用生成用于打印三角形星号的代码,并执行该代码。

它成功生成并执行了代码,同时还提供了进一步的选项。用户可以输入“exit”退出,或提出后续问题继续对话。

输出:

Enter your response: Write a Python script that prints stars and run it.
---------- TextMessage (user) ----------
Write a Python script that prints stars and run it.
---------- TextMessage (coder) ----------
# Print a simple star pattern
for i in range(1, 6):
    print('*' * i)
---------- CodeGenerationEvent (executor) ----------
# Print a simple star pattern
for i in range(1, 6):
    print('*' * i)
---------- CodeExecutionEvent (executor) ----------

*

**

***

****

*****

---------- TextMessage (executor) ----------

The star pattern has been printed successfully. If you'd like a different pattern or further modifications, just let me know!

Enter your response:

3. AutoGen Core

AutoGen Core 是一个低层框架,提供强大的方式来创建与管理多智能体系统。

在这个示例中,我们将创建两个智能体:一个将消息内容反转的 Echo 智能体,以及一个将消息内容打印到控制台的 Printer 智能体。

pip install "autogen-core"

本应用使用的组件:

  1. 消息结构:Text 类是一个简单的数据结构,用于保存消息内容。
  1. Echo 智能体: Echo 智能体会将接收到的任何消息内容反转,并使用 publish_message 将反转后的消息发布到默认主题。
  1. Printer 智能体: Printer 智能体会监听消息,并将其内容打印到控制台。
  1. 运行时: 使用 SingleThreadedAgentRuntime 管理智能体的生命周期并处理消息路由。
import asyncio
from dataclasses import dataclass

from AutoGen_core import (
    AgentId,
    DefaultTopicId,
    MessageContext,
    RoutedAgent,
    SingleThreadedAgentRuntime,
    default_subscription,
    message_handler,
)

@dataclass
class Text:
    content: str

@default_subscription
class Echo(RoutedAgent):
    def __init__(self) -> None:
        super().__init__("echo")

    @message_handler
    async def handle(self, message: Text, ctx: MessageContext) -> None:  # param must be named 'message'
        await self.publish_message(Text(message.content[::-1]), DefaultTopicId())

@default_subscription
class Printer(RoutedAgent):
    def __init__(self) -> None:
        super().__init__("printer")

    @message_handler
    async def handle(self, message: Text, ctx: MessageContext) -> None:  # param must be named 'message'
        print(message.content)

async def main() -> None:
    rt = SingleThreadedAgentRuntime()
    await Echo.register(rt, "echo", lambda: Echo())
    await Printer.register(rt, "printer", lambda: Printer())
    rt.start()
    await rt.send_message(Text("DataCamp"), AgentId("echo", "default"))
    await rt.stop_when_idle()

if __name__ == "__main__":
    asyncio.run(main())

将代码保存为 core_app.py,并通过以下命令运行:

python core_app.py            

消息流:

  • 内容为 "DataCamp" 的消息被发送至 Echo 智能体。
  • Echo 智能体将消息反转为 "pmaCataD" 并发布。
  • Printer 智能体接收反转后的消息并打印到控制台。

输出:

pmaCataD

4. AutoGen 扩展

AutoGen Extensions 框架提供官方与第三方扩展,用于拓展框架能力。

在本示例中,我们将演示如何使用 MultimodalWebSurfer 智能体,它能够与网页交互、执行搜索并提取信息。

运行示例前,请确保已安装 Playwright:

playwright install 

代码工作原理:

  1. 智能体初始化:创建一个 MultimodalWebSurfer 智能体,使用 OpenAI 的 gpt-4.1-mini 模型进行决策,并通过 Playwright 控制浏览器进行网页交互。
  2. 团队设置: 将该智能体加入 RoundRobinGroupChat 团队,由其管理工作流,并将任务限制为 3 轮。
  3. 任务执行: 指示团队执行任务:“打开 Google 并搜索 Abid Ali Awan 的相关信息。” 智能体将打开浏览器、导航至 Google、执行搜索,并提取相关信息。
  4. 流式输出: 智能体的操作(如导航、点击链接、提取元数据)将实时流式输出到控制台。
  5. 清理: 任务完成后将关闭浏览器以释放资源。
import asyncio
from AutoGen_agentchat.ui import Console
from AutoGen_agentchat.teams import RoundRobinGroupChat
from AutoGen_ext.models.openai import OpenAIChatCompletionClient
from AutoGen_ext.agents.web_surfer import MultimodalWebSurfer

async def main() -> None:
    # Define an agent
    web_surfer_agent = MultimodalWebSurfer(
        name="MultimodalWebSurfer",
        model_client=OpenAIChatCompletionClient(model="gpt-4.1-mini"),
    )

    # Define a team
    agent_team = RoundRobinGroupChat([web_surfer_agent], max_turns=3)

    # Run the team and stream messages to the console
    stream = agent_team.run_stream(task="Navigate to Google and search about Abid Ali Awan.")
    await Console(stream)
    # Close the browser controlled by the agent
    await web_surfer_agent.close()

asyncio.run(main())

将代码保存为 web_ext_app.py,并通过以下命令运行:

python web_ext_app.py          

运行应用时,将会出现如下交互:

                                                           
---------- TextMessage (user) ----------
Navigate to Google and search about Abid Ali Awan.
---------- MultiModalMessage (MultimodalWebSurfer) ----------
I typed 'https://www.google.com' into the browser address bar.

The web browser is open to the page [Google](https://www.google.com/).
The viewport shows 100% of the webpage, and is positioned at the top of the page
The following text is visible in the viewport:

Gmail
Images
Sign in
Google offered in:
اردو
پښتو
سنڌيPakistan
About
Advertising
Business
 How Search works
Privacy
Terms
Settings
Google recommends using Chrome
Try a fast, secure browser with updates built in
Don't switch
Yes

The following metadata was extracted from the webpage:

{
    "microdata": [
        {
            "itemType": "http://schema.org/WebPage",
            "image": "/images/branding/googleg/1x/googleg_standard_color_128dp.png"
        }
    ],
    "meta_tags": {
        "referrer": "origin"
    }
}

Here is a screenshot of the page.
<image>
---------- MultiModalMessage (MultimodalWebSurfer) ----------
I clicked 'Sign in'.

The web browser is open to the page [Sign in - Google Accounts](https://accounts.google.com/v3/signin/identifier?continue=https%3A%2F%2Fwww.google.com%2F&ec=futura_exp_og_so_72776762_e&hl=en&ifkv=ASKV5MhAzFZnwDH-Aw10tuqQN1ppsY8OZ2-OJ3YavFHXMDlX9iTddg1d_k78ZZ0SogFUivcY7Td0Hg&passive=true&flowName=GlifWebSignIn&flowEntry=ServiceLogin&dsh=S1980923188%3A1746809726624486).
The viewport shows 100% of the webpage, and is positioned at the top of the page
The following text is visible in the viewport:

Sign inUse your Google AccountEmail or phone
Forgot email?
Not your computer? Use a private browsing window to sign in.
Learn more about using Guest modeNext
Create account
English (United States)
Help
Privacy
Terms
Sign in Use your Google Account

The following metadata was extracted from the webpage:

{
    "meta_tags": {
        "referrer": "origin",
        "chrome": "nointentdetection",
        "viewport": "width=device-width, initial-scale=1",
        "description": ""
    }
}

Here is a screenshot of the page.
<image>
---------- TextMessage (MultimodalWebSurfer) ----------
Please provide the email or phone number you want to use to sign in, or let me know if you want to create a new account or need help with something else on this page.

与 AutoGen 类似,CrewAI 也是另一款广受欢迎的用于构建 Agentic 工作流的框架。请参考教程CrewAI:多 AI 智能体系统指南与示例 了解更多。

AutoGen 的用例

AutoGen 为创建智能的多智能体系统打开了大量可能性。以下是 AutoGen 生态的一些典型用例:

  1. 代码生成、执行与调试: 自动化编码任务,降低错误并提升效率。
  2. 多智能体协作: 支持智能体团队合作,解决复杂任务。
  3. 序列式多智能体对话: 管理结构化任务序列以高效完成。
  4. 嵌套对话: 通过层次化对话处理复杂精细任务。
  5. 工具使用: 通过集成网页搜索、SQL 查询等工具扩展智能体功能。
  6. 人类参与: 融入人类反馈以改进工作流。
  7. 智能体教学与学习: 提升智能体技能与知识。
  8. 与 OpenAI Assistants 的多智能体对话: 将 OpenAI 能力与 AutoGen 结合以完成更高级任务。
  9. 多模态智能体: 处理文本、图像及其他媒体,带来更丰富的交互。
  10. 长上下文处理: 在长对话中保持连贯性。

结语

AutoGen 之所以备受关注与认可,并成为 GitHub 上获星最多的 Agentic 框架之一,自有其原因。

它是一个全面的框架,既适用于专业开发者,也适用于休闲编程者,甚至零编码经验的个人。

借助 AutoGen,您可以使用 AutoGen Studio 快速原型化工作流,借助 Core 框架与 Extensions 构建稳健应用,并无缝部署到云端。它确实是一套打造与管理智能多智能体系统的一体化解决方案。

学习构建动态 LangChain 智能体课程,使用流行的 LLM 框架构建您的首个 AI 智能体应用。

Abid Ali Awan

作者

Abid Ali Awan

作为一名持证的数据科学家,我热衷于利用前沿技术打造创新的机器学习应用。凭借在语音识别、数据分析与报告、MLOps、对话式人工智能以及自然语言处理方面的扎实背景,我不断打磨构建智能系统的能力,力求带来切实影响。除技术专长外,我也擅长沟通,能够将复杂概念提炼为清晰、简明的表述。因此,我成为数据科学领域备受关注的博主,与不断壮大的数据专业人士社区分享洞见与实践经验。目前,我专注于内容创作与编辑,借助大语言模型打造有力且吸引人的内容,帮助企业与个人更好地发挥数据价值。

主题