我在opnai的文档中看到对stream: true的描述
stream: true
If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message. Example Python code.
这里使用了server-sent events
,我查看了server-sent events
的MDN文档,文档对server-sent events的使用说明是这样的,但是在课程的代码中没有看到类似的处理。
// 处理server-sent events
const evtSource = new EventSource(url)
evtSource.addEventlisenter('event', callback)
但是我不明白使用fetch请求的body是如何接收server-sent events的,我知道Response.body本身就是一个ReadableStream对象,例如下面这段代码:
fetch('https://www.example.org')
.then((response) => response.body)
.then((rb) => {
const reader = rb.getReader();
return new ReadableStream({
start(controller) {
// The following function handles each data chunk
function push() {
// "done" is a Boolean and value a "Uint8Array"
reader.read().then(({ done, value }) => {
// If there is no more data to read
if (done) {
console.log('done', done);
controller.close();
return;
}
// Get the data and send it to the browser via the controller
controller.enqueue(value);
// Check chunks by logging to the console
console.log(done, value);
push();
});
}
push();
},
});
})
.then((stream) =>
// Respond with our stream
new Response(stream, { headers: { 'Content-Type': 'text/html' } }).text()
)
.then((result) => {
// Do things with result
console.log(result);
});
流式解析好像和server-sent events本身并没有关系,就算没有server-sent events也依然可以流式解析响应,我理解的对吗?请老师解惑。