Bagikan melalui


Menghasilkan Output Terstruktur dengan Agen

Langkah tutorial ini menunjukkan kepada Anda cara menghasilkan output terstruktur dengan agen, di mana agen dibangun di layanan Penyelesaian Obrolan Azure OpenAI.

Penting

Tidak semua jenis agen mendukung output terstruktur. Langkah ini menggunakan ChatClientAgent, yang mendukung output terstruktur.

Prasyarat

Untuk prasyarat dan menginstal paket NuGet, lihat langkah Membuat dan menjalankan agen sederhana dalam tutorial ini.

Membuat agen dengan output terstruktur

ChatClientAgent dibangun di atas IChatClient implementasi apa pun. menggunakan ChatClientAgent dukungan untuk output terstruktur yang disediakan oleh klien obrolan yang mendasar.

Saat membuat agen, Anda memiliki opsi untuk menyediakan instans default ChatOptions yang akan digunakan untuk klien obrolan yang mendasar. Instans ini ChatOptions memungkinkan Anda untuk memilih pilihan ChatResponseFormat.

Berbagai opsi untuk ResponseFormat tersedia:

Contoh ini membuat agen yang menghasilkan output terstruktur dalam bentuk objek JSON yang sesuai dengan skema tertentu.

Cara termudah untuk menghasilkan skema adalah dengan menentukan tipe yang menggambarkan struktur output yang dihasilkan agen, kemudian dengan menggunakan metode AIJsonUtilities.CreateJsonSchema untuk membuat skema dari tipe tersebut.

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

Anda kemudian dapat membuat ChatOptions instans yang menggunakan skema ini untuk format respons.

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

Instans ini ChatOptions dapat digunakan saat membuat agen.

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 DefaultAzureCredential())
        .GetChatClient("gpt-4o-mini")
        .AsAIAgent(new ChatClientAgentOptions()
        {
            Name = "HelpfulAssistant",
            Instructions = "You are a helpful assistant.",
            ChatOptions = chatOptions
        });

Peringatan

DefaultAzureCredential nyaman untuk pengembangan tetapi membutuhkan pertimbangan yang cermat dalam produksi. Dalam produksi, pertimbangkan untuk menggunakan kredensial tertentu (misalnya, ManagedIdentityCredential) untuk menghindari masalah latensi, pemeriksaan kredensial yang tidak diinginkan, dan potensi risiko keamanan dari mekanisme fallback.

Sekarang Anda hanya dapat menjalankan agen dengan beberapa informasi tekstual yang dapat digunakan agen untuk mengisi output terstruktur.

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

Respons agen kemudian dapat dideserialisasi menjadi objek kelas PersonInfo menggunakan metode Deserialize<T> pada objek respons.

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

Saat streaming, respons agen dialirkan sebagai serangkaian pembaruan, dan Anda hanya dapat mendeserialisasi respons setelah semua pembaruan diterima. Anda harus merakit semua pembaruan menjadi satu respons sebelum mendeserialisasinya.

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

Petunjuk / Saran

Lihat sampel .NET untuk contoh lengkap yang dapat dijalankan.

Contoh streaming

Petunjuk / Saran

Lihat sampel .NET untuk contoh lengkap yang dapat dijalankan.

Langkah tutorial ini menunjukkan kepada Anda cara menghasilkan output terstruktur dengan agen, di mana agen dibangun di layanan Penyelesaian Obrolan Azure OpenAI.

Penting

Tidak semua jenis agen mendukung output terstruktur. Mendukung output terstruktur Agent saat digunakan dengan klien obrolan yang sesuai.

Prasyarat

Untuk prasyarat dan penginstalan paket, lihat langkah Buat dan jalankan agen sederhana dalam tutorial ini.

Membuat agen dengan output terstruktur

Agent dibangun di atas implementasi klien obrolan apa pun yang mendukung output terstruktur. Agent menggunakan response_format parameter untuk menentukan skema output yang diinginkan.

