AG2开源项目使用教程
1. 项目介绍
AG2(原名AutoGen)是一个开源的AgentOS,旨在构建AI代理并促进多个代理之间的协作以解决任务。AG2旨在简化代理AI的开发和研究工作。它提供了多种特性,如支持代理之间相互交互、使用大型语言模型(LLM)和工具支持、自主和人工参与的流程以及多代理对话模式等。
AG2目前由来自不同组织的志愿者团队维护。如果您有兴趣成为维护者,可以通过support@ag2.ai联系项目管理员Chi Wang和Qingyun Wu。
2. 项目快速启动
安装
AG2需要Python版本大于等于3.9且小于3.14。AG2可以通过PyPI上的ag2
(或其别名pyautogen
或autogen
)进行安装。
pip install ag2[openai]
默认情况下会安装最小依赖项。根据需要的特性,您可以安装额外的选项。
配置API密钥
为了方便管理LLM依赖,建议使用OAI_CONFIG_LIST
文件存储您的API密钥。您可以使用示例文件OAI_CONFIG_LIST_sample
作为模板。
[
{
"model": "gpt-4o",
"api_key": "<你的OpenAI API密钥>"
}
]
运行第一个代理
创建一个脚本或Jupyter Notebook,并运行您的第一个代理。
from autogen import AssistantAgent, UserProxyAgent, LLMConfig
# 加载LLM配置
llm_config = LLMConfig.from_json(path="OAI_CONFIG_LIST")
with llm_config:
# 创建助理代理
assistant = AssistantAgent("assistant")
# 创建用户代理
user_proxy = UserProxyAgent("user_proxy", code_execution_config={"work_dir": "coding", "use_docker": False})
# 用户代理与助理代理开始对话
user_proxy.initiate_chat(assistant, message="Plot a chart of NVDA and TESLA stock price change YTD.")
3. 应用案例和最佳实践
AG2提供了多种代理概念,以帮助您构建AI代理。以下是一些常见案例:
对话型代理
能够发送消息、接收消息并使用GenAI模型、非GenAI工具或人工输入生成回复的代理。
from autogen import ConversableAgent
with llm_config:
# 创建AI代理
assistant = ConversableAgent(name="assistant", system_message="You are an assistant that responds concisely.")
# 创建事实检查代理
fact_checker = ConversableAgent(name="fact_checker", system_message="You are a fact-checking assistant.")
# 开始对话
assistant.initiate_chat(recipient=fact_checker, message="What is AG2?", max_turns=2)
人工参与模式
当工作流程需要人工输入时,可以启用人工参与模式。
from autogen import UserProxyAgent
with llm_config:
# 创建助理代理
assistant = ConversableAgent(name="assistant", system_message="You are a helpful assistant.")
# 创建人工代理
human = UserProxyAgent(name="human", code_execution_config={"work_dir": "coding", "use_docker": False})
# 开始聊天
human.initiate_chat(recipient=assistant, message="Hello! What's 2 + 2?")
多代理协调
用户可以使用AG2的编程接口定义自己的协调模式,或者使用内置的群聊和群体模式。
from autogen import ConversableAgent, GroupChat, GroupChatManager
# 创建AI代理
teacher = ConversableAgent(name="teacher", system_message="You suggest lesson topics.")
planner = ConversableAgent(name="planner", system_message="You create lesson plans.")
reviewer = ConversableAgent(name="reviewer", system_message="You review lesson plans.")
# 创建群聊
groupchat = GroupChat(agents=[teacher, planner, reviewer], speaker_selection_method="auto")
# 创建群聊管理器
manager = GroupChatManager(name="manager", groupchat=groupchat)
# 开始对话
teacher.initiate_chat(manager, "Create a lesson on photosynthesis.")
4. 典型生态项目
AG2生态系统包含多种工具和项目,这些项目可以与AG2协同工作,以提供更丰富的工作流和解决方案。这些项目包括但不限于数据存储、API接口、前端界面等,旨在与AG2代理无缝集成,构建更加完善的应用程序。由于篇幅限制,这里不一一介绍,您可以在AG2的官方文档中找到更多相关信息。