Bringing Open AI Assistant on website

Dear community,
I encounted with an API endpoints issue.
I created an Assistant on Open AI and wanted to call it on my website. That is a sample of a code that I used:

<script>
document.getElementById("sendButton").addEventListener("click", function() {
    var userInput = document.getElementById("userInput").value;
    sendMessageToOpenAI(userInput);
});

function sendMessageToOpenAI(message) {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "https://api.openai.com/v1/assistants/asst_4hK1G0w4UqAakDD4N9M9ri08/messages");
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.setRequestHeader("Authorization", "Bearer ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■XXXXXXXX");

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            console.log("Full API answer: ", xhr.responseText);
            var response = JSON.parse(xhr.responseText);

            if (response.choices) {
                var aiMessage = response.choices[0].text.trim();
                displayMessage(aiMessage);
            } else {
                console.error("Answer doesnt contain 'choices'");
            }
        }
    };

    var data = JSON.stringify({
        model: "cospaces-assistant",
        messages: [{
            role: "user",
            content: message
        }]
    });

    xhr.send(data);
}

function displayMessage(message) {
    var messagesContainer = document.getElementById("messages");
    var messageDiv = document.createElement("div");
    messageDiv.textContent = message;
    messagesContainer.appendChild(messageDiv);
}
</script>

I received

Full API answer: {
“error”: {
“message”: “Invalid URL (POST /v1/assistants/asst_4hK1G0w4UqAakDD4N9M9ri08/messages)”,
“type”: “invalid_request_error”,
“param”: null,
“code”: null
}
}

I tried different options but without any success, so I’ve got lost with this ;/
Need your expert vision.
Thanks in advance

I don’t think there is a model names 'cospaces-assistant", try any from the list https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo

1 Like

This should not be done in client code!

You are exposing your API key to the world (or at least those who have access to view your web pages!)

You should move any Open AI calls to your server where your key can be kept secret.

Yep, this is a temporary solution while testing, I gonna move it to the separate proxy environment. But thank you for your forethought!

1 Like