I can’t seem to get my API code to work in JS for my chatbot in HTML…
Here is the code:
// Function to fetch a response from OpenAI
const getResponse = async (userMessage) => {
try {
const response = await fetch(‘https://api.openai.com/v1/assistants’, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
‘Authorization’: Bearer ${OPENAI_API_KEY},
‘OpenAI-Beta’: ‘assistants=v2’ // Add this header
},
body: JSON.stringify({
assistant_id: ASSISTANT_ID, // Use assistant ID here
messages: [
{ role: “system”, content: “You are chatting with an AI assistant.” },
{ role: “user”, content: userMessage }
],
max_tokens: 150
})
});
// Parse the response
const data = await response.json();
// Log the entire response for debugging
console.log("API response:", data);
// Handle response error
if (!response.ok) {
throw new Error(data.error.message || "API request failed");
}
// Check if data and choices exist
if (data.choices && data.choices.length > 0) {
return data.choices[0].message.content.trim();
} else {
throw new Error("No valid choices returned in the response");
}
} catch (error) {
console.error("Error fetching response:", error);
return "Der opstod en fejl ved hentning af svar fra assistenten.";
}