Spaces:
Running
Running
File size: 900 Bytes
dff2be9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import type { ChatCompletionChunk } from "openai/resources";
export function createOpenAIStream(
completion: AsyncIterable<ChatCompletionChunk>,
callbacks: { onFinal: () => void }
): ReadableStream {
const { readable, writable } = new TransformStream();
const writer = writable.getWriter();
const encoder = new TextEncoder();
let isFinished = false;
async function forwardCompletion() {
try {
for await (const chunk of completion) {
const { content } = chunk.choices[0].delta;
if (content) {
await writer.write(encoder.encode(`0:${JSON.stringify(content)}\n`));
}
}
} catch (error) {
console.error("Error forwarding completion:", error);
await writer.abort(error);
} finally {
isFinished = true;
await writer.close();
callbacks.onFinal();
}
}
forwardCompletion();
return readable;
}
|