返回对象处理
返回对象分析
根据流式返回的数据处理
内容对象
{
"choices": [
{
"delta": { "content": "", "role": "assistant" },
"index": 0,
"logprobs": null,
"finish_reason": null,
},
],
"object": "chat.completion.chunk",
"usage": null,
"created": 1733319748,
"system_fingerprint": null,
"model": "qwen2-vl-7b-instruct",
"id": "chatcmpl-34615907-7d35-9f8a-993b-af7c94ea8717",
}
最后一条显示token的内容
{
"choices": [],
"object": "chat.completion.chunk",
"usage": { "prompt_tokens": 29, "completion_tokens": 100, "total_tokens": 129 },
"created": 1733319748,
"system_fingerprint": null,
"model": "qwen2-vl-7b-instruct",
"id": "chatcmpl-34615907-7d35-9f8a-993b-af7c94ea8717",
}
将上面两个json内容合并生成一个对象类,主要就是choices字段和usage字段合并两个类就行了
具体操作就是复制json内容,切换到一个空的类文件中,然后在“编辑”→“选择性粘贴”→“将JSON 粘贴为类”操作,自动生产类,
将上面两个json都生成一遍,合并主类为StreamObject
,得到json类如下
public class StreamObject
{
public Choice[] choices { get; set; }
public string _object { get; set; }
public Usage usage { get; set; }
public int created { get; set; }
public object system_fingerprint { get; set; }
public string model { get; set; }
public string id { get; set; }
}
public class Choice
{
public Delta delta { get; set; }
public object finish_reason { get; set; }
public int index { get; set; }
public object logprobs { get; set; }
}
public class Delta
{
public string content { get; set; }
}
public class Usage
{
public int prompt_tokens { get; set; }
public int completion_tokens { get; set; }
public int total_tokens { get; set; }
}
流式对象反序列化
对返回的数据进行反序列化,然后判断choices数量,获取里面的content内容
额外的:可以sleep一下,可以看到像对话一样流式输出的效果了
var streamObject = JsonSerializer.Deserialize<StreamObject>(data);
if (streamObject.choices.Count() > 0)
{
var contentRes = streamObject.choices[0].delta.content;
Console.Write(contentRes);
}
效果:
显示提取出的内容
视频教程
<iframe allowfullscreen="true" data-mediaembed="bilibili" frameborder="0" id="F7218D1F-1733708526719" src="https://player.bilibili.com/player.html?aid=113586802333458"></iframe>.Net+AI开发入门HttpClient实现通义千问集成-流式输出内容提取和实现
标签:set,千问,get,C#,object,choices,tokens,public,HttpClient From: https://blog.csdn.net/qq_39427511/article/details/144338545