ERROR 401 Missing bearer or basic authentication in header GPT ASSISTANT

I am using the correct API key, and it even works in the same app but using completions. I have double-checked that I am passing it correctly, yet this issue persists. It doesn’t make any sense. I wonder if it’s an issue with the OpenAI library and how it makes API calls.

Can you check that you are using the latest openai library and also post a code snippet please.

import OpenAI from “openai”;
import Constants from ‘expo-constants’;

const API_KEY = Constants.expoConfig.extra.openaiApiKey; // Asegúrate de usar tu clave API de OpenAI
console.log(API_KEY)
const openai = new OpenAI({apiKey:API_KEY});

export default function Pruebagpt() {
const [message, setMessage] = useState(‘’);
const [messages, setMessages] = useState();
const scrollViewRef = useRef();

useEffect(() => {
    loadMessagesFromStorage();
    createPsychologistAssistant();
}, []);

const createPsychologistAssistant = async () => {
    try {
        const assistant = await openai.beta.assistants.create({
            name: "Psicólogo Virtual",
            instructions: "Eres un psicólogo profesional. Brindas apoyo, contención y nuevas perspectivas a distintas situaciones. Realizas preguntas introspectivas y mantienes una conversación empática y reflexiva.",
            model: "gpt-4-1106-preview"
        });

        console.log("Asistente de Psicólogo creado:", assistant);
        // Guarda el ID del asistente para su uso posterior
        assistantId = assistant.id; // Asegúrate de definir assistantId en el scope adecuado
    } catch (error) {
        console.error("Error al crear el asistente de psicólogo:", error);
    }
};

const loadMessagesFromStorage = async () => {
    try {
        const storedMessages = await AsyncStorage.getItem('chat_messages');
        if (storedMessages) {
            setMessages(JSON.parse(storedMessages));
        }
    } catch (error) {
        console.error("Error al cargar mensajes:", error);
    }
};


const handleSendMessage = async () => {
    if (message.trim()) {
        const newMessages = [...messages, { text: message, sender: 'user' }];
        setMessages(newMessages);
        await AsyncStorage.setItem('chat_messages', JSON.stringify(newMessages));
        setMessage('');

        try {
            console.log('Creando hilo...');
            const thread = await openai.beta.threads.create();

            console.log('Enviando mensaje al hilo...');
            await openai.beta.threads.messages.create(thread.id, {
                role: "user",
                content: message,
            });

            console.log('Ejecutando asistente...');
            const run = await openai.beta.threads.runs.create(thread.id, {
                assistant_id: assistantId, // Reemplaza con el ID de tu asistente
                instructions: "Responde como un psicólogo profesional, ofreciendo apoyo y consejo."
            });

            console.log('Recuperando estado de ejecución...');
            const runStatus = await openai.beta.threads.runs.retrieve(thread.id, run.id);
            if (runStatus.status === "completed") {
                console.log('Listando mensajes del hilo...');
                const messagesResponse = await openai.beta.threads.messages.list(thread.id);
                messagesResponse.data.forEach((msg) => {
                    if (msg.role === "assistant") {
                        const updatedMessages = [...newMessages, { text: msg.content[0].text.value, sender: 'assistant' }];
                        setMessages(updatedMessages);
                        AsyncStorage.setItem('chat_messages', JSON.stringify(updatedMessages));
                    }
                });
            }
        } catch (error) {
            console.error("Error al obtener respuesta:", error);
        }
    } else {
        console.log('Mensaje vacío o solo espacios. No se envía.');
    }
};


                                                                                                                                                                                In my package json: "openai": "^4.17.4"

latest is 17.5 and this is the latest test code for Node.js if you can give that a try

import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: 'My API Key', // defaults to process.env["OPENAI_API_KEY"]
});

async function main() {
  const chatCompletion = await openai.chat.completions.create({
    messages: [{ role: 'user', content: 'Say this is a test' }],
    model: 'gpt-3.5-turbo',
  });
}

main();

Chat completions is working excellent, but the gpt asistant is not working with the same api key. When i tried to first create te asistant Im having the 401 issue. I will try 17.5, but I doubt thats the problem const assistant = await openai.beta.assistants.create({
name: “Psicólogo Virtual”,
instructions: “Eres un psicólogo profesional. Brindas apoyo, contención y nuevas perspectivas a distintas situaciones. Realizas preguntas introspectivas y mantienes una conversación empática y reflexiva.”,
model: “gpt-4-1106-preview”
});

Is your account a paid one? i.e. have you made a payment to your API account at all?

Yes off course, I have 5 usd in credits and it works normally with other functions

so you have topped your account up with $5 or is that $5 the initial free grant? If you have not paid $5 in credit then I think that’s why.

Yes i paid it with credit card, and im currently using the api key in chat completions and works perfectly.But when i use the same apiKey in gpt assistant it gives me a 401.So im not sure whats happening, it doesnt have any sense

Do you have access to the assistant feature in the playground? (Here’s the link so you can check for yourself)

can you try replacing this part in your code with the one from the example, just as a test please.

Yes playground works perfectly good. Im really sure that is a problem with the library and not the api key

But you give me an example of completions, and im tryng to use assistants, completions its working perfectly fine

Yes, just the API key setting part

const API_KEY = Constants.expoConfig.extra.openaiApiKey; // Asegúrate de usar tu clave API de OpenAI

import OpenAI from ‘openai’;

const openai = new OpenAI({

apiKey: API_KEY, // defaults to process.env[“OPENAI_API_KEY”]

});

Done and im having same issue

OK, can you please try from the playground OpenAI Platform

Play ground works perfectly great, the issue is when im tryng to incorporate to my app with the api

The assistant API is a bit different than the completions one, there’s more documentation over here:

Yeah i read the documentation like 100 times, if you see the code is perfecty according to the docs, but It doesnt let me make the first step that is create an assistante because of error 401. I already checked the api key and its fine and also im using the same api key in other part of the app that uses completions and also works perfectly fine. So the issue 401 doesnt have any sense

Alright,
Error 401 mean that it’s unauthorized, so it’s either your key or that you don’t have access to the model.
Try replacing this:

model: "gpt-4-1106-preview"

With this:

1 Like