共用方式為


使用 Agent Framework 建立和執行代理程式

本教學課程示範如何根據 Azure OpenAI 聊天完成服務,使用代理程式架構建立和執行代理程式。

這很重要

代理程式架構支援許多不同類型的代理程式。 本教學課程使用以聊天完成服務為基礎的代理程式,但所有其他代理程式類型都會以相同的方式執行。 如需其他代理程式類型以及如何建構它們的詳細資訊,請參閱代理 程式架構使用者指南

先決條件

開始之前,請確定您具備下列先決條件:

備註

Microsoft Agent Framework 支援所有主動支援的 .NET 版本。 基於此範例的目的,建議使用 .NET 8 SDK 或更新版本。

這很重要

本教學課程會針對聊天完成服務使用 Azure OpenAI,但您可以使用任何提供 IChatClient 實作的推斷服務。

安裝 NuGet 套件

若要搭配 Azure OpenAI 使用 Microsoft Agent Framework,您必須安裝下列 NuGet 套件:

dotnet add package Azure.AI.OpenAI --prerelease
dotnet add package Azure.Identity
dotnet add package Microsoft.Agents.AI.OpenAI --prerelease

建立代理程式

  • 首先,提供 Azure OpenAI 端點,並使用您在必要 條件 步驟中使用 Azure CLI 驗證時所使用的相同登入,以建立 Azure OpenAI 的用戶端。
  • 然後,取得聊天用戶端以與聊天完成服務通訊,您也可以在其中指定要使用的特定模型部署。 使用您在 必要條件 步驟中建立的其中一個部署。
  • 最後,建立代理程式,提供代理程式的指示和名稱。
using System;
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using OpenAI;

AIAgent agent = new AzureOpenAIClient(
    new Uri("https://<myresource>.openai.azure.com"),
    new AzureCliCredential())
        .GetChatClient("gpt-4o-mini")
        .CreateAIAgent(instructions: "You are good at telling jokes.", name: "Joker");

執行代理程式

若要執行代理程式,請在代理程式執行個體上呼叫 RunAsync 方法,並提供使用者輸入。 代理程式將傳回一個 AgentRunResponse 物件,並在此回應物件上呼叫 .ToString().Text ,提供來自代理程式的文字結果。

Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate."));

範例輸出:

Why did the pirate go to school?

Because he wanted to improve his "arrr-ticulation"! 🏴‍☠️

使用串流執行代理程式

若要使用串流執行代理程式,請在代理程式執行個體上呼叫 RunStreamingAsync 方法,並提供使用者輸入。 代理程式會傳回串流 AgentRunResponseUpdate 物件,並在每個更新物件上呼叫 .ToString().Text 提供該更新中包含的文字結果部分。

await foreach (var update in agent.RunStreamingAsync("Tell me a joke about a pirate."))
{
    Console.WriteLine(update);
}

範例輸出:

Why
 did
 the
 pirate
 go
 to
 school
?


To
 improve
 his
 "
ar
rrrr
rr
tic
ulation
!"

使用 ChatMessages 執行代理程式

您可以提供一或多個ChatMessage物件給RunAsyncRunStreamingAsync方法,而不是僅提供簡單的字串。

以下是具有單一使用者訊息的範例:

ChatMessage message = new(ChatRole.User, [
    new TextContent("Tell me a joke about this image?"),
    new UriContent("https://upload.wikimedia.org/wikipedia/commons/1/11/Joseph_Grimaldi.jpg", "image/jpeg")
]);

Console.WriteLine(await agent.RunAsync(message));

範例輸出:

Why did the clown bring a bottle of sparkling water to the show?

Because he wanted to make a splash!

以下是包含系統和使用者訊息的範例:

ChatMessage systemMessage = new(
    ChatRole.System,
    """
    If the user asks you to tell a joke, refuse to do so, explaining that you are not a clown.
    Offer the user an interesting fact instead.
    """);
ChatMessage userMessage = new(ChatRole.User, "Tell me a joke about a pirate.");

Console.WriteLine(await agent.RunAsync([systemMessage, userMessage]));

範例輸出:

I'm not a clown, but I can share an interesting fact! Did you know that pirates often revised the Jolly Roger flag? Depending on the pirate captain, it could feature different symbols like skulls, bones, or hourglasses, each representing their unique approach to piracy.

本教學課程示範如何根據 Azure OpenAI 聊天完成服務,使用代理程式架構建立和執行代理程式。

這很重要

代理程式架構支援許多不同類型的代理程式。 本教學課程使用以聊天完成服務為基礎的代理程式,但所有其他代理程式類型都會以相同的方式執行。 如需其他代理程式類型以及如何建構它們的詳細資訊,請參閱代理 程式架構使用者指南

先決條件

開始之前,請確定您具備下列先決條件:

這很重要

本教學課程會針對聊天完成服務使用 Azure OpenAI,但您可以使用任何與代理程式架構聊天用戶端通訊協定相容的推斷服務。

安裝 Python 套件

若要搭配 Azure OpenAI 使用 Microsoft Agent Framework,您必須安裝下列 Python 套件:

pip install agent-framework --pre

建立代理程式

  • 首先,建立聊天用戶端以與 Azure OpenAI 通訊,並使用您在必要 條件 步驟中使用 Azure CLI 驗證時所使用的相同登入。
  • 然後,建立代理程式,並提供代理程式的指示和名稱。
import asyncio
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential

agent = AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
    instructions="You are good at telling jokes.",
    name="Joker"
)

執行代理程式

若要執行代理程式,請在代理程式執行個體上呼叫 run 方法,並提供使用者輸入。 代理程式會傳回回應物件,而存取屬性 .text 會提供來自代理程式的文字結果。

async def main():
    result = await agent.run("Tell me a joke about a pirate.")
    print(result.text)

asyncio.run(main())

使用串流執行代理程式

若要使用串流執行代理程式,請在代理程式執行個體上呼叫 run_stream 方法,並提供使用者輸入。 代理程式會即時傳送更新物件的清單,並且透過存取每個更新物件上的屬性來提供該更新中包含的文字結果部分。

async def main():
    async for update in agent.run_stream("Tell me a joke about a pirate."):
        if update.text:
            print(update.text, end="", flush=True)
    print()  # New line after streaming is complete

asyncio.run(main())

使用 ChatMessage 執行代理程式

您可以提供一或多個ChatMessage物件給runrun_stream方法,而不是僅提供簡單的字串。

from agent_framework import ChatMessage, TextContent, UriContent, Role

message = ChatMessage(
    role=Role.USER,
    contents=[
        TextContent(text="Tell me a joke about this image?"),
        UriContent(uri="https://samplesite.org/clown.jpg", media_type="image/jpeg")
    ]
)

async def main():
    result = await agent.run(message)
    print(result.text)

asyncio.run(main())

後續步驟