Microsoft Agent Framework 代理类型

Microsoft代理框架为多种类型的代理提供支持,以适应不同的用例和要求。

所有代理都派生自通用基类, AIAgent该类为所有代理类型提供一致的接口。 这允许生成与代理无关的更高级别的常见功能,例如多代理业务流程。

重要

如果使用 Microsoft Agent Framework 生成使用第三方服务器或代理运行的应用程序,则自行承担风险。 建议查看与第三方服务器或代理共享的所有数据,并识别第三方保留和位置数据的做法。 您负责管理数据是否将流出组织的 Azure 合规性和地理边界以及任何相关影响。

基于推理服务的简单代理

借助代理框架,可以轻松基于许多不同的推理服务创建简单的代理。 提供 Microsoft.Extensions.AI.IChatClient 实现的任何推理服务都可用于生成这些代理。 Microsoft.Agents.AI.ChatClientAgent是用于为任何IChatClient实现提供代理的代理类。

这些代理程序原生支持多种功能:

  1. 函数调用
  2. 使用本地聊天历史记录管理或服务提供的聊天历史记录管理进行多轮次对话
  3. 自定义服务提供的工具(例如 MCP、代码执行)
  4. 结构化输出

要创建这些代理之一,只需使用所选的ChatClientAgent实现来构造一个IChatClient

using Microsoft.Agents.AI;

var agent = new ChatClientAgent(chatClient, instructions: "You are a helpful assistant");

对于许多常用服务,我们还提供帮助程序,以便更轻松地创建这些代理。 有关详细信息,请参阅每个服务的文档:

基础推理服务 Description 支持服务聊天历史记录存储 支持的自定义聊天历史记录存储
Azure AI Foundry 代理 使用 Azure AI Foundry Agents 服务作为其后台的代理。 是的
Azure AI Foundry 模型 ChatCompletion 使用 Azure AI Foundry 服务中部署的任何模型作为其后端通过 ChatCompletion 的代理。 是的
Azure AI Foundry 模型响应 使用 Azure AI Foundry 服务中部署的任何模型,通过响应作为其后端的代理。 是的
Azure OpenAI ChatCompletion 使用 Azure OpenAI ChatCompletion 服务的代理。 是的
Azure OpenAI 响应 使用 Azure OpenAI 响应服务的代理。 是的 是的
OpenAI ChatCompletion 使用 OpenAI ChatCompletion 服务的代理。 是的
OpenAI 响应 使用 OpenAI 响应服务的代理。 是的 是的
OpenAI 助手 使用 OpenAI 助手服务的代理。 是的
任何其他 IChatClient 还可以使用任何其他 Microsoft.Extensions.AI.IChatClient 实现来创建代理。 多种多样 多种多样

复杂的自定义代理

还可以创建完全自定义的代理,而不仅仅是围绕IChatClient的包装器。 代理框架提供 AIAgent 基类型。 此基类型是所有代理的核心抽象,通过子类化可以完全控制代理的行为和功能。

有关详细信息,请参阅 自定义代理 的文档。

远程代理的代理服务器

代理框架开箱即用地为常见服务托管代理协议(如 A2A)提供AIAgent 实现。 这样,可以轻松地从应用程序连接到和使用远程代理。

有关详细信息,请参阅每种代理类型的文档:

协议 Description
A2A 一个通过 A2A 协议充当远程代理的代理。

Azure 和 OpenAI SDK 选项参考

使用 Azure AI Foundry、Azure OpenAI 或 OpenAI 服务时,可以使用各种 SDK 选项连接到这些服务。 在某些情况下,可以使用多个 SDK 连接到同一服务或使用同一 SDK 连接到不同的服务。 下面是连接到每个 URL 时应使用的不同选项的列表。 请务必用您的实际资源和项目名称替换 <resource><project>

