gpt4 book ai didi

typescript - 是否可以在服务器发送的事件之间添加延迟?

转载 作者:行者123 更新时间:2023-12-02 05:49:26 30 4
gpt4 key购买 nike

我在 OpenAI 的 /v1/chat/completions 端点 ( https://platform.openai.com/docs/api-reference/chat/create ) 上使用 stream=true 标志。

目前,我通过使用 Date.now() 为每个传入 block 分配时间戳并将其添加到 Firestore 中的文档来处理服务器发送的事件。然后客户端将根据时间戳对这些 block 进行排序并将它们附加在一起。

例如,一个示例文档如下所示: A screenshot of the Firestore Document

这种方法的问题是......有时 block 发送得太快!

例如,chunk1 的时间戳可为 1682970460319,如果 chunk2 发送得足够快,它也可具有相同的 Date.now() 时间戳为 1682970460319,导致冲突。

我能想到的唯一解决方法是是否可以在服务器发送的事件之间添加一个小的延迟以防止冲突。否则,我不太确定如何解决这个问题。

这是我的 https 调用:

const req = https.request(
{
hostname: "api.openai.com",
port: 443,
path: "/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + apiKey,
},
},
function (res) {
res.on("data", async (data) => {
const timestamp = Date.now();
// Messages in the event stream are separated by a pair of newline characters.
const payloads = data.toString().split("\n\n");
for (const payload of payloads) {
if (payload.includes("[DONE]")) return;
if (payload === undefined) continue;
if (payload.startsWith("data:")) {
const data = payload.replaceAll(/(\n)?^data:\s*/g, ""); // in case there's multiline data event
try {
const delta = JSON.parse(data.trim());
const content = delta.choices[0].delta?.content;
console.log({content, timestamp})
if (!content) continue;
await handleNewChunk(content, timestamp);
} catch (error) {
console.log(`Error with JSON.parse and ${payload}.\n${error}`);
}
}
}
});
res.on("end", () => {
console.log("No more data in response.");
});
}
);

最佳答案

正如 Doug 在他的评论中所说,这里使用时间戳是不正确的。因为 block 具有自然排序,所以我最终使用了在每个 block 之后递增的索引。

关于typescript - 是否可以在服务器发送的事件之间添加延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76150014/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com