app.post(“/chat”, async (req, res) => {
7
console.log(req.body.prompt);
const thread = await openAI.beta.threads.create({
messages: [{
role: "user",
content: [{
type: "text",
text: req.body.prompt,
}],
}],
});
const assistantFilePath = "./assistant.json"
const assistantData = await fsPromises.readFile(
assistantFilePath,
"utf8"
);
assistantDetails = JSON.parse(assistantData);
assistantId = assistantDetails.assistantId;
console.log(assistantId);
const run = await openAI.beta.threads.runs.create({
threads_id: thread.id,
assistant_id: assistantId,
});
let message = await openAI.beta.threads.runs.retrieve(
thread.id, run.id);
while(message.status !== "completed") {
await new Promise((resolve) => setTimeout(resolve, 1000));
message = await openAI.beta.threads.runs.retrieve(
thread.id, run.id);
if(message.status.includes(["failed", "cancelled", "expired"])) {
console.log(
`Run status is ${message.status}. Chat paused...`
);
break;
}
}
const messages = await openAI.beta.threads.messages.list(thread.id);
const messageToBeShown = messages.data
.filter((msg) => msg.run_id === run.id && msg.role === "assistant").pop();
if(messageToBeShown) {
console.log(messageToBeShown.content[0].text.value + "\n");
}
res.send(messageToBeShown.content[0].text.value + "\n");
})
I get this error and Im not sure why. Any help is appreciated.