Marked as helpful by the asker
Your server collects the whole stream into text and only then responds. Streaming from OpenAI to your server doesn't help if you don't pass it on. Return a stream:
export async function POST(req: Request) {
const { messages } = await req.json();
const completion = await openai.chat.completions.create({ model, messages, stream: true });
const encoder = new TextEncoder();
const body = new ReadableStream({
async start(controller) {
for await (const chunk of completion) {
const t = chunk.choices[0]?.delta?.content;
if (t) controller.enqueue(encoder.encode(t));
}
controller.close();
},
});
return new Response(body, { headers: { "Content-Type": "text/plain; charset=utf-8" } });
}On the client, read with res.body.getReader() and a TextDecoder, appending as chunks arrive. The Vercel AI SDK wraps all of this if you'd rather not do it by hand.
oh. I was streaming into a variable. works now, text comes in nicely yusuf_k · edited
textbefore returning, right? Look at the loop. mei_lin · edited