AI 服务 SDK Nuget 网址
Azure AI Foundry 模型 Azure OpenAI SDK 2 Azure.AI.OpenAI https://ai-foundry-<resource.services.ai.azure.com/>
Azure AI Foundry 模型 OpenAI SDK 3 OpenAI https://ai-foundry-<resource.services.ai.azure.com/openai/v1/>
Azure AI Foundry 模型 Azure AI 推理 SDK 2 Azure.AI.Inference https://ai-foundry-<resource.services.ai.azure.com/models>
Azure AI Foundry 软件代理 Azure AI 持久代理 SDK Azure.AI.Agents.Persistent https://ai-foundry-<resource.services.ai.azure.com/api/projects/ai-project-project><>
Azure OpenAI1 Azure OpenAI SDK 2 Azure.AI.OpenAI <https:// resource.openai.azure.com/>
Azure OpenAI1 OpenAI SDK OpenAI <https://resource.openai.azure.com/openai/v1/>
OpenAI OpenAI SDK OpenAI 不需要 URL
  1. 从 Azure OpenAI 升级到 Azure AI Foundry
  2. 建议使用 OpenAI SDK。
  3. 虽然我们建议使用 OpenAI SDK 访问 Azure AI Foundry 模型,但 Azure AI Foundry 模型支持来自许多不同的供应商的模型,而不仅仅是 OpenAI。 所有这些模型都通过 OpenAI SDK 受支持。

使用 OpenAI SDK

如上表所示,OpenAI SDK 可用于连接到多个服务。 根据要连接到的服务,在创建 OpenAIClient 时,可能需要设置自定义 URL。 还可以根据服务使用不同的身份验证机制。

如果需要自定义 URL(请参阅上表),可以通过 OpenAIClientOptions 对其进行设置。

var clientOptions = new OpenAIClientOptions() { Endpoint = new Uri(serviceUrl) };

创建客户端时可以使用 API 密钥。

OpenAIClient client = new OpenAIClient(new ApiKeyCredential(apiKey), clientOptions);

使用 Azure 服务时,也可以使用 Azure 凭据而不是 API 密钥。

OpenAIClient client = new OpenAIClient(new BearerTokenPolicy(new AzureCliCredential(), "https://ai.azure.com/.default"), clientOptions)

创建 OpenAIClient 后,可以获取要使用的特定服务的子客户端,然后从该服务创建一个 AIAgent

AIAgent agent = client
    .GetChatClient(model)
    .CreateAIAgent(instructions: "You are good at telling jokes.", name: "Joker");

使用 Azure OpenAI SDK

此 SDK 可用于连接到 Azure OpenAI 和 Azure AI Foundry 模型服务。 无论哪种情况,在创建AzureOpenAIClient时,都需要提供正确的服务 URL。 有关要使用的正确 URL,请参阅上表。

AIAgent agent = new AzureOpenAIClient(
    new Uri(serviceUrl),
    new AzureCliCredential())
     .GetChatClient(deploymentName)
     .CreateAIAgent(instructions: "You are good at telling jokes.", name: "Joker");

使用 Azure AI 持久代理 SDK

此 SDK 仅受 Azure AI Foundry 代理服务支持。 有关要使用的正确 URL,请参阅上表。

var persistentAgentsClient = new PersistentAgentsClient(serviceUrl, new AzureCliCredential());
AIAgent agent = await persistentAgentsClient.CreateAIAgentAsync(
    model: deploymentName,
    name: "Joker",
    instructions: "You are good at telling jokes.");

基于推理服务的简单代理

借助代理框架,可以轻松基于许多不同的推理服务创建简单的代理。 提供聊天客户端实现的任何推理服务都可用于生成这些代理。

这些代理程序原生支持多种功能:

  1. 函数调用
  2. 使用本地聊天历史记录管理或服务提供的聊天历史记录管理进行多轮次对话
  3. 自定义服务提供的工具(例如 MCP、代码执行)
  4. 结构化输出
  5. 流式处理响应

若要创建其中一个代理,只需使用所选的聊天客户端实现来构造一个 ChatAgent

from agent_framework import ChatAgent
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import DefaultAzureCredential

