Hello I am experimenting with assistants, i have created one in my playground and would like to interrogate it from my homepage.
I have written down an elementary code (see below) on the track of the one i use to interrogate chatGPT but i always get a Bad request error when i send messages.
Can anybody point me to a solution? Please, no python nor node.js cause i don’t have them in my hosting account.
Than you very much in advance
// Define the function to add a message to the chat container
function appendMessage(container, message, sender) {
const messageElement = document.createElement('div');
messageElement.classList.add('message');
messageElement.classList.add(sender === 'user' ? 'from-user' : 'from-assistant');
messageElement.innerText = message;
container.appendChild(messageElement);
}
// Select the chat container and user input elements
const chatContainer = document.getElementById('chat-container');
const userInputForm = document.getElementById('user-input');
const messageInput = document.getElementById('message-input');
// Create a function to send a message to the assistant
async function sendMessage(message) {
appendMessage(chatContainer, message, 'user');
messageInput.value = ''; // Clear the input field
const response = await fetch('https://api.openai.com/v1/assistants/myassistantid', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer myownapikey',
'OpenAI-Beta': 'assistants=v1',
},
body: JSON.stringify({
'messages': [{'role': 'system', 'content': 'user'}, {'role': 'user', 'content': message}],
}),
});
const { choices } = await response.json();
if (choices && choices.length > 0) {
const assistantReply = choices[0].message.content;
appendMessage(chatContainer, assistantReply, 'assistant');
} else {
console.error('Empty or invalid response from API');
}
}
// Add an event listener to the form submit event
userInputForm.addEventListener('submit', function(e) {
e.preventDefault(); // Prevent the page from reloading
const message = messageInput.value;
if (message) {
sendMessage(message);
}
});