AI智能体入门 2)探索 AI 智能体框架
个性化推荐:AI 能分析用户行为与偏好,提供个性化的推荐、内容和体验。✅ 示例:Netflix 使用 AI 根据观影记录推荐电影和剧集,从而提升用户参与度和满意度。自动化与效率提升:AI 可自动执行重复性任务,简化工作流程,提升运营效率。✅ 示例:客户服务应用使用 AI 聊天机器人处理常见问题,降低响应时间,让人工客服专注于复杂事务。增强用户体验:通过语音识别、自然语言处理和预测文本输入等智能功能
原文:https://github.com/microsoft/ai-agents-for-beginners
译者:Jamon
协议:CC BY-NC-SA 4.0
探索 AI 智能体框架(AI Agent Frameworks)
AI 智能体框架是一类软件平台,旨在简化 AI 智能体的创建、部署与管理。它们为开发者提供了预构建的组件、抽象模型和工具,帮助高效地开发复杂的 AI 系统。
这些框架通过为 AI 智能体开发中的常见挑战提供标准化的解决方案,使开发者能够专注于应用的独特价值,从而提升系统的可扩展性、可访问性与开发效率。
📌 课程导学
本节课将讲解以下内容:
- 什么是 AI 智能体框架?它们帮助开发者实现了哪些能力?
- 团队如何利用这些框架快速进行原型设计、迭代与功能增强?
- Microsoft 的 AutoGen、Semantic Kernel 和 Azure AI Agent Service 各框架和工具有何区别?
- 是否可以将我现有的 Azure 生态工具直接集成?是否需要独立部署?
- 什么是 Azure AI Agents 服务?它能如何帮助我?
🎯 学习目标
通过本节课,你将了解:
- AI 智能体框架在 AI 开发中的角色;
- 如何利用这些框架构建智能体系统;
- 智能体框架所支持的关键能力;
- AutoGen、Semantic Kernel 与 Azure AI Agent Service 三者之间的核心差异。
🤖 什么是 AI 智能体框架?它们帮助开发者做什么?
传统的 AI 框架可以帮助你将 AI 融入应用,并在以下方面提升体验:
-
个性化推荐:AI 能分析用户行为与偏好,提供个性化的推荐、内容和体验。
✅ 示例:Netflix 使用 AI 根据观影记录推荐电影和剧集,从而提升用户参与度和满意度。 -
自动化与效率提升:AI 可自动执行重复性任务,简化工作流程,提升运营效率。
✅ 示例:客户服务应用使用 AI 聊天机器人处理常见问题,降低响应时间,让人工客服专注于复杂事务。 -
增强用户体验:通过语音识别、自然语言处理和预测文本输入等智能功能,优化整体用户体验。
✅ 示例:Siri 和 Google Assistant 利用 AI 理解语音命令,简化设备交互。
🧠 那么我们为什么还需要“AI 智能体框架”?
AI 智能体框架不仅仅是 AI 框架的简单扩展。它们专为创建“智能体”设计——这些智能体能够与用户、其他智能体或外部环境交互,以实现特定目标。
这些系统支持自主行为、决策能力和适应性。
AI 智能体框架支持的核心能力包括:
- 智能体协作与协调:支持多个智能体间协同工作、通信与任务分工,解决复杂问题。
- 任务自动化与管理:提供多步骤工作流的自动化机制,实现任务的分发与动态管理。
- 上下文理解与适应能力:智能体能够理解上下文,根据环境变化实时做出决策。
总结一句话:智能体让你不只是“做自动化”,而是构建能自适应学习、决策与协作的“智能系统”。
⚡ 如何快速构建原型、迭代与提升智能体能力?
AI 智能体框架的发展非常迅速,但无论哪个平台,下面三种通用能力是关键:
✅ 使用模块化组件
大多数 AI SDK(如 Semantic Kernel、LangChain)都提供了可复用的模块,包括:
- AI 连接器(调用模型)
- Memory 存储模块(上下文记忆)
- Prompt 模板
- 函数调用插件(代码/自然语言调用工具)
团队如何利用:
快速组装这些组件即可构建功能原型,无需从零开发,便于快速试验与迭代。
实战应用:
你可以使用预构建的解析器提取用户输入信息,Memory 模块来记录用户偏好,再通过 Prompt 模板与用户交互 —— 所有功能模块都开箱即用。
🛠 示例代码:
接下来我们会演示如何使用 Semantic Kernel(支持 Python 与 .NET)中的 AI Connector 和自动函数调用功能,来实现智能体对用户输入的响应。
# Semantic Kernel Python Example
import asyncio
from typing import Annotated
from semantic_kernel.connectors.ai import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion, AzureChatPromptExecutionSettings
from semantic_kernel.contents import ChatHistory
from semantic_kernel.functions import kernel_function
from semantic_kernel.kernel import Kernel
# Define a ChatHistory object to hold the conversation's context
chat_history = ChatHistory()
chat_history.add_user_message("I'd like to go to New York on January 1, 2025")
# Define a sample plugin that contains the function to book travel
class BookTravelPlugin:
"""A Sample Book Travel Plugin"""
@kernel_function(name="book_flight", description="Book travel given location and date")
async def book_flight(
self, date: Annotated[str, "The date of travel"], location: Annotated[str, "The location to travel to"]
) -> str:
return f"Travel was booked to {location} on {date}"
# Create the Kernel
kernel = Kernel()
# Add the sample plugin to the Kernel object
kernel.add_plugin(BookTravelPlugin(), plugin_name="book_travel")
# Define the Azure OpenAI AI Connector
chat_service = AzureChatCompletion(
deployment_name="YOUR_DEPLOYMENT_NAME",
api_key="YOUR_API_KEY",
endpoint="https://<your-resource>.azure.openai.com/",
)
# Define the request settings to configure the model with auto-function calling
request_settings = AzureChatPromptExecutionSettings(function_choice_behavior=FunctionChoiceBehavior.Auto())
async def main():
# Make the request to the model for the given chat history and request settings
# The Kernel contains the sample that the model will request to invoke
response = await chat_service.get_chat_message_content(
chat_history=chat_history, settings=request_settings, kernel=kernel
)
assert response is not None
"""
Note: In the auto function calling process, the model determines it can invoke the
`BookTravelPlugin` using the `book_flight` function, supplying the necessary arguments.
For example:
"tool_calls": [
{
"id": "call_abc123",
"type": "function",
"function": {
"name": "BookTravelPlugin-book_flight",
"arguments": "{'location': 'New York', 'date': '2025-01-01'}"
}
}
]
Since the location and date arguments are required (as defined by the kernel function), if the
model lacks either, it will prompt the user to provide them. For instance:
User: Book me a flight to New York.
Model: Sure, I'd love to help you book a flight. Could you please specify the date?
User: I want to travel on January 1, 2025.
Model: Your flight to New York on January 1, 2025, has been successfully booked. Safe travels!
"""
print(f"`{response}`")
# Example AI Model Response: `Your flight to New York on January 1, 2025, has been successfully booked. Safe travels! ✈️🗽`
# Add the model's response to our chat history context
chat_history.add_assistant_message(response.content)
if __name__ == "__main__":
asyncio.run(main())
🧩 你可以从这个示例中看到:
我们可以利用预构建的解析器(parser)从用户输入中提取关键信息,例如航班预订请求中的出发地、目的地和日期。这种模块化的方法让你可以专注于高层逻辑设计,而不必从头处理底层数据提取流程。
🤝 利用协作工具(Collaborative Tools)
像 CrewAI、Microsoft AutoGen 和 Semantic Kernel 这样的框架,支持创建多个可以协作的智能体系统。
✅ 团队如何使用这些工具:
团队可以为每个智能体设计明确的角色与任务,从而测试和优化协同工作流程,进一步提升系统的整体效率与稳定性。
⚙️ 实战中的工作方式:
你可以创建一个“智能体团队”,其中每个智能体各司其职,例如:
- 一个智能体专注于数据检索;
- 另一个智能体负责分析处理;
- 第三个智能体负责做出最终决策。
这些智能体之间可以通信、共享信息,共同完成用户查询或复杂任务 —— 例如,一起完成一次航班预订请求或生成财务分析报告。
💻 示例代码(AutoGen):
接下来将展示如何使用 AutoGen 框架 构建一个多智能体系统,并通过协作完成特定任务。
# creating agents, then create a round robin schedule where they can work together, in this case in order
# Data Retrieval Agent
# Data Analysis Agent
# Decision Making Agent
agent_retrieve = AssistantAgent(
name="dataretrieval",
model_client=model_client,
tools=[retrieve_tool],
system_message="Use tools to solve tasks."
)
agent_analyze = AssistantAgent(
name="dataanalysis",
model_client=model_client,
tools=[analyze_tool],
system_message="Use tools to solve tasks."
)
# conversation ends when user says "APPROVE"
termination = TextMentionTermination("APPROVE")
user_proxy = UserProxyAgent("user_proxy", input_func=input)
team = RoundRobinGroupChat([agent_retrieve, agent_analyze, user_proxy], termination_condition=termination)
stream = team.run_stream(task="Analyze data", max_turns=10)
# Use asyncio.run(...) when running in a script.
await Console(stream)
以下是你提供内容的完整中文翻译,适合用于博客、教程或技术讲解场景:
🧠 正如之前的代码所示:
你可以创建一个任务,这个任务由多个智能体协同完成数据分析工作。每个智能体都承担特定的职责,而整个任务的完成依赖于这些智能体的协调与合作,以达成预期目标。
通过为每个智能体分配专门化的角色,你可以显著提高任务的执行效率与系统整体性能。
📡 实时学习(Learn in Real-Time)
高级框架提供了实时上下文理解与动态适应的能力。
✅ 团队如何使用这些能力:
团队可以实现反馈循环机制,使得智能体能够根据交互过程中的反馈信息不断学习并动态调整行为,从而持续优化自身能力。
⚙️ 实际工作方式:
智能体可以:
- 分析用户反馈;
- 感知环境数据;
- 评估任务结果;
从而不断更新知识库、调整决策逻辑,并逐步提升系统整体表现。
这种迭代式学习过程使智能体能够适应不断变化的环境和用户偏好,从而增强系统的实用性与智能性。
🧰 AutoGen、Semantic Kernel 和 Azure AI Agent Service 有何区别?
虽然可以从多个维度对比这些框架,但我们重点关注以下几个方面的关键差异:
| 框架 | 核心定位 | 能力特点 | 适用场景 |
|---|---|---|---|
| AutoGen | 多智能体、分布式、事件驱动框架 | 支持异步消息通信、多模型(LLM/SLM)协作、工具集成,支持高级 agentic 模式 | 代码生成、数据分析、自定义智能体设计 |
| Semantic Kernel | 生产级 AI 插件框架 | 支持函数级调用(function calling)、Prompt 模板、内存管理 | 构建可扩展 AI 应用,适用于企业开发者 |
| Azure AI Agent Service | 全托管 Agent 平台 | 集成 Azure 生态(如认知服务、OpenAI 服务)、支持任务调度、Agent 管理 | 快速上线 Agent 系统,适用于企业和低代码开发者 |
🔍 深入理解 AutoGen
AutoGen 是微软研究院(AI Frontiers Lab)开发的开源智能体框架,专注于构建 事件驱动的分布式智能体应用。支持多个 LLM、SLM 协同工作,并可结合工具链形成复杂的多智能体架构。
AutoGen 基于一个核心概念:智能体(Agent),即能自主感知环境、做出决策并采取行动的系统组件。
✉️ 智能体之间如何通信:
AutoGen 使用 异步消息机制(asynchronous messaging)进行智能体之间的通信,使得每个 Agent 可以独立运行、并发响应,从而提升系统的可扩展性与响应速度。
🧱 Agent 模型基础:Actor Model
根据 Wikipedia 的定义,Actor(角色)是并发计算的基本构建模块。
一个 Actor 在接收到消息时可以:
- 做出本地决策;
- 创建更多 Actor;
- 发送新消息;
- 决定如何处理下一条接收到的消息。
🛠 AutoGen 示例核心概念:
- Agent:一个具有状态、消息处理能力与外部动作的独立软件实体。
- 消息通信:支持同步/异步;
- 状态管理:每个 Agent 维护自己的状态,可根据收到的消息进行更新;
- 外部交互:可执行代码、调用 API、修改外部环境等。
💡 快速示例:使用 AutoGen 创建一个带有聊天能力的智能体
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.messages import TextMessage
from autogen_ext.models.openai import OpenAIChatCompletionClient
class MyAssistant(RoutedAgent):
def __init__(self, name: str) -> None:
super().__init__(name)
model_client = OpenAIChatCompletionClient(model="gpt-4o")
self._delegate = AssistantAgent(name, model_client=model_client)
@message_handler
async def handle_my_message_type(self, message: MyMessageType, ctx: MessageContext) -> None:
print(f"{self.id.type} received message: {message.content}")
response = await self._delegate.on_messages(
[TextMessage(content=message.content, source="user")], ctx.cancellation_token
)
print(f"{self.id.type} responded: {response.chat_message.content}")
在上面的代码中,我们定义了一个名为 MyAssistant 的类,它继承自 RoutedAgent。这个类定义了一个消息处理器(handle_my_message_type),该处理器会打印收到的消息内容,并将消息委托给 AssistantAgent 来生成响应。
特别注意:我们将一个内建的 AssistantAgent 实例赋值给 self._delegate,这是一个预构建的智能体,可以处理对话类的任务,如语言模型回复等。
🚀 启动 AutoGen 程序
# main.py
runtime = SingleThreadedAgentRuntime()
await MyAgent.register(runtime, "my_agent", lambda: MyAgent())
runtime.start() # 启动后台消息处理
await runtime.send_message(MyMessageType("Hello, World!"), AgentId("my_agent", "default"))
上面的代码中,我们:
- 创建了一个
SingleThreadedAgentRuntime实例; - 注册了名为
"my_agent"的智能体; - 启动运行时;
- 向智能体发送一条消息。
程序的输出将类似于:
my_agent received message: Hello, World!
my_assistant received message: Hello, World!
my_assistant responded: Hello! How can I assist you today?
🤖 多智能体系统(Multi-Agent Systems)
AutoGen 支持创建多个智能体协作完成复杂任务的场景。这些智能体可以彼此通信、共享信息并协调行动,以更高效地解决问题。
例如,你可以定义以下类型的智能体:
- 数据检索智能体;
- 分析智能体;
- 决策智能体;
- 用户交互智能体等。
🧩 示例:构建编辑器智能体
editor_description = "Editor for planning and reviewing the content."
editor_agent_type = await EditorAgent.register(
runtime,
editor_topic_type, # 使用 Topic 类型作为 Agent 类型
lambda: EditorAgent(
description=editor_description,
group_chat_topic_type=group_chat_topic_type,
model_client=OpenAIChatCompletionClient(
model="gpt-4o-2024-08-06",
# api_key="YOUR_API_KEY",
),
),
)
上述代码中我们注册了一个“编辑器”智能体,并提供了其描述信息与所使用的语言模型。
💬 群聊协调管理(Group Chat Manager)
group_chat_manager_type = await GroupChatManager.register(
runtime,
"group_chat_manager",
lambda: GroupChatManager(
participant_topic_types=[
writer_topic_type,
illustrator_topic_type,
editor_topic_type,
user_topic_type
],
model_client=OpenAIChatCompletionClient(
model="gpt-4o-2024-08-06",
# api_key="YOUR_API_KEY",
),
participant_descriptions=[
writer_description,
illustrator_description,
editor_description,
user_description
],
),
)
在上述代码中,我们定义了一个 GroupChatManager 智能体,它负责协调多个参与者(如写作者、插画师、编辑者和用户)之间的互动。该组件是实现多智能体协作对话的关键。
🧠 Agent Runtime 运行时环境
AutoGen 提供了一个专用的运行时环境,用于:
- 管理智能体之间的通信;
- 管理智能体的生命周期与身份;
- 实现安全和隐私边界控制。
这确保了智能体在一个受控、可靠且安全的环境中运行与交互。
AutoGen 支持两种运行时模式:
🖥️ Stand-alone Runtime(独立运行时)
适用于单进程应用场景,即所有智能体运行在同一语言环境和进程中。
运行机制示意图:
Application Stack
│
┌──▼───────────────────────────┐
│ Stand-alone AgentRuntime │
└───▲──────────────────────────┘
│ │ │
Agent1 Agent2 Agent3
- 所有智能体通过运行时传递消息;
- 运行时统一管理智能体的状态与生命周期。
🌐 Distributed Agent Runtime(分布式运行时)
适用于多进程或多语言环境,即智能体可能部署在不同服务器或使用不同编程语言实现。
运行机制示意图:
Distributed System
│
┌──▼────────────┐ ┌──-───────────┐
│ Runtime Host 1│ <--> │Runtime Host 2│
└──▲────────────┘ └──-───────────┘
│ │
AgentA AgentB / AgentC
- 智能体可以跨机器通信;
- 支持大规模协同、弹性部署、服务化调用。
🔧 Semantic Kernel 与 Agent Framework
Semantic Kernel 是一个企业级的 AI 编排(Orchestration)SDK,包含 AI 连接器(AI Connectors)、**记忆机制(Memory)以及智能体框架(Agent Framework)**等核心组件。
🧩 核心组件介绍
1. 🌐 AI 连接器(AI Connectors)
AI Connectors 提供与外部 AI 服务和数据源的接口,目前支持 Python 与 C#。
✅ Python 示例:
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.kernel import Kernel
kernel = Kernel()
kernel.add_service(
AzureChatCompletion(
deployment_name="your-deployment-name",
api_key="your-api-key",
endpoint="your-endpoint",
)
)
✅ C# 示例:
using Microsoft.SemanticKernel;
// 创建 Kernel
var builder = Kernel.CreateBuilder();
// 添加 Azure OpenAI Chat Completion 服务
builder.Services.AddAzureOpenAIChatCompletion(
"your-resource-name",
"your-endpoint",
"your-resource-key",
"deployment-model");
var kernel = builder.Build();
通过以上代码,我们创建了一个 Kernel,并为其添加了一个 Azure OpenAI 的聊天补全服务。
2. 🧠 插件(Plugins)
插件封装了应用可调用的功能。可以使用预设插件或自定义插件。相关概念包括“提示函数(Prompt Functions)”,即通过特定提示定义函数,让大模型根据上下文自主选择是否调用某个函数。
✅ Python 示例:
from semantic_kernel.connectors.ai.open_ai.services.azure_chat_completion import AzureChatCompletion
async def main():
from semantic_kernel.functions import KernelFunctionFromPrompt
from semantic_kernel.kernel import Kernel
kernel = Kernel()
kernel.add_service(AzureChatCompletion())
user_input = input("User Input:> ")
kernel_function = KernelFunctionFromPrompt(
function_name="SummarizeText",
prompt="""
Summarize the provided unstructured text in a sentence that is easy to understand.
Text to summarize: {{$user_input}}
""",
)
response = await kernel_function.invoke(kernel=kernel, user_input=user_input)
print(f"Model Response: {response}")
if __name__ == "__main__":
import asyncio
asyncio.run(main())
✅ C# 示例:
var userInput = Console.ReadLine();
string skPrompt = @"Summarize the provided unstructured text in a sentence that is easy to understand.
Text to summarize: {{$userInput}}";
// 从提示创建函数
KernelFunction summarizeFunc = kernel.CreateFunctionFromPrompt(
promptTemplate: skPrompt,
functionName: "SummarizeText"
);
// 导入插件
kernel.ImportPluginFromFunctions("SemanticFunctions", [summarizeFunc]);
在上述示例中,我们用一个名为 SummarizeText 的提示函数处理用户输入并进行总结。SemanticFunctions 是插件名称,用于组织相关函数。
3. ⚙️ 原生函数(Native Functions)
除了提示函数,你也可以使用“原生函数”,即由代码直接定义、由框架直接调用的函数。
✅ C# 示例:
public class NativeFunctions {
[SKFunction, Description("Retrieve content from local file")]
public async Task<string> RetrieveLocalFile(string fileName, int maxSize = 5000)
{
string content = await File.ReadAllTextAsync(fileName);
if (content.Length <= maxSize) return content;
return content.Substring(0, maxSize);
}
}
// 导入原生函数
kernel.ImportPluginFromType<NativeFunctions>();
通过 [SKFunction] 属性声明该方法为 Semantic Kernel 可识别的函数,然后导入即可使用。
4. 💾 记忆机制(Memory)
Memory 模块简化了上下文管理,让 AI 模型可以记住关键信息并在未来任务中使用。
以下是一个简化示例,展示如何向记忆中添加知识片段(fact):
✅ C# 示例:
var facts = new Dictionary<string, string>();
facts.Add(
"Azure Machine Learning; https://learn.microsoft.com/azure/machine-learning/",
@"Azure Machine Learning 是一个云服务,用于加速和管理机器学习项目的生命周期。
数据科学家和工程师可以将其用于日常工作流中。"
);
facts.Add(
"Azure SQL Service; https://learn.microsoft.com/azure/azure-sql/",
@"Azure SQL 是一组托管、安全且智能的数据库产品,
使用 SQL Server 引擎,在 Azure 云上运行。"
);
string memoryCollectionName = "SummarizedAzureDocs";
foreach (var fact in facts) {
await memoryBuilder.SaveReferenceAsync(
collection: memoryCollectionName,
description: fact.Key.Split(";")[1].Trim(),
text: fact.Value,
externalId: fact.Key.Split(";")[0].Trim(),
externalSourceName: "Azure Documentation"
);
}
以上信息被存储在 SummarizedAzureDocs 记忆集合中,供模型后续调用。实际使用中你也可以接入向量数据库如 Azure Cognitive Search、Qdrant、Pinecone 等。
👥 Agent Framework 简介
Semantic Kernel 除了提供 AI 服务接入和插件机制之外,还包含了一个Agent Framework(智能体框架)。该框架用于:
- 构建具有“感知 - 决策 - 执行”能力的智能体(Agent);
- 编排多个插件、记忆模块、函数和服务;
- 支持智能体之间的协作与消息通信。
Agent Framework 是 Semantic Kernel 实现 LLM+Tools 和多智能体协同系统的核心模块,类似于 AutoGen 或 LangGraph 中的 Agent 概念。
以下是对“Azure AI Agent Service”内容的中文翻译:
Azure AI Agent Service(Azure AI 代理服务)
Azure AI Agent Service 是微软在 2024 年 Ignite 大会上推出的较新服务。它支持更灵活的模型,能够直接调用开源大语言模型(如 Llama 3、Mistral、Cohere)等。
Azure AI Agent Service 提供了更强的企业安全机制和数据存储方式,适合企业级应用场景。
它开箱即用,支持与多代理编排框架(如 AutoGen 和 Semantic Kernel)集成。
该服务目前处于公开预览阶段,支持使用 Python 和 C# 进行代理开发。
使用示例(Semantic Kernel Python)
import asyncio
from typing import Annotated
from azure.identity.aio import DefaultAzureCredential
from semantic_kernel.agents import AzureAIAgent, AzureAIAgentSettings, AzureAIAgentThread
from semantic_kernel.functions import kernel_function
# 定义示例插件
class MenuPlugin:
"""示例菜单插件"""
@kernel_function(description="提供菜单中特价菜列表")
def get_specials(self) -> Annotated[str, "返回菜单中特价菜"]:
return """
特价汤品: 蛤蜊浓汤
特价沙拉: Cobb 沙拉
特价饮品: 印度奶茶
"""
@kernel_function(description="提供指定菜单项的价格")
def get_item_price(self, menu_item: Annotated[str, "菜单项名称"]) -> Annotated[str, "返回菜单项价格"]:
return "$9.99"
async def main() -> None:
ai_agent_settings = AzureAIAgentSettings.create()
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(
credential=creds,
conn_str=ai_agent_settings.project_connection_string.get_secret_value(),
) as client,
):
# 创建代理定义
agent_definition = await client.agents.create_agent(
model=ai_agent_settings.model_deployment_name,
name="Host",
instructions="回答关于菜单的问题。",
)
# 创建 Azure AI 代理
agent = AzureAIAgent(
client=client,
definition=agent_definition,
plugins=[MenuPlugin()],
)
thread: AzureAIAgentThread | None = None
user_inputs = [
"Hello",
"特价汤品是什么?",
"价格是多少?",
"谢谢你",
]
try:
for user_input in user_inputs:
print(f"# 用户: '{user_input}'")
response = await agent.get_response(
messages=user_input,
thread_id=thread,
)
print(f"# {response.name}: {response.content}")
thread = response.thread
finally:
if thread:
await thread.delete()
await client.agents.delete_agent(agent.id)
if __name__ == "__main__":
asyncio.run(main())
核心概念
-
Agent(代理)
Azure AI Agent Service 集成于 Azure AI Foundry 中。AI 代理是一个“智能”微服务,可用于回答问题(如检索增强生成,RAG)、执行操作或完全自动化工作流程。它结合了生成式 AI 模型和工具,使其能访问和操作真实世界的数据源。
例如:agent = project_client.agents.create_agent( model="gpt-4o-mini", name="my-agent", instructions="You are helpful agent", tools=code_interpreter.definitions, tool_resources=code_interpreter.resources, ) -
Thread 和 Messages(线程与消息)
线程表示代理与用户间的对话或交互。它用于跟踪对话进度、存储上下文和管理状态。示例:thread = project_client.agents.create_thread() message = project_client.agents.create_message( thread_id=thread.id, role="user", content="请帮我用以下数据创建一张营业利润条形图,并把文件发给我:公司A 120万美元,公司B 250万美元,公司C 300万美元,公司D 180万美元" ) run = project_client.agents.create_and_process_run(thread_id=thread.id, agent_id=agent.id) messages = project_client.agents.list_messages(thread_id=thread.id) print(f"Messages: {messages}")通过线程可以管理不同类型的消息,如文本、图片或文件,方便后续处理和展示。
-
与其他 AI 框架集成
Azure AI Agent Service 能与 AutoGen、Semantic Kernel 等框架协同工作,你可以用这些框架构建应用的一部分,也可以完全依赖 Azure AI Agent Service 进行管理和部署。
###v 适用场景
Azure AI Agent Service 设计用于需要安全、可扩展、灵活 AI 代理部署的企业应用。
框架对比
| 框架 | 重点 | 核心概念 | 适用场景 |
|---|---|---|---|
| AutoGen | 事件驱动、分布式多代理系统 | 代理、角色、功能、数据 | 代码生成、数据分析 |
| Semantic Kernel | 理解和生成自然语言文本 | 代理、模块化组件、协作 | 自然语言理解、内容生成 |
| Azure AI Agent Service | 灵活模型、企业安全、代码生成、工具调用 | 模块化、协作、流程编排 | 安全、可扩展、灵活的企业级代理部署 |
选择建议
- 如果你想快速试验和原型多代理系统,AutoGen 是最佳选择。
- 如果你要构建生产级、多模型、多代理的企业应用,建议先用 Semantic Kernel 开发,再用 Azure AI Agent Service 部署。
- Azure AI Agent Service 具备深度 Azure 集成,适合需要无缝接入 Azure 生态的场景,比如 Bing 搜索、Azure AI Search 和 Azure Functions。
更多推荐



所有评论(0)