Saat membuat atau menjalankan agen, Anda dapat menyediakan model Pydantic yang menentukan struktur output yang diharapkan.

Berbagai format respons didukung berdasarkan kemampuan klien obrolan yang mendasar.

Contoh ini membuat agen yang menghasilkan output terstruktur dalam bentuk objek JSON yang sesuai dengan skema model Pydantic.

Pertama, tentukan model Pydantic yang mewakili struktur output yang Anda inginkan dari agen:

from pydantic import BaseModel

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

Sekarang Anda dapat membuat agen menggunakan Klien Obrolan 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()).as_agent(
    name="HelpfulAssistant",
    instructions="You are a helpful assistant that extracts person information from text."
)

Sekarang Anda dapat menjalankan agen dengan beberapa informasi tekstual dan menentukan format output terstruktur menggunakan response_format parameter :

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

Respons agen akan berisi output terstruktur dalam value properti , yang dapat diakses langsung sebagai instans model Pydantic:

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

Saat streaming, agent.run(..., stream=True) mengembalikan ResponseStream. Finalizer bawaan stream secara otomatis menangani proses penguraian keluaran terstruktur, sehingga Anda dapat melakukan iterasi untuk pembaruan real-time lalu memanggil get_final_response() untuk mendapatkan hasil yang sudah diurai.

# Stream updates in real time, then get the structured result
stream = agent.run(query, stream=True, options={"response_format": PersonInfo})
async for update in stream:
    print(update.text, end="", flush=True)

# get_final_response() returns the AgentResponse with the parsed value
final_response = await stream.get_final_response()

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

Jika Anda tidak perlu memproses pembaruan streaming individu, Anda dapat sepenuhnya melewati iterasi — get_final_response() akan secara otomatis mengonsumsi aliran tersebut.

stream = agent.run(query, stream=True, options={"response_format": PersonInfo})
final_response = await stream.get_final_response()

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

Contoh lengkap

# Copyright (c) Microsoft. All rights reserved.

import asyncio

from agent_framework.openai import OpenAIResponsesClient
from pydantic import BaseModel

"""
OpenAI Responses Client with Structured Output Example

This sample demonstrates using structured output capabilities with OpenAI Responses Client,
showing Pydantic model integration for type-safe response parsing and data extraction.
"""


class OutputStruct(BaseModel):
    """A structured output for testing purposes."""

    city: str
    description: str


async def non_streaming_example() -> None:
    print("=== Non-streaming example ===")

    agent = OpenAIResponsesClient().as_agent(
        name="CityAgent",
        instructions="You are a helpful agent that describes cities in a structured format.",
    )

    query = "Tell me about Paris, France"
    print(f"User: {query}")

    result = await agent.run(query, options={"response_format": OutputStruct})

    if structured_data := result.value:
        print("Structured Output Agent:")
        print(f"City: {structured_data.city}")
        print(f"Description: {structured_data.description}")
    else:
        print(f"Failed to parse response: {result.text}")


async def streaming_example() -> None:
    print("=== Streaming example ===")

    agent = OpenAIResponsesClient().as_agent(
        name="CityAgent",
        instructions="You are a helpful agent that describes cities in a structured format.",
    )

    query = "Tell me about Tokyo, Japan"
    print(f"User: {query}")

    # Stream updates in real time using ResponseStream
    stream = agent.run(query, stream=True, options={"response_format": OutputStruct})
    async for update in stream:
        if update.text:
            print(update.text, end="", flush=True)
    print()

    # get_final_response() returns the AgentResponse with structured output parsed
    result = await stream.get_final_response()

    if structured_data := result.value:
        print("Structured Output (from streaming with ResponseStream):")
        print(f"City: {structured_data.city}")
        print(f"Description: {structured_data.description}")
    else:
        print(f"Failed to parse response: {result.text}")


async def main() -> None:
    print("=== OpenAI Responses Agent with Structured Output ===")

    await non_streaming_example()
    await streaming_example()


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

Langkah selanjutnya