共用方式為


工作流程中的代理

本教學課程示範如何使用代理程式架構將 AI 代理程式整合到工作流程中。 您將學習創建工作流程,利用專門的 AI 代理的強大功能來進行內容創建、審查和其他協作任務。

您將構建什麼

您將建立工作流程,以:

  • 使用 Azure Foundry 代理程式服務來建立智慧型代理程式
  • 實作法語翻譯代理,將輸入翻譯成法語
  • 實施將法語翻譯成西班牙語的西班牙語翻譯代理
  • 實施一個英語翻譯程式,將西班牙語翻譯回英語。
  • 在循序工作流程管線中連接代理人
  • 在客服人員處理請求時串流即時更新
  • 示範如何為 Azure Foundry 代理程式正確地釋放資源

涵蓋概念

先決條件

步驟 1:安裝 NuGet 套件

首先,安裝 .NET 專案所需的套件:

dotnet add package Azure.AI.Agents.Persistent --prerelease
dotnet add package Azure.Identity
dotnet add package Microsoft.Agents.AI.AzureAI --prerelease
dotnet add package Microsoft.Agents.AI.Workflows --prerelease

步驟 2:設定 Azure Foundry 用戶端

使用環境變數和驗證來設定 Azure Foundry 用戶端:

using System;
using System.Threading.Tasks;
using Azure.AI.Agents.Persistent;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Workflows;
using Microsoft.Extensions.AI;

public static class Program
{
    private static async Task Main()
    {
        // Set up the Azure Foundry client
        var endpoint = Environment.GetEnvironmentVariable("AZURE_FOUNDRY_PROJECT_ENDPOINT") ?? throw new Exception("AZURE_FOUNDRY_PROJECT_ENDPOINT is not set.");
        var model = Environment.GetEnvironmentVariable("AZURE_FOUNDRY_PROJECT_MODEL_ID") ?? "gpt-4o-mini";
        var persistentAgentsClient = new PersistentAgentsClient(endpoint, new AzureCliCredential());

步驟三:建立代理工廠方法

實作協助程式方法,以使用特定指示建立 Azure Foundry 代理程式:

    /// <summary>
    /// Creates a translation agent for the specified target language.
    /// </summary>
    /// <param name="targetLanguage">The target language for translation</param>
    /// <param name="persistentAgentsClient">The PersistentAgentsClient to create the agent</param>
    /// <param name="model">The model to use for the agent</param>
    /// <returns>A ChatClientAgent configured for the specified language</returns>
    private static async Task<ChatClientAgent> GetTranslationAgentAsync(
        string targetLanguage,
        PersistentAgentsClient persistentAgentsClient,
        string model)
    {
        var agentMetadata = await persistentAgentsClient.Administration.CreateAgentAsync(
            model: model,
            name: $"{targetLanguage} Translator",
            instructions: $"You are a translation assistant that translates the provided text to {targetLanguage}.");

        return await persistentAgentsClient.GetAIAgentAsync(agentMetadata.Value.Id);
    }
}

步驟 4:建立專用的 Azure Foundry 代理

使用協助程式方法建立三個翻譯代理程式:

        // Create agents
        AIAgent frenchAgent = await GetTranslationAgentAsync("French", persistentAgentsClient, model);
        AIAgent spanishAgent = await GetTranslationAgentAsync("Spanish", persistentAgentsClient, model);
        AIAgent englishAgent = await GetTranslationAgentAsync("English", persistentAgentsClient, model);

步驟 5:建立工作流程

使用 WorkflowBuilder 在循序工作流程中連接代理程式:

        // Build the workflow by adding executors and connecting them
        var workflow = new WorkflowBuilder(frenchAgent)
            .AddEdge(frenchAgent, spanishAgent)
            .AddEdge(spanishAgent, englishAgent)
            .Build();

第 6 步:使用串流執行

使用串流執行工作流程,以觀察所有代理程式的即時更新:

        // Execute the workflow
        await using StreamingRun run = await InProcessExecution.StreamAsync(workflow, new ChatMessage(ChatRole.User, "Hello World!"));

        // Must send the turn token to trigger the agents.
        // The agents are wrapped as executors. When they receive messages,
        // they will cache the messages and only start processing when they receive a TurnToken.
        await run.TrySendMessageAsync(new TurnToken(emitEvents: true));
        await foreach (WorkflowEvent evt in run.WatchStreamAsync().ConfigureAwait(false))
        {
            if (evt is AgentRunUpdateEvent executorComplete)
            {
                Console.WriteLine($"{executorComplete.ExecutorId}: {executorComplete.Data}");
            }
        }

第 7 步:資源清理

使用後正確清除 Azure Foundry 代理程式:

        // Cleanup the agents created for the sample.
        await persistentAgentsClient.Administration.DeleteAgentAsync(frenchAgent.Id);
        await persistentAgentsClient.Administration.DeleteAgentAsync(spanishAgent.Id);
        await persistentAgentsClient.Administration.DeleteAgentAsync(englishAgent.Id);
    }

運作方式

  1. Azure Foundry 用戶端設定PersistentAgentsClient 搭配 Azure CLI 認證進行驗證
  2. 代理程式建立:在 Azure Foundry 上建立持續性代理程式,並提供特定的翻譯指示
  3. 順序處理:法語代理先翻譯輸入,然後翻譯西班牙語代理,然後翻譯英語代理
  4. 轉權杖模式:代理程式會快取訊息,並且僅在收到權杖後才處理訊息。
  5. 流式更新AgentRunUpdateEvent 在代理生成響應時提供實時標記更新
  6. 資源管理:使用系統管理 API 正確清除 Azure Foundry 代理程式

