本教學課程步驟示範如何使用代理程式產生結構化輸出,其中代理程式是以 Azure OpenAI 聊天完成服務為基礎。
這很重要
並非所有代理程式類型都支援結構化輸出。 此步驟使用 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}");
串流時,代理程式回應會串流為一系列更新,而且只有在收到所有更新後,您才能還原序列化回應。 您必須將所有更新整合為一個回應才能進行反序列化。
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
)
代理回應將在value屬性中包含結構化輸出,並且可以直接作為 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")
串流時,代理程式回應會串流為一系列更新。 若要取得結構化輸出,您必須收集所有更新,然後存取最終回應值:
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}")