Hello All, I have an issue with my code, I keep getting different errors when trying to implement Assistant API. My code is attached below:
import dotenv from 'dotenv';
dotenv.config();
import express from 'express';
import axios from 'axios';
const router = express.Router();
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const ASSISTANT_ID = 'asst_b4UtFGVw5lkrrSJpud6moq7V'; // Replace with your Assistant ID
const OPENAI_API_BASE_URL = 'https://api.openai.com/v1';
if (!OPENAI_API_KEY) {
console.error('Error: OPENAI_API_KEY is not set in the environment variables.');
process.exit(1);
}
router.post('/chat', async (req, res) => {
try {
const userMessage = req.body?.message;
if (!userMessage) {
return res.status(400).json({ error: 'Message is required' });
}
console.log('User message:', userMessage);
// 🟢 Step 1: Create a thread
const threadResponse = await axios.post(
`${OPENAI_API_BASE_URL}/assistants/threads`,
{}, // Do NOT send assistant_id here
{
headers: {
'Authorization': `Bearer ${OPENAI_API_KEY}`,
'Content-Type': 'application/json',
'OpenAI-Beta': 'assistants=v2' // Ensure Assistants API is enabled
}
}
);
const threadId = threadResponse?.data?.id;
if (!threadId) {
console.error('Failed to create thread: Thread ID is undefined');
return res.status(500).json({ error: 'Failed to create thread' });
}
console.log('Thread ID:', threadId);
// 🟢 Step 2: Add user message into the thread
const messageResponse = await axios.post(
`${OPENAI_API_BASE_URL}/assistants/threads/${threadId}/messages`,
{
role: 'user',
content: userMessage
},
{
headers: {
'Authorization': `Bearer ${OPENAI_API_KEY}`,
'Content-Type': 'application/json',
'OpenAI-Beta': 'assistants=v2' // Ensure Assistants API is enabled
}
}
);
if (!messageResponse) {
throw new Error(`Failed to add message to thread ${threadId}`);
}
console.log('User message sent to thread:', threadId);
// 🟢 Step 3: Run the assistant in the thread
const runResponse = await axios.post(
`${OPENAI_API_BASE_URL}/assistants/threads/${threadId}/runs`,
{
assistant_id: ASSISTANT_ID // ✅ Send assistant_id here, not in threads
},
{
headers: {
'Authorization': `Bearer ${OPENAI_API_KEY}`,
'Content-Type': 'application/json',
'OpenAI-Beta': 'assistants=v2' // Ensure Assistants API is enabled
}
}
);
const aiResponse = runResponse?.data?.choices?.[0]?.message?.content;
if (!aiResponse) {
console.error('No AI response received.');
return res.status(500).json({ error: 'No AI response received.' });
}
console.log('AI Response:', aiResponse);
res.json({ reply: aiResponse });
} catch (error) {
console.error('Error calling OpenAI:', error.response?.data || error.message);
res.status(500).json({ error: 'API failed: ' + (error.response?.data?.error?.message || error.message) });
}
});
export default router;
I would appriciate any help on the matter as I dont know JavaScript ( I am a front-end coder) and am ironically relying on ChatGPT for help.