重要概念

  • Azure Foundry 代理服務:具有進階推理功能的雲端式 AI 代理程式
  • PersistentAgentsClient:用於在 Azure Foundry 上建立和管理代理程式的用戶端
  • AgentRunUpdateEvent:代理程式執行期間的即時串流更新
  • TurnToken:訊息快取後觸發代理程式處理的訊號
  • 循序工作流程:在管道中連接的代理程式,其中輸出從一個流向下一個

完成實施

如需此 Azure Foundry 代理程式工作流程的完整工作實作,請參閱代理程式架構存放庫中的 FoundryAgent Program.cs 範例。

您將構建什麼

您將建立工作流程,以:

  • 使用 Azure AI 代理程式服務來建立智慧型代理程式
  • 實作根據提示建立內容的 Writer 代理程式
  • 實作檢閱者代理程式,提供內容的意見反應
  • 在循序工作流程管線中連接代理人
  • 在客服人員處理請求時串流即時更新
  • 示範 Azure AI 客戶端的正確異步上下文管理

涵蓋概念

先決條件

  • Python 3.10 或更新版本
  • 已安裝代理程式架構: pip install agent-framework-azure-ai --pre
  • 使用適當環境變數設定的 Azure AI 代理程式服務
  • Azure CLI 驗證: az login

步驟 1:匯入所需的依賴項

首先匯入 Azure AI 代理程式和工作流程的必要元件:

import asyncio
from collections.abc import Awaitable, Callable
from contextlib import AsyncExitStack
from typing import Any

from agent_framework import AgentRunUpdateEvent, WorkflowBuilder, WorkflowOutputEvent
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential

步驟 2:建立 Azure AI 代理處理站

建立協助程式函式,以適當的非同步內容處理來管理 Azure AI 代理程式建立:

async def create_azure_ai_agent() -> tuple[Callable[..., Awaitable[Any]], Callable[[], Awaitable[None]]]:
    """Helper method to create an Azure AI agent factory and a close function.

    This makes sure the async context managers are properly handled.
    """
    stack = AsyncExitStack()
    cred = await stack.enter_async_context(AzureCliCredential())

    client = await stack.enter_async_context(AzureAIAgentClient(async_credential=cred))

    async def agent(**kwargs: Any) -> Any:
        return await stack.enter_async_context(client.create_agent(**kwargs))

    async def close() -> None:
        await stack.aclose()

    return agent, close

步驟 3:建立特製化的 Azure AI 代理程式

建立兩個專門的代理程式以進行內容建立和檢閱:

async def main() -> None:
    agent, close = await create_azure_ai_agent()
    try:
        # Create a Writer agent that generates content
        writer = await agent(
            name="Writer",
            instructions=(
                "You are an excellent content writer. You create new content and edit contents based on the feedback."
            ),
        )

        # Create a Reviewer agent that provides feedback
        reviewer = await agent(
            name="Reviewer",
            instructions=(
                "You are an excellent content reviewer. "
                "Provide actionable feedback to the writer about the provided content. "
                "Provide the feedback in the most concise manner possible."
            ),
        )

步驟 4:建立工作流程

使用流暢建構器將代理程式連接到循序工作流程中:

        # Build the workflow with agents as executors
        workflow = WorkflowBuilder().set_start_executor(writer).add_edge(writer, reviewer).build()

步驟 5:使用串流執行

使用串流執行工作流程,以觀察兩個代理程式的即時更新:

        last_executor_id: str | None = None

        events = workflow.run_stream("Create a slogan for a new electric SUV that is affordable and fun to drive.")
        async for event in events:
            if isinstance(event, AgentRunUpdateEvent):
                # Handle streaming updates from agents
                eid = event.executor_id
                if eid != last_executor_id:
                    if last_executor_id is not None:
                        print()
                    print(f"{eid}:", end=" ", flush=True)
                    last_executor_id = eid
                print(event.data, end="", flush=True)
            elif isinstance(event, WorkflowOutputEvent):
                print("\n===== Final output =====")
                print(event.data)
    finally:
        await close()

第 6 步:完成主要功能

使用適當的非同步執行將所有內容包裝在 main 函數中:

if __name__ == "__main__":
    asyncio.run(main())

運作方式

  1. Azure AI 用戶端設定AzureAIAgentClient 搭配 Azure CLI 認證進行驗證
  2. 代理程式工廠模式:建立工廠函數,用於管理多個代理程式的非同步上下文生命週期
  3. 順序處理: Writer 代理首先生成內容,然後將其傳遞給 Reviewer 代理
  4. 流式更新AgentRunUpdateEvent 在代理生成響應時提供實時標記更新
  5. 情境管理:使用 AsyncExitStack 妥善清理 Azure AI 資源

重要概念

  • Azure AI 代理服務: 基於雲的 AI 代理,具有高級推理能力
  • AgentRunUpdateEvent:代理程式執行期間的即時串流更新
  • AsyncExitStack:多個資源的適當非同步內容管理
  • 代理程式工廠模式:使用共用用戶端組態建立可重複使用的代理程式
  • 循序工作流程:在管道中連接的代理程式,其中輸出從一個流向下一個

完成實施

如需此 Azure AI 代理程式工作流程的完整工作實作,請參閱代理程式架構存放庫中的 azure_ai_agents_streaming.py 範例。

後續步驟