선언적 에이전트

선언적 에이전트를 사용하면 프로그래밍 코드를 작성하는 대신 YAML 또는 JSON 파일을 사용하여 에이전트 구성을 정의할 수 있습니다. 이 접근 방식을 사용하면 에이전트가 팀 간에 보다 쉽게 정의, 수정 및 공유할 수 있습니다.

사전 요구 사항

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

사전 요구 사항

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 아래 예제에서 AgentFactorycreate_agent_from_yaml 사용되는 클래스와 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())

다음 단계: