Streaming completions with the text completion API - 401 Error

Hey all,

I am trying to test the streaming parameter for the text completion API. However, I am receiving a 401 error when I run the code. If anyone could offer some guidance or advice, I would be so grateful. Thanks a bunch!

I already tested my API keys and it is working fine everywhere else. It just does not work here for some reason.

Here is the JavaScript code I am using:

var xhr = new XMLHttpRequest();
xhr.open("POST", "https://api.openai.com/v1/completions", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "Bearer ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■BglrxE8L");
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var eventSource = new EventSource(xhr.responseURL);
        eventSource.onmessage = function (event) {
            var result = JSON.parse(event.data);
            var label = document.querySelector("#completion");
            label.innerHTML += '<span id="text">' + result.text + '</span>';
        };
    }
};
xhr.send(JSON.stringify({
    "model": "text-davinci-003",
    "prompt": document.querySelector("#prompt").value,
    "temperature": 0.7,
    "max_tokens": 1000,
    "top_p": 1,
    "frequency_penalty": 0,
    "presence_penalty": 0,
    "stream": true
}));

To clarify, does it only give you a 401 when you set streaming to true? Or does it error regardless?

Yes indeed. The same code with the parameter “stream”: false or without the stream parameter works fine.