结构化输出
使用 Agent 生成结构化输出,其中 Agent 是基于 Azure OpenAI 聊天完成服务构建的。
并非所有代理类型都支持原生结构化输出。
ChatClientAgent在与兼容的聊天客户端一起使用时支持结构化输出。
方式一:RunAsync<T> 泛型方法
RunAsync<T> 方法在 AIAgent 基类上可用,接受指定结构化输出类型的泛型类型参数。
定义输出类型
csharp
public class PersonInfo
{
public string? Name { get; set; }
public int? Age { get; set; }
public string? Occupation { get; set; }
}运行并获取类型化结果
csharp
AgentResponse<PersonInfo> response = await agent
.RunAsync<PersonInfo>(
"Please provide information about John Smith, " +
"who is a 35-year-old software engineer.");
Console.WriteLine(
$"Name: {response.Result.Name}, " +
$"Age: {response.Result.Age}, " +
$"Occupation: {response.Result.Occupation}");适用场景:编译时已知结构类型,需要类型化结果实例。支持基元、数组和复杂类型。
方式二:ResponseFormat 配置
可以通过在调用时设置 ResponseFormat 属性 AgentRunOptions,或在代理初始化时配置结构化输出。
适用场景:
- 编译时结构类型未知
- 架构表示为原始 JSON
- 结构化输出只在代理创建时配置
- 只需要原始 JSON 文本,无需反序列化
- 使用代理间协作
ResponseFormat 选项
| 选项 | 说明 |
|---|---|
ChatResponseFormat.Text | 响应为纯文本 |
ChatResponseFormat.Json | JSON 对象(无特定模式) |
自定义 ChatResponseFormatJson | 符合特定 JSON Schema 的 JSON |
使用 JSON Schema
csharp
using System.Text.Json;
using Microsoft.Extensions.AI;
AgentRunOptions runOptions = new()
{
ResponseFormat = ChatResponseFormat.ForJsonSchema<PersonInfo>()
};
AgentResponse response = await agent.RunAsync(
"Please provide information about John Smith...",
options: runOptions);
PersonInfo personInfo =
JsonSerializer.Deserialize<PersonInfo>(
response.Text, JsonSerializerOptions.Web)!;
ResponseFormat方式不支持基元和数组。如果需要使用基元或数组,使用RunAsync<T>方法或创建包装器类型。
csharp
// 正确做法:为数组创建包装器类型
public class MovieListWrapper
{
public List<string> Movies { get; set; }
}下一步:后台响应 — 处理长时间运行的任务。