Skip to content

声明性代理

声明性代理允许使用 YAML 或 JSON 文件定义 Agent 配置,而不是编写编程代码。此方法使 Agent 更易于跨团队定义、修改和共享。


先决条件

在 C# 中使用声明性代理,需要添加 Microsoft.Agents.AI.Declarative NuGet 包:

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

该包在 ChatClientPromptAgentFactory 上提供了 CreateFromYamlAsync 扩展方法。

使用 YAML 内联定义

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

var endpoint = Environment
    .GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")!;
var deploymentName = Environment
    .GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME")
    ?? "gpt-4o-mini";

IChatClient chatClient = new AzureOpenAIClient(
    new Uri(endpoint), new DefaultAzureCredential())
        .GetChatClient(deploymentName)
        .AsIChatClient();

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.
    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.
    """;

var agentFactory = new ChatClientPromptAgentFactory(chatClient);
var agent = await agentFactory
    .CreateFromYamlAsync(yamlDefinition);

Console.WriteLine(await agent!
    .RunAsync("Tell me a joke in English."));

从 YAML 文件加载

将 YAML 定义存储在单独的文件中。例如 agent.yml

yaml
kind: Prompt
name: Assistant
description: Helpful assistant
instructions: |
  You are a helpful assistant.
  You answer questions in the language specified by the user.
model:
  options:
    temperature: 0.9
    topP: 0.95

然后从文件加载:

csharp
var yamlContent = await File.ReadAllTextAsync("agent.yml");
var agent = await agentFactory
    .CreateFromYamlAsync(yamlContent);

YAML Schema 字段

字段必填说明
kind代理类型,目前为 Prompt
name代理名称
description代理描述
instructions系统指令/提示词
model.options.temperature模型温度参数
model.options.topP模型 topP 参数
outputSchema结构化输出定义,含 properties 字段

声明性代理的核心价值在于配置与代码分离。团队中的非开发人员(如 PM、领域专家)可以直接编辑 YAML 文件调整 Agent 行为,无需改动 C# 代码。


下一步:可观测性 — 通过 OpenTelemetry 监控 Agent。

学而不思则罔,思而不学则殆