async with (
    DefaultAzureCredential() as credential,
    ChatAgent(
        chat_client=AzureAIAgentClient(async_credential=credential),
        instructions="You are a helpful assistant"
    ) as agent
):
    response = await agent.run("Hello!")

或者,可以在聊天客户端上使用便利方法:

from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import DefaultAzureCredential

async with DefaultAzureCredential() as credential:
    agent = AzureAIAgentClient(async_credential=credential).create_agent(
        instructions="You are a helpful assistant"
    )

有关详细示例,请参阅下面的特定于代理的文档部分。

支持的代理类型

基础推理服务 Description 支持服务聊天历史记录存储 支持的自定义聊天历史记录存储
Azure AI 代理 使用 Azure AI 代理服务作为其后端的代理。 是的
Azure OpenAI 聊天完成 使用 Azure OpenAI 聊天完成服务的代理。 是的
Azure OpenAI 响应 使用 Azure OpenAI 响应服务的代理。 是的 是的
OpenAI 聊天完成 使用 OpenAI 聊天完成服务的代理。 是的
OpenAI 响应 使用 OpenAI 响应服务的代理。 是的 是的
OpenAI 助手 使用 OpenAI 助手服务的代理。 是的
任何其他聊天客户端 还可以使用任何其他聊天客户端实现来创建代理。 多种多样 多种多样

函数工具

可以为代理提供函数工具,以便增强功能:

from typing import Annotated
from pydantic import Field
from azure.identity.aio import DefaultAzureCredential
from agent_framework.azure import AzureAIAgentClient

def get_weather(location: Annotated[str, Field(description="The location to get the weather for.")]) -> str:
    """Get the weather for a given location."""
    return f"The weather in {location} is sunny with a high of 25°C."

async with (
    DefaultAzureCredential() as credential,
    AzureAIAgentClient(async_credential=credential).create_agent(
        instructions="You are a helpful weather assistant.",
        tools=get_weather
    ) as agent
):
    response = await agent.run("What's the weather in Seattle?")

有关函数工具的完整示例,请参阅:

流式处理响应

代理支持流式响应和常规响应。

# Regular response (wait for complete result)
response = await agent.run("What's the weather like in Seattle?")
print(response.text)

# Streaming response (get results as they are generated)
async for chunk in agent.run_stream("What's the weather like in Portland?"):
    if chunk.text:
        print(chunk.text, end="", flush=True)

有关流式处理示例,请参阅:

代码解释器工具

Azure AI 代理支持用于执行 Python 代码的托管代码解释器工具:

from agent_framework import ChatAgent, HostedCodeInterpreterTool
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import DefaultAzureCredential

async with (
    DefaultAzureCredential() as credential,
    ChatAgent(
        chat_client=AzureAIAgentClient(async_credential=credential),
        instructions="You are a helpful assistant that can execute Python code.",
        tools=HostedCodeInterpreterTool()
    ) as agent
):
    response = await agent.run("Calculate the factorial of 100 using Python")

有关代码解释器示例,请参阅:

自定义智能体

还可以创建完全自定义的代理,这些代理不仅仅是聊天客户端的包装器。 代理框架提供 AgentProtocol 协议和基类,当实现/子类时,该协议和 BaseAgent 基类允许完全控制代理的行为和功能。

from agent_framework import BaseAgent, AgentRunResponse, AgentRunResponseUpdate, AgentThread, ChatMessage
from collections.abc import AsyncIterable

class CustomAgent(BaseAgent):
    async def run(
        self,
        messages: str | ChatMessage | list[str] | list[ChatMessage] | None = None,
        *,
        thread: AgentThread | None = None,
        **kwargs: Any,
    ) -> AgentRunResponse:
        # Custom agent implementation
        pass

    def run_stream(
        self,
        messages: str | ChatMessage | list[str] | list[ChatMessage] | None = None,
        *,
        thread: AgentThread | None = None,
        **kwargs: Any,
    ) -> AsyncIterable[AgentRunResponseUpdate]:
        # Custom streaming implementation
        pass