共用方式為


Microsoft Agent Framework 代理類型

Microsoft 代理程式架構提供數種類型的代理程式支援,以適應不同的使用案例和需求。

所有代理程式都衍生自通用基類, AIAgent該基類為所有代理程式類型提供一致的介面。 這允許建置通用的、與代理程式無關的更高層級功能,例如多代理程式協調流程。

這很重要

如果您使用 Microsoft 代理程式架構來建置與協力廠商伺服器或代理程式搭配運作的應用程式,則風險由您自行承擔。 我們建議您檢閱與第三方伺服器或代理程式共用的所有資料,並瞭解第三方資料保留和位置的做法。 您有責任管理您的資料是否會流向組織的 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 代理程式服務作為其後端的代理程式。 Yes
Azure AI Foundry 模型 ChatCompletion 代理程式透過 ChatCompletion 將 Azure AI Foundry Service 中部署的任何模型用作其後端。 Yes
Azure AI Foundry 模型回應 透過 Azure AI Foundry Service 中的回應機制,使用任何已部署的模型作為其後端的代理程式。 Yes
Azure OpenAI 聊天完成 使用 Azure OpenAI ChatCompletion 服務的代理程式。 Yes
Azure OpenAI 回應 使用 Azure OpenAI 回應服務的代理程式。 Yes Yes
OpenAI 聊天完成 使用 OpenAI ChatCompletion 服務的代理程式。 Yes
OpenAI 回應 使用 OpenAI Responses 服務的代理程式。 Yes Yes
OpenAI 助手 使用 OpenAI Assistants 服務的代理程式。 Yes
任何其他 IChatClient 您也可以使用任何其他 Microsoft.Extensions.AI.IChatClient 實作來建立代理程式。 不定 不定

複雜的自訂代理程式

也可以建立完全客製化的代理,而不是僅僅包裹在 IChatClient 之中。 代理程式架構提供 AIAgent 基本類型。 此基礎型態是所有代理的核心抽象,當被子類化時,允許對代理的行為與能力進行完全控制。

欲了解更多資訊,請參閱 《海關代理人》相關文件。

遠端代理的代理程式

代理框架提供開箱即可使用的通用服務託管的代理協定實作,例如 A2A。 如此一來,您就可以從應用程式輕鬆連線及使用遠端代理程式。

如需詳細資訊,請參閱每種代理程式類型的文件:

協定 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-<資源>.services.ai.azure.com/
Azure AI Foundry 模型 OpenAI SDK 3 OpenAI https://ai-foundry-<資源>.services.ai.azure.com/openai/v1/
Azure AI Foundry 模型 Azure AI 推斷 SDK 2 Azure.AI.推論 https://ai-foundry-<資源>.services.ai.azure.com/models
Azure AI Foundry 代理程式 Azure AI 持續性代理程式 SDK Azure.AI.Agents.Persistent https://ai-foundry-<資源>.services.ai.azure.com/api/projects/ai-project 項目<>
Azure OpenAI1 Azure OpenAI SDK 2 Azure.AI.OpenAI https://< 資源>.openai.azure.com/
Azure OpenAI1 OpenAI 開發套件 OpenAI https://< 資源>.openai.azure.com/openai/v1/
OpenAI OpenAI 開發套件 OpenAI 無需網址
  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。 請參閱上表,瞭解要使用的正確網址。

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 代理程式服務。 請參閱上表,瞭解要使用的正確網址。

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 代理程式服務作為其後端的代理程式。 Yes
Azure OpenAI 聊天完成 使用 Azure OpenAI 聊天完成服務的代理程式。 Yes
Azure OpenAI 回應 使用 Azure OpenAI 回應服務的代理程式。 Yes Yes
OpenAI 聊天完成 使用 OpenAI 聊天完成服務的代理程式。 Yes
OpenAI 回應 使用 OpenAI Responses 服務的代理程式。 Yes Yes
OpenAI 助手 使用 OpenAI Assistants 服務的代理程式。 Yes
任何其他聊天客戶端 您也可以使用任何其他聊天用戶端實作來建立代理程式。 不定 不定

功能工具

您可以向客服專員提供功能工具以增強功能:

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")

如需程式碼解譯器範例,請參閱:

客製化 Agent

也可以建立完全自訂的代理,不只是聊天客戶端的封裝器。 代理程式架構提供 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