我正在尝试使用ChatGPT和Delphi,并使用位于https://github.com/HemulGM/DelphiOpenAI的OpenAI库。它支持流式传输,但我无法弄清楚ChatGPT的流式传输机制。我可以创建一个聊天,并在一次返回消息中获取所有数据。
然而,当我尝试使用流式传输时,我会遇到错误。以下控制台代码运行良好。我提交我的聊天,并在一次“事件”中获得完整的回答。我希望能像ChatGPT网站那样,显示生成的标记。我的代码如下…
var buf : TStringlist;begin... var Chat := OpenAI.Chat.Create( procedure(Params: TChatParams) begin Params.Messages([TChatMessageBuild.Create(TMessageRole.User, Buf.Text)]); Params.MaxTokens(1024); // Params.Stream(True); end); try for var Choice in Chat.Choices do begin Buf.Add(Choice.Message.Content); Writeln(Choice.Message.Content); end; finally Chat.Free; end;
这个代码是有效的。当我尝试开启流式传输时,我会得到’EConversionError’错误’输入值不是有效的对象’,这导致ChatGPT返回’空或无效的响应’。
回答:
因为在这种模式下,它的响应不是JSON对象,而是它自己的特殊格式。
data: {"id": "cmpl-6wsVxtkU0TZrRAm4xPf5iTxyw9CTf", "object": "text_completion", "created": 1679490597, "choices": [{"text": "\r", "index": 0, "logprobs": null, "finish_reason": null}], "model": "text-davinci-003"}data: {"id": "cmpl-6wsVxtkU0TZrRAm4xPf5iTxyw9CTf", "object": "text_completion", "created": 1679490597, "choices": [{"text": "\n", "index": 0, "logprobs": null, "finish_reason": null}], "model": "text-davinci-003"}data: {"id": "cmpl-6wsVxtkU0TZrRAm4xPf5iTxyw9CTf", "object": "text_completion", "created": 1679490597, "choices": [{"text": "1", "index": 0, "logprobs": null, "finish_reason": null}], "model": "text-davinci-003"}data: {"id": "cmpl-6wsVxtkU0TZrRAm4xPf5iTxyw9CTf", "object": "text_completion", "created": 1679490597, "choices": [{"text": ",", "index": 0, "logprobs": null, "finish_reason": null}], "model": "text-davinci-003"}data: {"id": "cmpl-6wsVxtkU0TZrRAm4xPf5iTxyw9CTf", "object": "text_completion", "created": 1679490597, "choices": [{"text": " 2", "index": 0, "logprobs": null, "finish_reason": null}], "model": "text-davinci-003"}...
我可以开始为该库开发这种模式。