I save the file to open ai, and wait for the completed status of a simple RUN. Then write a message on this file and it crashes with error 400 due to the fact that some other RUN (id is different at the same time) has already been created in the chat. Why does this happen?
I would put some logging into your code anywhere that an API call is made to a run endpoint, or for tool return.
You might see that you are the one doing this.
What, where, and how are you doing a “save the file to OpenAI”, though…
You can check for a run status and wait for it complete before submitting another message to the thread. Insert this function before the function code writing to the file
const checkAndCompleteActiveRun = async (threadId) => {
console.log("🔄 Checking for active runs on thread:", threadId);
try {
const runs = await openai.beta.threads.runs.list(threadId);
const activeRun = runs.data.find(
(run) => run.status === "in_progress" || run.status === "queued",
);
// console.log("runs", runs.data);
if (!activeRun) {
console.log("✅ No active runs found.");
return null;
}
console.log(
`🟡 Active run detected: ${activeRun.id}. Waiting for it to complete...`,
);
// ✅ Poll until OpenAI finishes processing
for (let attempt = 0; attempt < 20; attempt++) {
// Max retries to prevent infinite loops
const updatedRun = await openai.beta.threads.runs.retrieve(
threadId,
activeRun.id,
);
if (updatedRun.status === "completed") {
console.log(`✅ Active run ${activeRun.id} completed.`);
return updatedRun;
} else if (
updatedRun.status === "failed" ||
updatedRun.status === "cancelled"
) {
console.log(`❌ Active run ${activeRun.id} failed or was cancelled.`);
return null;
}
console.log("⏳ Waiting for OpenAI to finish processing...");
await new Promise((resolve) => setTimeout(resolve, 2000)); // Wait 2 seconds before retrying
}
console.log("⚠️ OpenAI run took too long to finish. Moving on...");
return null;
} catch (error) {
console.error("❌ Error checking for active runs:", error);
return null;
}
};
await checkAndCompleteActiveRun(thread.id);