I want to stream the results of a completion via OpenAI's API.
The doc's mention using server-sent events - it seems like this isn't handled out of the box for flask so I was trying to do it client side (I know this exposes API keys). However, because the OpenAI API requires it post it seems like it isn't compatible with the eventSource API. I tried doing it via a fetch (Using readable streams) but when I try to convert to JSON via the example I get the following error: Uncaught (in promise) SyntaxError: Unexpected token 'd', "data: {"id"... is not valid JSON
(I know this isn't valid JSON). It seems like it is parsing the entire result not each individual stream.
data: {"id": "cmpl-5l11I1kS2n99uzNiNVpTjHi3kyied", "object": "text_completion", "created": 1661887020, "choices": [{"text": " to", "index": 0, "logprobs": null, "finish_reason": null}], "model": "text-davinci-002"}
data: {"id": "cmpl-5l11I1kS2n99uzNiNVpTjHi3kyied", "object": "text_completion", "created": 1661887020, "choices": [{"text": " AL", "index": 0, "logprobs": null, "finish_reason": null}], "model": "text-davinci-002"}
data: {"id": "cmpl-5l11I1kS2n99uzNiNVpTjHi3kyied", "object": "text_completion", "created": 1661887020, "choices": [{"text": "I", "index": 0, "logprobs": null, "finish_reason": null}], "model": "text-davinci-002"}
Would love some pointers or a simple code example of how to do this because I've been banging my head against it for a while. Thanks!
javascript const data = bytes.toString(); const message = data.replace(/^data: /, ""); console.log(JSON.parse(message));
and that's it. – Ahoufe