ag2ai/ag2
GitHub: ag2ai/ag2
AG2 是一个开源的多智能体协作框架,旨在简化 AI Agent 的开发与多 Agent 间的协同工作,帮助用户快速构建复杂的 Agentic 工作流。
Stars: 4521 | Forks: 621
📚 文档 |
💡 示例 |
🤝 参与贡献 |
📝 引用论文 |
💬 加入 Discord
AG2 由 AutoGen 演进而来。完全开源。我们邀请所有组织的合作者共同参与贡献。
# AG2:面向 AI Agent 的开源 AgentOS
AG2(前身为 AutoGen)是一个开源编程框架,用于构建 AI Agent 并促进多个 Agent 之间的协作以解决任务。AG2 旨在简化 Agentic AI 的开发与研究。它提供了诸多功能,例如支持 Agent 之间相互交互、方便使用各种大型语言模型 (LLM) 和工具、支持自主和 Human-in-the-Loop 工作流,以及多 Agent 对话模式。
该项目目前由来自多个组织的[活跃的志愿者团队](MAINTAINERS.md)维护。如果您有兴趣成为维护者,请通过 [support@ag2.ai](mailto:support@ag2.ai) 联系项目管理员 Chi Wang 和 Qingyun Wu。
## 目录
- [AG2:面向 AI Agent 的开源 AgentOS](#ag2-open-source-agentos-for-ai-agents)
- [目录](#table-of-contents)
- [快速入门](#getting-started)
- [安装说明](#installation)
- [设置 API 密钥](#setup-your-api-keys)
- [运行你的第一个 Agent](#run-your-first-agent)
- [示例应用](#example-applications)
- [不同 Agent 概念介绍](#introduction-of-different-agent-concepts)
- [对话 Agent](#conversable-agent)
- [编排多个 Agent](#orchestrating-multiple-agents)
- [Human in the Loop](#human-in-the-loop)
- [工具](#tools)
- [高级 Agentic 设计模式](#advanced-agentic-design-patterns)
- [公告](#announcements)
- [代码风格和 Linting](#code-style-and-linting)
- [相关论文](#related-papers)
- [贡献者墙](#contributors-wall)
- [引用本项目](#cite-the-project)
- [许可证](#license)
## 快速入门
有关 AG2 概念和代码的分步介绍,请参阅我们文档中的[基本概念](https://docs.ag2.ai/latest/docs/user-guide/basic-concepts/installing-ag2/)。
### 安装说明
AG2 需要 **Python 版本 >= 3.10**。你可以通过 PyPI 上的 `ag2`(或其别名 `autogen`)进行安装。
**Windows/Linux:**
```
pip install ag2[openai]
```
**Mac:**
```
pip install 'ag2[openai]'
```
默认情况下会安装最小依赖。您可以根据所需功能安装额外的选项。
### 设置 API 密钥
为了保持您的 LLM 依赖项整洁,并避免在代码中意外提交您的 API 密钥,我们建议将您的密钥存储在配置文件中。
在我们的示例中,我们使用一个名为 **`OAI_CONFIG_LIST`** 的文件来存储 API 密钥。您可以选择任何文件名,但请确保将其添加到 `.gitignore` 中,这样它就不会被提交到源代码控制中。
您可以使用以下内容作为模板:
```
[
{
"model": "gpt-5",
"api_key": "
"
}
]
```
### 运行你的第一个 Agent
创建一个脚本或 Jupyter Notebook 并运行你的第一个 Agent。
```
from autogen import AssistantAgent, UserProxyAgent, LLMConfig
llm_config = LLMConfig.from_json(path="OAI_CONFIG_LIST")
assistant = AssistantAgent("assistant", llm_config=llm_config)
user_proxy = UserProxyAgent("user_proxy", code_execution_config={"work_dir": "coding", "use_docker": False})
user_proxy.run(assistant, message="Summarize the main differences between Python lists and tuples.").process()
```
## 示例应用
我们维护着一个包含大量应用程序的专用代码库,以帮助您在各种用例中快速入门,或者您也可以查看我们的 Jupyter Notebook 集合作为起点。
- [使用 AG2 构建](https://github.com/ag2ai/build-with-ag2)
- [Jupyter Notebooks](notebook)
## 不同 Agent 概念介绍
AG2 中有多个 Agent 概念可帮助您构建 AI Agent。我们在此介绍最常见的一些。
- **对话 Agent (Conversable Agent)**:能够使用 GenAI 模型、非 GenAI 工具或人类输入来发送消息、接收消息和生成回复的 Agent。
- **Human in the loop**:将人类输入添加到对话中
- **编排多个 Agent**:用户可以使用内置的对话模式(如 Swarm、群聊、嵌套聊天、顺序聊天)来编排多个 Agent,或者通过注册自定义回复方法来自定义编排。
- **工具**:可由 Agent 注册、调用和执行的程序
- **高级概念**:AG2 支持更多概念,例如结构化输出、RAG、代码执行等。
### 对话 Agent
[ConversableAgent](https://docs.ag2.ai/latest/docs/api-reference/autogen/ConversableAgent) 是 AG2 的基础构建块,旨在实现 AI 实体之间的无缝通信。这种核心 Agent 类型负责处理消息交换和响应生成,是框架中所有 Agent 的基类。
让我们从一个简单的示例开始,其中两个 Agent 相互协作:
- 一个负责编写 Python 代码的 **coder Agent**。
- 一个负责审查代码而不重写代码的 **reviewer Agent**。
```
import logging
from autogen import ConversableAgent, LLMConfig
# 配置 logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# 加载 LLM 配置
llm_config = LLMConfig.from_json(path="OAI_CONFIG_LIST")
# 定义 agents
coder = ConversableAgent(
name="coder",
system_message="You are a Python developer. Write short Python scripts.",
llm_config=llm_config,
)
reviewer = ConversableAgent(
name="reviewer",
system_message="You are a code reviewer. Analyze provided code and suggest improvements. "
"Do not generate code, only suggest improvements.",
llm_config=llm_config,
)
# 开始对话
response = reviewer.run(
recipient=coder,
message="Write a Python function that computes Fibonacci numbers.",
max_turns=10
)
response.process()
logger.info("Final output:\n%s", response.summary)
```
### 编排多个 Agent
AG2 通过灵活的编排模式支持复杂的多 Agent 协作,允许您创建由专门的 Agent 共同协作解决复杂问题的动态系统。
以下是如何构建一个由 **teacher**(教师)、**lesson planner**(课程规划师)和 **reviewer**(审查员)Agent 组成的团队,共同设计课程计划的示例:
```
import logging
from autogen import ConversableAgent, LLMConfig
from autogen.agentchat import run_group_chat
from autogen.agentchat.group.patterns import AutoPattern
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
llm_config = LLMConfig.from_json(path="OAI_CONFIG_LIST")
# 定义 lesson planner 和 reviewer
planner_message = "You are a classroom lesson planner. Given a topic, write a lesson plan for a fourth grade class."
reviewer_message = "You are a classroom lesson reviewer. Compare the plan to the curriculum and suggest up to 3 improvements."
lesson_planner = ConversableAgent(
name="planner_agent",
system_message=planner_message,
description="Creates or revises lesson plans.",
llm_config=llm_config,
)
lesson_reviewer = ConversableAgent(
name="reviewer_agent",
system_message=reviewer_message,
description="Provides one round of feedback to lesson plans.",
llm_config=llm_config,
)
teacher_message = "You are a classroom teacher. You decide topics and collaborate with planner and reviewer to finalize lesson plans. When satisfied, output DONE!"
teacher = ConversableAgent(
name="teacher_agent",
system_message=teacher_message,
is_termination_msg=lambda x: "DONE!" in (x.get("content", "") or "").upper(),
llm_config=llm_config,
)
auto_selection = AutoPattern(
agents=[teacher, lesson_planner, lesson_reviewer],
initial_agent=lesson_planner,
group_manager_args={"name": "group_manager", "llm_config": llm_config},
)
response = run_group_chat(
pattern=auto_selection,
messages="Let's introduce our kids to the solar system.",
max_rounds=20,
)
response.process()
logger.info("Final output:\n%s", response.summary)
```
### Human in the Loop
人工监督通常对于验证或指导 AI 输出至关重要。
AG2 提供了 `UserProxyAgent` 以实现人工反馈的无缝集成。
在这里,我们扩展了 **teacher-planner-reviewer** 示例,引入了一个 **human Agent** 来验证最终的课程:
```
import logging
from autogen import ConversableAgent, LLMConfig, UserProxyAgent
from autogen.agentchat import run_group_chat
from autogen.agentchat.group.patterns import AutoPattern
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
llm_config = LLMConfig.from_json(path="OAI_CONFIG_LIST")
# 与之前的 agents 相同,但现在 human validator 将传递给 planner,planner 将检查 "APPROVED" 并终止
planner_message = "You are a classroom lesson planner. Given a topic, write a lesson plan for a fourth grade class."
reviewer_message = "You are a classroom lesson reviewer. Compare the plan to the curriculum and suggest up to 3 improvements."
teacher_message = "You are an experienced classroom teacher. You don't prepare plans, you provide simple guidance to the planner to prepare a lesson plan on the key topic."
lesson_planner = ConversableAgent(
name="planner_agent",
system_message=planner_message,
description="Creates or revises lesson plans before having them reviewed.",
is_termination_msg=lambda x: "APPROVED" in (x.get("content", "") or "").upper(),
human_input_mode="NEVER",
llm_config=llm_config,
)
lesson_reviewer = ConversableAgent(
name="reviewer_agent",
system_message=reviewer_message,
description="Provides one round of feedback to lesson plans back to the lesson planner before requiring the human validator.",
llm_config=llm_config,
)
teacher = ConversableAgent(
name="teacher_agent",
system_message=teacher_message,
description="Provides guidance on the topic and content, if required.",
llm_config=llm_config,
)
human_validator = UserProxyAgent(
name="human_validator",
system_message="You are a human educator who provides final approval for lesson plans.",
description="Evaluates the proposed lesson plan and either approves it or requests revisions, before returning to the planner.",
)
auto_selection = AutoPattern(
agents=[teacher, lesson_planner, lesson_reviewer],
initial_agent=teacher,
user_agent=human_validator,
group_manager_args={"name": "group_manager", "llm_config": llm_config},
)
response = run_group_chat(
pattern=auto_selection,
messages="Let's introduce our kids to the solar system.",
max_rounds=20,
)
response.process()
logger.info("Final output:\n%s", response.summary)
```
### 工具
Agent 通过**工具**获得极大的实用性,这些工具通过外部数据、API 或函数扩展了它们的能力。
```
import logging
from datetime import datetime
from typing import Annotated
from autogen import ConversableAgent, register_function, LLMConfig
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
llm_config = LLMConfig.from_json(path="OAI_CONFIG_LIST")
# Tool: 返回给定日期的 weekday
def get_weekday(date_string: Annotated[str, "Format: YYYY-MM-DD"]) -> str:
date = datetime.strptime(date_string, "%Y-%m-%d")
return date.strftime("%A")
date_agent = ConversableAgent(
name="date_agent",
system_message="You find the day of the week for a given date.",
llm_config=llm_config,
)
executor_agent = ConversableAgent(
name="executor_agent",
human_input_mode="NEVER",
llm_config=llm_config,
)
# 注册 tool
register_function(
get_weekday,
caller=date_agent,
executor=executor_agent,
description="Get the day of the week for a given date",
)
# 在 chat 中使用 tool
chat_result = executor_agent.initiate_chat(
recipient=date_agent,
message="I was born on 1995-03-25, what day was it?",
max_turns=2,
)
logger.info("Final output:\n%s", chat_result.chat_history[-1]["content"])
```
### 高级 Agentic 设计模式
AG2 支持更多高级概念来帮助您构建 AI Agent 工作流。您可以在文档中找到更多信息。
- [结构化输出](https://docs.ag2.ai/latest/docs/user-guide/basic-concepts/structured-outputs)
- [结束对话](https://docs.ag2.ai/latest/docs/user-guide/advanced-concepts/orchestration/ending-a-chat/)
- [检索增强生成 (RAG)](https://docs.ag2.ai/latest/docs/user-guide/advanced-concepts/rag/)
- [代码执行](https://docs.ag2.ai/latest/docs/user-guide/advanced-concepts/code-execution)
- [带有 Secrets 的工具](https://docs.ag2.ai/latest/docs/user-guide/advanced-concepts/tools/tools-with-secrets/)
- [模式手册(9 种群组编排)](https://docs.ag2.ai/latest/docs/user-guide/advanced-concepts/pattern-cookbook/overview/)
## 公告
🔥 🎉 **2024 年 11 月 11 日:** 我们正在将 AutoGen 演进为 **AG2**!
我们创建了一个新组织 [AG2AI](https://github.com/ag2ai),以开放治理的方式托管 AG2 及相关项目的开发。请查看 [AG2 的新面貌](https://ag2.ai/)。
📄 **许可证:**
我们从 v0.3 版本开始采用 Apache 2.0 许可证。这加强了我们对开源协作的承诺,同时为贡献者和用户提供了额外的保护。
🎉 2024 年 5 月 29 日:DeepLearning.ai 推出了一门新的短期课程 [AI Agentic Design Patterns with AutoGen](https://www.deeplearning.ai/short-courses/ai-agentic-design-patterns-with-autogen),该课程由 Microsoft 和宾夕法尼亚州立大学联合制作,并由 AutoGen 创建者 [Chi Wang](https://github.com/sonichi) 和 [Qingyun Wu](https://github.com/qingyun-wu) 主讲。
🎉 2024 年 5 月 24 日:Foundation Capital 在 [Forbes: The Promise of Multi-Agent AI](https://www.forbes.com/sites/joannechen/2024/05/24/the-promise-of-multi-agent-ai/?sh=2c1e4f454d97) 上发表了一篇文章,并发布了一期视频 [AI in the Real World Episode 2: Exploring Multi-Agent AI and AutoGen with Chi Wang](https://www.youtube.com/watch?v=RLwyXRVvlNk)。
🎉 2024 年 4 月 17 日:Andrew Ng 在红杉资本的 AI Ascent 活动(3 月 26 日)上的 [The Batch newsletter](https://www.deeplearning.ai/the-batch/issue-245/) 和 [What's next for AI agentic workflows](https://youtu.be/sal78ACtGTc?si=JduUzN_1kDnMq0vF) 中引用了 AutoGen。
[更多公告](announcements.md)
## 代码风格和 Linting
本项目使用 [prek](https://github.com/j178/prek) 钩子来维护代码质量。在贡献之前:
1. 安装 prek:
```
pip install prek
prek install
```
2. 这些钩子将在提交时自动运行,您也可以手动运行它们:
```
prek run --all-files
```
## 相关论文
- [AutoGen: Enabling Next-Gen LLM Applications via Multi-Agent Conversation](https://arxiv.org/abs/2308.08155)
- [EcoOptiGen: Hyperparameter Optimization for Large Language Model Generation Inference](https://arxiv.org/abs/2303.04673)
- [MathChat: Converse to Tackle Challenging Math Problems with LLM Agents](https://arxiv.org/abs/2306.01337)
- [AgentOptimizer: Offline Training of Language Model Agents with Functions as Learnable Weights](https://arxiv.org/pdf/2402.11359)
- [StateFlow: Enhancing LLM Task-Solving through State-Driven Workflows](https://arxiv.org/abs/2403.11322)
## 引用本项目
```
@software{AG2_2024,
author = {Chi Wang and Qingyun Wu and the AG2 Community},
title = {AG2: Open-Source AgentOS for AI Agents},
year = {2024},
url = {https://github.com/ag2ai/ag2},
note = {Available at https://docs.ag2.ai/},
version = {latest}
}
```
## 许可证
本项目基于 [Apache License, Version 2.0 (Apache-2.0)](./LICENSE) 授权。
本项目是 [AutoGen](https://github.com/microsoft/autogen) 的衍生项目,包含基于双重许可证的代码:
- 来自 https://github.com/microsoft/autogen 的原始代码采用 MIT 许可证授权。有关详细信息,请参阅 [LICENSE_original_MIT](./license_original/LICENSE_original_MIT) 文件。
- 此 fork 中所做的修改和新增内容采用 Apache License, Version 2.0 授权。完整的许可证文本请参阅 [LICENSE](./LICENSE) 文件。
为了清晰起见,并确保对我们的用户和贡献者社区保持透明,我们已将这些更改记录在案。有关更多详细信息,请参阅 [NOTICE](./NOTICE.md) 文件。 标签:AG2, AgentOS, AI开发工具, AI编程框架, AutoGen, C2, DLL 劫持, LLM, Petitpotam, PyRIT, Python, Unmanaged PE, 人工智能, 多智能体协作, 多智能体系统, 大模型, 大语言模型, 工作流编排, 开源框架, 持续集成, 无后门, 用户模式Hook绕过, 网络调试, 自动化, 请求拦截, 逆向工具