How to retrieve most recent message from a given thread when we do not know message-ID?
I would like to do so, because to know the message-ID, I need to get the whole thread. To increase the throughput of my chatbot-system, I am interested to retrieve more recent message without knowing its ID from a given thread.
Please help …
Hi, you can do that with this.
import OpenAI from "openai";
const openai = new OpenAI();
async function main() {
const threadMessages = await openai.beta.threads.messages.list(
"thread_abc123"
);
console.log(threadMessages.data);
}
main();
Thanks Bernejorge!
But I think with the above code we will get all the messages in the given thread (not just the response to my last query). While I am interested in last response only.
Of course, it (last message) could be fetched from all message but for sake of optimisation “last message only”.
When run.status === “completed” I get the last message as follows.
// Get the last assistant message from the messages array
const messages = await openai.beta.threads.messages.list(this.thread.id);
// Find the last message for the current run
const lastMessageForRun = messages.data
.filter(
(message) => message.run_id === run.id && message.role === "assistant"
)
.pop();
// If an assistant message is found, console.log() it
if (lastMessageForRun) {
console.log(`${lastMessageForRun.content[0].text.value} \n`);
return `${lastMessageForRun.content[0].text.value} \n`;
}
return "Lo siento no pude recuperar tu respuesta.";