陳述性代理

宣告式代理允許你使用 YAML 或 JSON 檔案來定義代理配置,而非撰寫程式化程式碼。 這種方式讓代理更容易定義、修改並在團隊間共享。

Prerequisites

要在 C# 中使用宣告式代理,請將 Microsoft.Agents.AI.Declarative NuGet 套件加入你的專案,與你的服務提供者的聊天客戶端套件(例如 Azure.AI.OpenAI):

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

Microsoft.Agents.AI.Declarative 套件提供了 ChatClientPromptAgentFactory 型別及 CreateFromYamlAsync 擴展方法,適用於下方範例中的 PromptAgentFactory

定義一個與 YAML 內嵌的代理

你可以直接在程式碼中定義完整的 YAML 規範,然後從中建立AIAgent一個字串:ChatClientPromptAgentFactory

using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
    ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";

// Create the chat client
IChatClient chatClient = new AzureOpenAIClient(
    new Uri(endpoint),
    new DefaultAzureCredential())
        .GetChatClient(deploymentName)
        .AsIChatClient();

// Define the agent using a YAML definition.
var yamlDefinition =
    """
    kind: Prompt
    name: Assistant
    description: Helpful assistant
    instructions: You are a helpful assistant. You answer questions in the language specified by the user. You return your answers in a JSON format.
    model:
        options:
            temperature: 0.9
            topP: 0.95
    outputSchema:
        properties:
            language:
                type: string
                required: true
                description: The language of the answer.
            answer:
                type: string
                required: true
                description: The answer text.
    """;

// Create the agent from the YAML definition.
var agentFactory = new ChatClientPromptAgentFactory(chatClient);
var agent = await agentFactory.CreateFromYamlAsync(yamlDefinition);

// Invoke the agent and output the text result.
Console.WriteLine(await agent!.RunAsync("Tell me a joke about a pirate in English."));

// Invoke the agent with streaming support.
await foreach (var update in agent!.RunStreamingAsync("Tell me a joke about a pirate in French."))
{
    Console.WriteLine(update);
}

警告

DefaultAzureCredential 開發方便,但在生產過程中需謹慎考量。 在生產環境中,建議使用特定的憑證(例如 ManagedIdentityCredential),以避免延遲問題、意外的憑證探測,以及備援機制帶來的安全風險。

從 YAML 檔案載入代理

你也可以將 YAML 定義存於獨立檔案中,並在執行時載入,這樣可以更容易獨立於程式碼分享、版本化和編輯代理設定:

using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
    ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";

// Create the chat client.
IChatClient chatClient = new AzureOpenAIClient(
    new Uri(endpoint),
    new DefaultAzureCredential())
        .GetChatClient(deploymentName)
        .AsIChatClient();

// Read the YAML agent definition from a file.
var yamlFilePath = "agent.yaml";
var yamlDefinition = await File.ReadAllTextAsync(yamlFilePath);

// Create the agent from the YAML definition.
var agentFactory = new ChatClientPromptAgentFactory(chatClient);
var agent = await agentFactory.CreateFromYamlAsync(yamlDefinition);

// Invoke the agent and output the text result.
Console.WriteLine(await agent!.RunAsync("Tell me a joke about a pirate in English."));

Prerequisites

若要在 Python 中使用宣告式代理,請將 agent-framework-declarative 套件與你的聊天用戶端的提供者套件一併安裝(例如,Microsoft Foundry 的 agent-framework-foundry,或 Azure AI Foundry 的 agent-framework-azure-ai):

pip install agent-framework-declarative agent-framework-foundry --pre

套件 agent-framework-declarative 提供了 AgentFactory 以下範例中使用的類別及 create_agent_from_yaml and create_agent_from_yaml_path 方法。

定義一個與 YAML 內嵌的代理

你可以直接在程式碼中定義完整的 YAML 規格,作為字串:

import asyncio

from agent_framework.declarative import AgentFactory
from azure.identity.aio import AzureCliCredential


async def main():
    """Create an agent from an inline YAML definition and run it."""
    yaml_definition = """kind: Prompt
name: DiagnosticAgent
displayName: Diagnostic Assistant
instructions: Specialized diagnostic and issue detection agent for systems with critical error protocol and automatic handoff capabilities
description: An agent that performs diagnostics on systems and can escalate issues when critical errors are detected.

model:
  id: =Env.AZURE_OPENAI_MODEL
  connection:
    kind: remote
    endpoint: =Env.FOUNDRY_PROJECT_ENDPOINT
"""
    async with (
        AzureCliCredential() as credential,
        AgentFactory(client_kwargs={"credential": credential}).create_agent_from_yaml(yaml_definition) as agent,
    ):
        response = await agent.run("What can you do for me?")
        print("Agent response:", response.text)


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

從 YAML 檔案載入代理

你也可以從檔案載入 YAML 定義:

import asyncio
from pathlib import Path

from agent_framework.declarative import AgentFactory
from azure.identity.aio import AzureCliCredential


async def main():
    """Create an agent from a declarative YAML file and run it."""
    yaml_path = Path(__file__).parent / "agent-config.yaml"

    async with (
        AzureCliCredential() as credential,
        AgentFactory(client_kwargs={"credential": credential}).create_agent_from_yaml_path(yaml_path) as agent,
    ):
        response = await agent.run("Why is the sky blue?")
        print("Agent response:", response.text)


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

後續步驟