async function handleChatGPTRequest(req, res) {
let full =""
const chatHistory = req.body.updatedChat;
console.log(chatHistory)
try {
const response = await openai.chat.completions.create({
messages: chatHistory,
model: 'gpt-4o',
max_tokens:90,
stream: true,
});
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
for await (const chunk of response) {
// console.log(chunk.choices[0]?.delta?.content || "");
let text = chunk.choices[0]?.delta?.content || "";
full += text
console.log(full)
res.write(text)
}
// console.log(response.choices[0]);
// res.json(response.choices[0]);
// console.log(chatHistory);
res.end()
} catch (error) {
console.error('Error:', error);
res.status(500).json({ error: 'An error occurred while processing your request' });
}
}
this is my node.js endpoint for openai
but error occurs whenever i try to get the data of the response in the frontend and stream it.
const Response = await fetch('http://192.168.188.90:8000/chatGPT',{
method:'POST',
body:JSON.stringify({updatedChat}),
headers:{ 'Content-Type':'application/json' }
})
if (!Response.ok) {
throw new Error('Network response was not ok');
}else{
const reader = Response.body?.pipeThrough(new TextDecoderStream()).getReader();
let receivedData = '';
console.log(Response)
console.log(Response["body"])
try {
while (true && reader) {
const { value, done } = await reader?.read();
if (done) break;
receivedData += value;
console.log('Received:', value); // You can update your UI or state here
setData((prev) => prev + value); // Assuming you have a 'setData' function to update state
}
} finally {
reader?.releaseLock();
}
console.log('Received data:', receivedData);
}
the error states: JSON Parse error: Unexpected character: B
(B is the correct starting character of the response from the backend)
but the weird thing is that front cant see the Response.body but the pypethrough function can.
any solutions or alternative ways of solving this?
the error states: JSON Parse error: Unexpected character: B
(B is the correct starting character of the response from the backend)
but the weird thing is that front cant see the Response.body but the pypethrough function can.
any solutions or alternative ways of solving this?