次の方法で共有


エージェントを使用した構造化出力の生成

このチュートリアルの手順では、エージェントを使用して構造化された出力を生成する方法について説明します。この場合、エージェントは Azure OpenAI Chat Completion サービス上に構築されます。

Important

すべてのエージェントの種類が構造化出力をサポートしているわけではありません。 この手順では、構造化された出力をサポートする ChatClientAgentを使用します。

[前提条件]

前提条件と NuGet パッケージのインストールについては、このチュートリアルの 「エージェントの作成と実行 」の手順を参照してください。

構造化された出力を使用してエージェントを作成する

ChatClientAgentは、IChatClientインプリメンテーションの上に構築されています。 ChatClientAgentは、基になるチャット クライアントによって提供される構造化された出力のサポートを使用します。

エージェントを作成するときに、基になるチャット クライアントに使用する既定の ChatOptions インスタンスを指定するオプションがあります。 この ChatOptions インスタンスを使用すると、優先する ChatResponseFormatを選択できます。

ResponseFormatのさまざまなオプションを使用できます。

  • 組み込みの ChatResponseFormat.Text プロパティ: 応答はプレーン テキストになります。
  • 組み込みの ChatResponseFormat.Json プロパティ: 応答は、特定のスキーマのない JSON オブジェクトになります。
  • カスタム ChatResponseFormatJson インスタンス: 応答は、特定のスキーマに準拠する JSON オブジェクトになります。

この例では、特定のスキーマに準拠する 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}");

ストリーミング時には、エージェントの応答は一連の更新としてストリーミングされ、すべての更新プログラムを受信した後にのみ応答を逆シリアル化できます。 逆シリアル化する前に、すべての更新を 1 つの応答にアセンブルする必要があります。

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 Chat Completion サービス上に構築されます。

Important

すべてのエージェントの種類が構造化出力をサポートしているわけではありません。 ChatAgentは、互換性のあるチャット クライアントで使用する場合の構造化された出力をサポートします。

[前提条件]

前提条件とパッケージのインストールについては、このチュートリアルの 「エージェントの作成と実行 」の手順を参照してください。

構造化された出力を使用してエージェントを作成する

ChatAgentは、構造化された出力をサポートするチャット クライアント実装の上に構築されています。 ChatAgentでは、response_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}")

次のステップ