-
返回结构化结果需要对应的 AI 支持 (OpenAI),发出请求时指定 response_format 为 json_schema, 然后 json_schema 属性指定返回的结构
-
可以通过修改提示词,强制要求返回结构化结果,在某些 AI 上,它还是会返回兼容结果,从而成功运行。测试时在 ollama + phi4, 通义上都正常的返回指定的结构。
-
下面的例子,使用 mitmproxy 监听后台数据,然后复制出 json schema 作为提示词进行提交
using var client = serviceProvider.GetRequiredService<IChatClient>();
using var configChatClient = client.ConfigChatClient();
var options = new ChatOptions
{
ConversationId = $"{Guid.CreateVersion7()}",
ResponseFormat = ChatResponseFormat.Text, // 这里指定返回的是文本
};
// options.ResponseFormat = ChatResponseFormat.ForJsonSchema(); // 对支持的 AI 指定返回结构
var messages = new List<ChatMessage>
{
new(ChatRole.System, @"你是一位情绪分析专家。请必须返回 json 格式,返回 json schema定义如下:
{
""$schema"": ""https://json-schema.org/draft/2020-12/schema"",
""type"": ""object"",
""properties"": {
""data"": {
""$schema"": ""https://json-schema.org/draft/2020-12/schema"",
""type"": ""string"",
""enum"": [
""Positive"",
""Angry"",
""Sad"",
""Neutral"",
""Negative""
]
}
},
""additionalProperties"": false,
""required"": [
""data""
]
}"),
new(ChatRole.User, "请分析下面这句话的情绪:我今天很生气。"),
};
var result = await client.GetResponseAsync<Sentiment>(messages, options);
this.LogInfo($"{result.Result}");
private enum Sentiment
{
/// <summary>
/// 积极情绪 - Positive emotion
/// </summary>
Positive,
/// <summary>
/// 愤怒情绪 - Angry emotion
/// </summary>
Angry,
/// <summary>
/// 悲伤情绪 - Sad emotion
/// </summary>
Sad,
/// <summary>
/// 中性情绪 - Neutral emotion
/// </summary>
Neutral,
/// <summary>
/// 消极情绪 - Negative emotion
/// </summary>
Negative,
}