-
I am trying to setup Vercel AI SDK with an express endpoint which I will then use with After all my custom logic I have a This just has a |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 12 replies
-
You can use |
Beta Was this translation helpful? Give feedback.
-
Not sure if this helps, but the AI SDK uses the Node standard fetch. Have you tried setting the following in
More info: https://remix.run/docs/en/main/guides/single-fetch |
Beta Was this translation helpful? Give feedback.
-
I just used On the client: const { messages, input, handleInputChange, handleSubmit } =
useChat({
// Use streamProtocol 'text' so the server can sent text deltas directly without SSE framing
streamProtocol: 'text',
}); On the server: app.post('/api/chat', async (req, res) => {
const { messages } = req.body as { messages: CoreMessage[] };
if (!messages) {
res.status(400).send('messages field in body is required');
return;
}
// Set headers for streaming plain text (not SSE)
res.setHeader('Content-Type', 'text/plain;charset=utf-8');
res.setHeader('Cache-Control', 'no-cache, no-transform');
res.setHeader('Connection', 'keep-alive');
res.flushHeaders(); // Ensure headers are sent immediately
try {
const { textStream } = await streamText({
model: openai('gpt-4o'),
messages,
onFinish: event => {
console.log('onFinish', event.text);
// TODO: save to database
},
});
for await (const delta of textStream) {
// Client's useChat is configured to use streamProtocol 'text', so we can send text deltas directly
// without SSE framing.
res.write(delta);
}
res.end();
} catch (error) {
console.error('Error processing request:', error);
res.status(500).send('Internal server error');
}
}); |
Beta Was this translation helpful? Give feedback.
I just figured this out. Just leaving the idea here for anyone else stumbling on this discussion looking for answers:
Copy-paste the file from this comment: #199 (comment)
Take the response from
openai.createChatCompletion()
and re-create it as:Then use the
new StreamingTextResponse(OpenAiStream(resp))
to create the stream that can be returned from remix-run action.