我有一个文本流,我将其发送到函数以转换为语音。我逐句发送文本以获得更好的延迟。我遇到的问题是处理中断。现在,我将每个句子发送到包含承诺的函数。因此,我最终得到了一个等待链,该等待链很快就会堆积起来,因此当我尝试中断该函数时,尽管它正确地中断了,但等待链仍然继续运行。这是代码片段(send_voice 返回一个承诺)
const stream = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: conversation_history,
stream: true,
});
let sentence = "";
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || "";
sentence += content;
if (interruptionState.value){
console.log("breaking");
break; //break correctly called but send_voice chain continues
}
if (sentence.endsWith('.') || sentence.endsWith('!') || sentence.endsWith('?')) {
console.log("FINAL: ", sentence);
conversation_history.push({ "role": "system", "content": sentence });
await send_voice(sentence, ws, elleven_key, voice_id,interruptionState);
sentence = "";
}
}
我知道我无法停止等待链,但是有什么办法可以解决这个问题吗?我本质上需要顺序调用 send_voice 并能够在中断时快速停止它。我已经被困在这个问题上有一段时间了,所以任何帮助将不胜感激!
我已经被困在这个问题上有一段时间了,所以任何帮助将不胜感激!
希望有帮助。
const stream = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: conversation_history,
stream: true,
});
const improveStream = stream.map(item => {
return new Promise(async res => {
item.then(async chunk => {
await checkInterruptionState()
res(chunk)
})
})
})
function checkInterruptionState() {
return new Promise(res => {
if (interruptionState.value) {
console.log("breaking");
//break correctly called but send_voice chain continues
const Interval = setInterval(() => {
if (!interruptionState.value) {
clearInterval(Interval )
res()
}
}, 200)
} else {
res()
}
})
}
let sentence = "";
for await (const chunk of improveStream ) {
const content = chunk.choices[0] ? .delta ? .content || "";
sentence += content;
if (sentence.endsWith('.') || sentence.endsWith('!') || sentence.endsWith('?')) {
console.log("FINAL: ", sentence);
conversation_history.push({
"role": "system",
"content": sentence
});
await send_voice(sentence, ws, elleven_key, voice_id, interruptionState);
sentence = "";
}
}