探索 Autogen AG2 和 Semantic Kernel:AI 代理框架及其独特功能的综合指南
- Rifx.Online
- Machine Learning , AI Applications , AI Research
- 05 Mar, 2025
🚀 深入探讨 AutoGen (0.2 & 0.4)、AG2 和 Semantic Kernel — 探索 Agent 架构、使用所有框架的聊天等 🤖
图片由 Microsoft Designer 生成
1. 简介
随着人工智能 (AI) 🌍 的快速发展,开发人员和组织已经开始利用 AI 代理来构建自主系统 🤖。 AI 代理是独立的、以目标为导向的,可以自主地执行繁琐的任务。它可以感知、推理、行动和适应环境,这有助于我们实现任务自动化。代理架构 🏗️ 由编排器、模型、源、技能和工具组成。
标准的高级代理架构。图片来源 — 作者
2. 关于框架
有不同的框架可用,每个框架都有其自身的特点。在本博客中,我们将主要关注 AutoGen(实际上我最初使用它来探索代理)、AG2 和 Semantic Kernel,它们提供了独特的功能和能力。我们还将探索这些框架支持的不同聊天类型,以及有关为您的特定场景选择最合适的框架的示例和一些指导。
⚠️ 注意:本博客不是关于比较哪个框架是“最好的” 😉 — 而是关于了解它们的优势和用例。
让我们在高层次上了解一下这些框架:🔎
2.1 AutoGen:
AutoGen 框架的初始版本 v0.2 在代理技术中非常受欢迎,但在架构约束、有限的调试和发明能力方面存在一些问题。它需要更强的可观察性和控制、更灵活的多代理协作模式以及可重用的组件。
2.2 AutoGen v0.4:
这个版本几天前(1 月 14 日)发布,它从微软内部和外部资源提供的反馈中获得了强大且可扩展的功能。以下是几个重要的新功能:
✅ 异步消息传递:代理现在可以通过异步消息进行通信,具有事件驱动和请求/响应交互模式。
✅ 模块化和可扩展:我们可以使用可插拔组件轻松自定义系统,包括自定义代理、工具、内存和模型。此外,我们现在可以使用事件驱动模式构建主动且长时间运行的代理。
✅ 可观察性和调试:这是最需要的功能之一,内置的指标跟踪、消息跟踪和调试工具提供了对代理交互和工作流的监控和控制。
框架中的每一层都有明确划分的职责,并构建在下面的层之上。
- 核心 API:它实现了消息传递、事件驱动代理以及本地和分布式运行时,以实现灵活性和强大功能。
- AgentChat API:它构建在核心 API 之上,类似于 v0.2,是一种多代理模式,例如双代理聊天或群聊👥。
- 扩展 API: 这使得第一方和第三方扩展可以持续扩展框架功能。它支持 LLM 客户端的特定实现(例如,OpenAI、AzureOpenAI)以及代码执行等功能。
图片来源:microsoft.com/blogs
除了框架之外,AutoGen 0.4 还包括升级的编程工具和应用程序。
✅ AutoGen Bench:使用它可以衡量和比较代理在不同任务和环境中的性能,从而对代理进行基准测试。
✅ AutoGen Studio:它在 v0.4 上进行了完全重建,现在可以实现 AI 代理的快速原型设计,并具有几项新功能,以下是几个重要功能:实时代理更新,具有异步操作流、执行中控制,用于暂停、重定向和调整团队,以及消息流可视化,以获得更清晰的沟通见解。其拖放界面简化了代理团队的设计和配置。
✅ Magentic-One:一个新的通用多代理应用程序,用于解决跨各种领域的基于 Web 和文件的任务。该工具标志着朝着创建能够完成在工作和个人环境中遇到的常见任务的代理迈出了重要一步。
2.3 Semantic Kernel:
它更像是一个轻量级且开源的框架,允许我们构建 AI 代理并与最新的 AI 模型集成。它现在支持 3 种编程语言 — C#、Python 或 Java。它是企业级生产解决方案的高效中间件。 Semantic Kernel 代理框架在 Semantic Kernel 生态系统中提供了一个平台,用于创建 AI 代理并将代理模式合并到应用程序中。它的架构建立在几个关键组件之上:
✅ 代理:抽象的 Agent 类是所有代理类型的基础结构,子类 KernelAgent 直接与 Kernel 对象关联,通过该对象,我们可以创建 ChatCompletionAgent 和 OpenAI AssistantAgent 等代理。这些代理可以独立运行或在代理聊天中协作。
✅ 代理聊天:这允许各种代理进行对话。它管理聊天环境中的交互,而 AgentGroupChat 类通过使多个代理能够在同一对话中的众多交互中进行协作来扩展此功能。
✅ 代理通道:此类促进了不同代理类型参与 AgentChat,它对于创建自定义代理也至关重要。
该框架的设计与 Semantic Kernel 的核心原则保持一致,确保一致性和易于集成。通过利用作为驱动 AI 操作的中心对象的 Kernel,该框架支持创建智能、适应性强的代理,这些代理能够管理多个并发对话并在不同的场景中有效协作。
2.4 AG2:
AG2 不是一个新框架 — 它是 AutoGen 0.2.34 的重新命名 版本,现在以 AG2 的名称继续,最新版本为 0.3.2。
社区驱动,采用 开放 RFC 流程 🏗️。 保持了早期 AutoGen 版本的 熟悉的代理架构。 微软正在朝着不同的方向发展 AutoGen,而 AG2 保持社区主导。
AG2 的路线图和功能: 🌟 AG2 也有 AG2 Studio、AG2 Marketplace 和 Scaling Tools 的良好未来展望。它拥有 20k 活跃构建者、每日技术讨论、开放 RFC 流程等。它简化了大型语言模型 (LLM) 工作流的编排、优化和自动化,提供可定制和可对话的代理,这些代理利用了 GPT-4 等高级 LLM。
3. 实现
在本节中,我们将看到如何使用以下方式实现不同类型的聊天:
- AutoGen
- AG2
- Semantic Kernel
敬请关注,我们将探索实际示例,并指导您为您的 AI 应用程序选择合适的框架!🚀
3.1 AutoGen:
这里我们将只关注 v0.4,如果你使用的是 v0.2,请寻找迁移方法,然后可以按照这里的说明进行操作 — 迁移指南。
SetUp:
pip install -U "autogen-agentchat" "autogen-ext[openai, azure]"
3.1.1 简单聊天:
import asyncio
from autogen_agentchat.agents import AssistantAgent
from autogen_ext.models.openai import AzureOpenAIChatCompletionClient
az_model_client = AzureOpenAIChatCompletionClient(
azure_deployment="gpt-4o",
model="gpt-4o",
api_version="2024-08-01-preview",
azure_endpoint="https://<<your-azure-openai-endpoint-name>>.openai.azure.com/",
api_key="<<your-azure-openai-api-key>>", # For key-based authentication. `AZURE_OPENAI_API_KEY` environment variable can also be used instead.
)
async def main() -> None:
agent = AssistantAgent("assistant", az_model_client)
print(await agent.run(task="How are you doing today?"))
asyncio.run(main())
结果:
作者截取的执行结果截图
这里有 OpenAI 模型的示例,因此在这些示例中,我将使用 AzureOpenAI 模型和来自模型目录的几个其他模型。
3.1.2 群聊:
import asyncio
from autogen_agentchat.agents import AssistantAgent, UserProxyAgent
from autogen_agentchat.conditions import TextMentionTermination
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import AzureOpenAIChatCompletionClient
async def main() -> None:
az_model_client = AzureOpenAIChatCompletionClient(
azure_deployment="gpt-4o",
model="gpt-4o",
api_version="2024-08-01-preview",
azure_endpoint="https://<<your-azure-openai-endpoint-name>>.openai.azure.com/",
api_key="<<your-azure-openai-api-key>>", # For key-based authentication. `AZURE_OPENAI_API_KEY` environment variable can also be used instead.
)
assistant = AssistantAgent("assistant",
az_model_client,
description="Agent that can help find the information",
system_message="You are a helpful assistant that can help find the information which user_proxy agent requested for, when its complete you can respond with TERMINATE."
)
user_proxy = UserProxyAgent("user_proxy")
termination = TextMentionTermination("exit") # Type 'exit' to end the conversation.
team = RoundRobinGroupChat([assistant, user_proxy], termination_condition=termination)
await Console(team.run_stream(task="Find information about AutoGen and write a short summary."))
asyncio.run(main())
结果:
作者截取的执行结果截图
3.1.3 工具:
财务报告:美国航空
概述:
美国航空集团公司(“美国航空”)是全球最大的航空公司之一,在国际航空市场中持续发挥关键作用。凭借其广泛的国内和国际航线网络,该公司近年来在其财务业绩、运营和市场定位方面经历了重大事件,包括宏观经济状况和疫情驱动的影响所加剧的挑战。以下分析评估了其关键财务指标、运营策略和股票表现。
关键财务亮点(2023年):
-
市值和股票状况:
- 截至2023年6月30日,非关联方持有的有投票权的股票总市值约为 $117 亿美元。
- 截至2024年2月16日,该公司共有 654,756,816 股流通普通股,显示出股票结构的稳定性。
-
收入和盈利能力:
- 在全球旅行人数从疫情后反弹之际,美国航空的收入受益于强劲的旅行需求复苏。
- 尽管需求旺盛,但持续的成本压力,包括燃油价格上涨,对盈利能力造成了限制。
-
资产负债表:
- 该公司一直在管理着巨额债务,这是新冠疫情期间遭受的巨大损失的遗留问题。
- 流动性措施正在改善,美国航空正专注于有效的成本管理以偿还债务。
-
运营成本和燃油价格:
- 燃油价格仍然是美国航空的关键运营成本因素。该公司还应对了由于与工会达成新的工资协议而产生的劳动力成本压力。
收入来源分析:
-
国内市场:
- 国内市场仍然是美国航空的主要收入来源,占据其总收入的很大一部分。随着消费者信心的增强,商务和休闲旅行均有所反弹。
-
国际业务:
- 拉丁美洲和欧洲等地区对美国航空来说表现出令人印象深刻的增长轨迹,航班频率增加,并重新引入了疫情前的航线。
主要投资和战略举措:
-
机队现代化:
- 美国航空已大力投资于机队现代化,引入了新的燃油效率型飞机。此举旨在降低运营成本并实现可持续发展目标。
-
可持续发展承诺:
- 航空业面临着越来越大的减少碳排放的压力。美国航空已制定了雄心勃勃的可持续发展目标,包括到2050年实现碳中和运营。
-
增强客户体验:
- 对客户忠诚度计划和高端舱位产品的重新关注突显了该公司对提高单票收入的重视。
挑战:
-
债务负担:
- 疫情时代的债务仍然很大,重点在于其重组和偿还,同时平衡运营增长和投资。
-
宏观经济因素:
- 动荡的油价和通货膨胀给运营成本带来了风险。此外,地缘政治的不确定性可能会影响国际旅行需求。
-
竞争环境:
- 美国航空在竞争激烈的市场中运营,并继续面临来自达美航空和联合航空等主要美国航空公司的激烈竞争。
股票市场表现:
- 在过去一年中,美国航空的股票出现了波动趋势,受到更广泛的市场波动性和特定行业挑战的影响。
- 投资者正在密切关注该公司管理其债务水平和维持运营盈利的能力。
2024年展望:
-
顺风:
- 有利的消费者旅行需求,尤其是长途和休闲市场,可能会推动收入增长。
- 预计运营效率和成本节约计划将改善未来的利润率。
-
逆风:
- 持续的宏观经济不确定性,尤其是在欧洲和亚洲,以及长期高利率的可能性,可能会对公司的财务表现造成影响。
结论:
美国航空正处于转型时期,因为它试图平衡增长和财务纪律。其在机队现代化、增强客户满意度和实现可持续发展目标方面的战略重点与长期的行业趋势相符。然而,对债务水平和运营成本的谨慎管理对其成功至关重要。投资者和利益相关者将热切地观察该公司如何有效地利用持续的旅行复苏来改善其财务状况和竞争力。
pip install -U "autogenstudio"
autogenstudio ui --port 8080 --appdir ./my-app
3.2 Semantic Kernel:
All samples here use Azure OpenAI gpt-4o model.
Kernel Configuration is needed to successfully run these samples. I kept them in .env file at project root. For more details refer SemanticKernel Configuration.
AZURE_OPENAI_CHAT_DEPLOYMENT_NAME="gpt-4o"
AZURE_OPENAI_ENDPOINT="https://<<your-azure-openai-deployment-name>>.openai.azure.com/"
AZURE_OPENAI_API_KEY="<<your-azure-openai-key>>"
AZURE_OPENAI_API_VERSION="2024-08-01-preview"
3.2.1 Assistant: It allows function calling, file search and a code interpreter. Assistant Threads are used to manage the conversation state, similar to a Semantic Kernel Chat History.
## Copyright (c) Microsoft. All rights reserved.
import asyncio
from typing import Annotated
from semantic_kernel.agents.open_ai import AzureAssistantAgent, OpenAIAssistantAgent
from semantic_kernel.contents.chat_message_content import ChatMessageContent
from semantic_kernel.contents.utils.author_role import AuthorRole
from semantic_kernel.functions.kernel_function_decorator import kernel_function
from semantic_kernel.kernel import Kernel
HOST_NAME = "Host"
HOST_INSTRUCTIONS = "Answer questions about the menu."
## Define a sample plugin for the sample
class MenuPlugin:
"""A sample Menu Plugin used for the concept sample."""
@kernel_function(description="Provides a list of specials from the menu.")
def get_specials(self) -> Annotated[str, "Returns the specials from the menu."]:
return """
Special Soup: Clam Chowder
Special Salad: Cobb Salad
Special Drink: Chai Tea
"""
@kernel_function(description="Provides the price of the requested menu item.")
def get_item_price(
self, menu_item: Annotated[str, "The name of the menu item."]
) -> Annotated[str, "Returns the price of the menu item."]:
return "$9.99"
使用用户输入调用 Agent 的辅助方法
async def invoke_agent(agent: OpenAIAssistantAgent, thread_id: str, input: str) -> None:
"""Invoke the agent with the user input."""
await agent.add_chat_message(thread_id=thread_id, message=ChatMessageContent(role=AuthorRole.USER, content=input))
print(f"# {AuthorRole.USER}: '{input}'")
async for content in agent.invoke(thread_id=thread_id):
if content.role != AuthorRole.TOOL:
print(f"# {content.role}: {content.content}")
async def main():
# Create the instance of the Kernel
kernel = Kernel()
# Add the sample plugin to the kernel
kernel.add_plugin(plugin=MenuPlugin(), plugin_name="menu")
# Create the OpenAI Assistant Agent
service_id = "agent"
agent = await AzureAssistantAgent.create(
kernel=kernel, service_id=service_id, name=HOST_NAME, instructions=HOST_INSTRUCTIONS
)
thread_id = await agent.create_thread()
try:
await invoke_agent(agent, thread_id=thread_id, input="Hello")
await invoke_agent(agent, thread_id=thread_id, input="What is the special soup?")
await invoke_agent(agent, thread_id=thread_id, input="What is the special drink?")
await invoke_agent(agent, thread_id=thread_id, input="Thank you")
finally:
await agent.delete_thread(thread_id)
await agent.delete()
if __name__ == "__main__":
asyncio.run(main())
3.2.2 Code Interpreter:
import asyncio
from semantic_kernel.agents.open_ai.azure_assistant_agent import AzureAssistantAgent
from semantic_kernel.agents.open_ai.open_ai_assistant_agent import OpenAIAssistantAgent
from semantic_kernel.contents.chat_message_content import ChatMessageContent
from semantic_kernel.contents.utils.author_role import AuthorRole
from semantic_kernel.kernel import Kernel
AGENT_NAME = "CodeRunner"
AGENT_INSTRUCTIONS = "Run the provided code file and return the result."
## A helper method to invoke the agent with the user input
async def invoke_agent(agent: OpenAIAssistantAgent, thread_id: str, input: str) -> None:
"""Invoke the agent with the user input."""
await agent.add_chat_message(thread_id=thread_id, message=ChatMessageContent(role=AuthorRole.USER, content=input))
print(f"# {AuthorRole.USER}: '{input}'")
async for content in agent.invoke(thread_id=thread_id):
if content.role != AuthorRole.TOOL:
print(f"# {content.role}: {content.content}")
async def main():
# Create the instance of the Kernel
kernel = Kernel()
# Define a service_id for the sample
service_id = "agent"
# Create the agent
agent = await AzureAssistantAgent.create(
kernel=kernel,
service_id=service_id,
name=AGENT_NAME,
instructions=AGENT_INSTRUCTIONS,
enable_code_interpreter=True,
)
thread_id = await agent.create_thread()
try:
await invoke_agent(
agent,
thread_id=thread_id,
input="Use code to determine the values in the Fibonacci sequence that that are less then the value of 101?", # noqa: E501
)
finally:
await agent.delete_thread(thread_id)
await agent.delete()
if __name__ == "__main__":
asyncio.run(main())
**3.2.3 文件搜索:**此示例演示了如何使用 Azure OpenAI 创建 OpenAI 助手,利用助手的 文件搜索 功能。
import asyncio
import os
from semantic_kernel.agents.open_ai.azure_assistant_agent import AzureAssistantAgent
from semantic_kernel.agents.open_ai.open_ai_assistant_agent import OpenAIAssistantAgent
from semantic_kernel.contents.chat_message_content import ChatMessageContent
from semantic_kernel.contents.utils.author_role import AuthorRole
from semantic_kernel.kernel import Kernel
AGENT_NAME = "FileSearch"
AGENT_INSTRUCTIONS = "Find answers to the user's questions in the provided file."
## A helper method to invoke the agent with the user input
async def invoke_agent(agent: OpenAIAssistantAgent, thread_id: str, input: str) -> None:
"""Invoke the agent with the user input."""
await agent.add_chat_message(thread_id=thread_id, message=ChatMessageContent(role=AuthorRole.USER, content=input))
print(f"# {AuthorRole.USER}: '{input}'")
async for content in agent.invoke(thread_id=thread_id):
if content.role != AuthorRole.TOOL:
print(f"# {content.role}: {content.content}")
async def main():
# Create the instance of the Kernel
kernel = Kernel()
# Define a service_id for the sample
service_id = "agent"
# Get the path to the travelinfo.txt file
pdf_file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "resources", "employees.pdf")
# Create the agent configuration
agent = await AzureAssistantAgent.create(
kernel=kernel,
service_id=service_id,
name=AGENT_NAME,
instructions=AGENT_INSTRUCTIONS,
enable_file_search=True,
vector_store_filenames=[pdf_file_path],
)
# Define a thread and invoke the agent with the user input
thread_id = await agent.create_thread()
try:
await invoke_agent(agent, thread_id=thread_id, input="Who is the youngest employee?")
await invoke_agent(agent, thread_id=thread_id, input="Who works in sales?")
await invoke_agent(agent, thread_id=thread_id, input="I have a customer request, who can help me?")
finally:
[await agent.delete_file(file_id) for file_id in agent.file_search_file_ids]
await agent.delete_thread(thread_id)
await agent.delete()
if __name__ == "__main__":
asyncio.run(main())
3.3 AG2:
你可以在 Docker 中安装并运行 AG2,这里我使用了本地环境。
pip install ag2
在开始之前,我们准备好配置文件,以便 agent 可以使用这些模型。
[
{
"model": "gpt-4o",
"api_key": "<<your-azure-openai-key>>",
"base_url": "https://<<your-azure-openai-resource>>.openai.azure.com/",
"api_type": "azure",
"api_version": "2024-08-01-preview"
}
]
3.3.1 两个 Agent 聊天:
这启动了两个 agent 之间自动聊天,以解决一个简单的任务。它创建了一个编码目录,并将 python 文件放置其中。
from autogen import AssistantAgent, UserProxyAgent, config_list_from_json
config_list = config_list_from_json(env_or_file="OAI_CONFIG_LIST.json")
## You can also set config_list directly as a list, for example, config_list = [{‘model’: ‘gpt-4o’, ‘api_key’: ‘<your OpenAI API key here>’},]
assistant = AssistantAgent("assistant", llm_config={"config_list": config_list})
user_proxy = UserProxyAgent("user_proxy", code_execution_config={"work_dir": "coding", "use_docker": False}) # IMPORTANT: set to True to run code in docker, recommended
user_proxy.initiate_chat(assistant, message="Plot a chart of NVDA and TESLA stock price change YTD.")
user_proxy[0m (to assistant):
Plot a chart of NVDA and TESLA stock price change YTD.
--------------------------------------------------------------------------------
assistant[0m (to user_proxy):
To plot a chart of NVIDIA (NVDA) and Tesla (TSLA) stock price change year-to-date (YTD), follow these steps:
1. Collect historical stock price data for NVDA and TSLA for the current year.
2. Calculate the YTD percentage change for both stocks.
3. Plot the YTD percentage change on a chart.
We can use Python along with the `pandas`, `yfinance`, and `matplotlib` libraries to achieve this.
Here's the complete script to do this:
```python
## filename: nvda_tsla_ytd_plot.py
import pandas as pd
import yfinance as yf
import matplotlib.pyplot as plt
from datetime import datetime
## Set the start and end dates
start_date = f"{datetime.now().year}-01-01"
end_date = datetime.now().strftime("%Y-%m-%d")
## Fetch historical stock data
nvda_data = yf.download('NVDA', start=start_date, end=end_date)
tsla_data = yf.download('TSLA', start=start_date, end=end_date)
## Calculate YTD price change percentage
nvda_data['YTD Change %'] = (nvda_data['Close'] / nvda_data['Close'].iloc[0] - 1) * 100
tsla_data['YTD Change %'] = (tsla_data['Close'] / tsla_data['Close'].iloc[0] - 1) * 100
## Plot the data
plt.figure(figsize=(10, 6))
plt.plot(nvda_data.index, nvda_data['YTD Change %'], label='NVDA YTD Change %')
plt.plot(tsla_data.index, tsla_data['YTD Change %'], label='TSLA YTD Change %')
plt.xlabel('Date')
plt.ylabel('Year-To-Date Change (%)')
plt.title('NVDA and TSLA YTD Price Change')
plt.legend()
plt.grid(True)
plt.show()
Steps:
- Save the above code into a file named
nvda_tsla_ytd_plot.py
. - Execute the script to fetch the stock prices, calculate the YTD changes and plot the chart.
Please execute the script and provide the output.

Chart comparing 2 stocks, output generated by the Agent. — Author
### 3.3.2 多 Agent — 组聊天:
在这个示例中,一组 agent 协同工作来创建一个贪吃蛇游戏
from autogen import AssistantAgent, UserProxyAgent, config_list_from_json config_list = config_list_from_json(env_or_file=“OAI_CONFIG_LIST.json”)
llm_config={ ‘temperature’:0, ‘config_list’:config_list, ‘timeout’:60, }
coder=autogen.AssistantAgent( name=‘AIAssistant’, system_message=“You are a coder. You will write the code for the project. you will write the code for the snake game.”, llm_config=llm_config
)
userProxy=autogen.UserProxyAgent( name=‘UserProxy’, system_message=“You are an executor. you will help execute the code written by coder, make sure you save the copy of in the code in another folder called Games.”, human_input_mode=“NEVER”, code_execution_config={ “work_dir”: “coding”, “use_docker”:False } )
planner=autogen.AssistantAgent( name=‘Planner’, system_message=“You are a planner. You will help plan the project and make sure the project is well planned and documented. you will do code review on the code written by the coder.”, llm_config=llm_config )
group_chat=autogen.GroupChat( agents=[userProxy, coder, planner], messages=[], max_round=15 )
groupChatManager=autogen.GroupChatManager(groupchat=group_chat,llm_config=llm_config)
userProxy.initiate_chat( groupChatManager, message=“I want to play a snake game. create a snake game. It’s for 6 year old so make the snake go little slow.” )
**结果:**我只粘贴了输出,因为对话太大了。

Snake Game, code generated by Coder Agent and executed by UserProxy Agent. Screenshot taken by the Author
### 4. 结论
总之,*AG2*、*Semantic Kernel* 和 *AutoGen* 这三个框架都为特定的 AI 开发需求提供了共同的特性和优势。
**AG2** — 适合那些寻求**社区驱动框架**,更侧重于**agent 编排和协作**的人。
**Semantic Kernel** 最适合那些将**AI 功能集成**到现有**企业应用程序**中的人,因为它支持 **C#、Python 和 Java**。
**AutoGen** 主要面向需要**构建智能、自主 agent** 并能够**进行复杂决策**的**创新者**。
通过了解每个框架的**独特优势**,您现在可以**选择正确的框架** ✅,最适合您的**AI 项目和目标** 🚀!