다음을 통해 공유


에이전트를 사용하여 구조적 출력 생성

이 자습서 단계에서는 에이전트를 사용하여 구조화된 출력을 생성하는 방법을 보여 줍니다. 여기서 에이전트는 Azure OpenAI 채팅 완료 서비스를 기반으로 합니다.

중요합니다

모든 에이전트 형식이 구조적 출력을 지원하는 것은 아닙니다. 이 단계에서는 구조화된 출력을 지원하는 ChatClientAgent를 사용합니다.

필수 조건

필수 구성 요소 및 NuGet 패키지 설치는 이 자습서의 간단한 에이전트 만들기 및 실행 단계를 참조하세요.

구조화된 출력을 사용하여 에이전트 만들기

모든 ChatClientAgent 구현을 기반으로 IChatClient 빌드됩니다. 기본 ChatClientAgent 채팅 클라이언트에서 제공하는 구조적 출력에 대한 지원을 사용합니다.

에이전트를 만들 때 기본 채팅 클라이언트에 사용할 기본 ChatOptions 인스턴스를 제공하는 옵션이 있습니다. 이 ChatOptions 인스턴스를 사용하면 기본 ChatResponseFormat설정을 선택할 수 있습니다.

ResponseFormat에 대한 다양한 옵션이 제공됩니다.

이 예제에서는 특정 스키마를 준수하는 JSON 개체의 형태로 구조화된 출력을 생성하는 에이전트를 만듭니다.

스키마를 생성하는 가장 쉬운 방법은 에이전트에서 원하는 출력의 구조를 나타내는 형식을 정의한 다음 메서드를 사용하여 AIJsonUtilities.CreateJsonSchema 형식에서 스키마를 만드는 것입니다.

using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.AI;

public class PersonInfo
{
    public string? Name { get; set; }
    public int? Age { get; set; }
    public string? Occupation { get; set; }
}

JsonElement schema = AIJsonUtilities.CreateJsonSchema(typeof(PersonInfo));

그런 다음, 응답 형식에 ChatOptions 이 스키마를 사용하는 인스턴스를 만들 수 있습니다.

using Microsoft.Extensions.AI;

ChatOptions chatOptions = new()
{
    ResponseFormat = ChatResponseFormat.ForJsonSchema(
        schema: schema,
        schemaName: "PersonInfo",
        schemaDescription: "Information about a person including their name, age, and occupation")
};

ChatOptions 인스턴스는 에이전트를 만들 때 사용할 수 있습니다.

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

AIAgent agent = new AzureOpenAIClient(
    new Uri("https://<myresource>.openai.azure.com"),
    new AzureCliCredential())
        .GetChatClient("gpt-4o-mini")
        .CreateAIAgent(new ChatClientAgentOptions()
        {
            Name = "HelpfulAssistant",
            Instructions = "You are a helpful assistant.",
            ChatOptions = chatOptions
        });

이제 에이전트가 구조화된 출력을 채우는 데 사용할 수 있는 몇 가지 텍스트 정보로 에이전트를 실행할 수 있습니다.

var response = await agent.RunAsync("Please provide information about John Smith, who is a 35-year-old software engineer.");

그런 다음, 응답 객체의 PersonInfo 메서드를 사용하여 에이전트 응답을 Deserialize<T> 클래스에 역직렬화할 수 있습니다.

var personInfo = response.Deserialize<PersonInfo>(JsonSerializerOptions.Web);
Console.WriteLine($"Name: {personInfo.Name}, Age: {personInfo.Age}, Occupation: {personInfo.Occupation}");

스트리밍할 때 에이전트 응답은 일련의 업데이트로 스트리밍되며 모든 업데이트를 받은 후에만 응답을 역직렬화할 수 있습니다. 역직렬화하기 전에 모든 업데이트를 단일 응답으로 어셈블해야 합니다.

var updates = agent.RunStreamingAsync("Please provide information about John Smith, who is a 35-year-old software engineer.");
personInfo = (await updates.ToAgentRunResponseAsync()).Deserialize<PersonInfo>(JsonSerializerOptions.Web);

이 자습서 단계에서는 에이전트를 사용하여 구조화된 출력을 생성하는 방법을 보여 줍니다. 여기서 에이전트는 Azure OpenAI 채팅 완료 서비스를 기반으로 합니다.

중요합니다

모든 에이전트 형식이 구조적 출력을 지원하는 것은 아닙니다. ChatAgent 호환되는 채팅 클라이언트와 함께 사용할 경우 구조화된 출력을 지원합니다.

필수 조건

필수 구성 요소 및 패키지 설치는 이 자습서의 간단한 에이전트 만들기 및 실행 단계를 참조하세요.

구조화된 출력을 사용하여 에이전트 만들기

모든 구조화된 출력을 지원하는 채팅 클라이언트 시스템을 기반으로 ChatAgent가 구축됩니다. 시스템 ChatAgentresponse_format 매개변수를 사용하여 원하는 출력 스키마를 지정합니다.

에이전트를 만들거나 실행할 때 예상 출력의 구조를 정의하는 Pydantic 모델을 제공할 수 있습니다.

기본 채팅 클라이언트 기능에 따라 다양한 응답 형식이 지원됩니다.

이 예제에서는 Pydantic 모델 스키마를 따르는 JSON 개체의 형태로 구조화된 출력을 생성하는 에이전트를 만듭니다.

먼저 에이전트에서 원하는 출력의 구조를 나타내는 Pydantic 모델을 정의합니다.

from pydantic import BaseModel

class PersonInfo(BaseModel):
    """Information about a person."""
    name: str | None = None
    age: int | None = None
    occupation: str | None = None

이제 Azure OpenAI 채팅 클라이언트를 사용하여 에이전트를 만들 수 있습니다.

from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential

# Create the agent using Azure OpenAI Chat Client
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(
    name="HelpfulAssistant",
    instructions="You are a helpful assistant that extracts person information from text."
)

이제 몇 가지 텍스트 정보로 에이전트를 실행하고 매개 변수를 사용하여 구조화된 출력 형식을 response_format 지정할 수 있습니다.

response = await agent.run(
    "Please provide information about John Smith, who is a 35-year-old software engineer.",
    response_format=PersonInfo
)

에이전트 응답에는 Pydantic 모델 인스턴스로 직접 액세스할 수 있는 구조화된 출력 value 이 속성에 포함됩니다.

if response.value:
    person_info = response.value
    print(f"Name: {person_info.name}, Age: {person_info.age}, Occupation: {person_info.occupation}")
else:
    print("No structured data found in response")

스트리밍할 때 에이전트 응답은 일련의 업데이트로 스트리밍됩니다. 구조화된 출력을 가져오려면 모든 업데이트를 수집한 다음 최종 응답 값에 액세스해야 합니다.

from agent_framework import AgentRunResponse

# Get structured response from streaming agent using AgentRunResponse.from_agent_response_generator
# This method collects all streaming updates and combines them into a single AgentRunResponse
final_response = await AgentRunResponse.from_agent_response_generator(
    agent.run_stream(query, response_format=PersonInfo),
    output_format_type=PersonInfo,
)

if final_response.value:
    person_info = final_response.value
    print(f"Name: {person_info.name}, Age: {person_info.age}, Occupation: {person_info.occupation}")

다음 단계