CloudFlare Pages: POST https://api.openai.com/v1/completions Getting 401

Hi, I just deployed my openai js project to cloudflare but openai completions gettin 401 error:

Can you please share the relevant call to OpenAI in your code, with the parameters?

401 error generally means missing or invalid API Key. I’d start investigating there.

Yeah here:

import { Configuration, OpenAIApi } from "openai";

const configuration = new Configuration({

organization: "org-8sBBKnnzpa0m1QQdIgYJtvhS",

apiKey: process.env.OPENAI_API_KEY,

});

delete configuration.baseOptions.headers["User-Agent"];

const openai = new OpenAIApi(configuration);
const response = await openai.createCompletion({
    model: "text-davinci-003",
    prompt: `Generate a short message ${outline}` ,
    max_tokens: 60
});

and the api key was located in the env.js file.

here is the build settings on cloudflare – I’ve added OPENAI_API_KEY to environment variables.

Yeah, I tried to create new api key but didn’t worked.

Try doing a console log of the api key env variable just to make sure that it’s correct, it’s possible that it went into the build but not into the launching environment for example, depending on the configuration

1 Like

I checked the api key its correct.

What’s the full body response from the API call? It should tell you what the error is

I found the solution, when deploying on github, you must use environment variables, also when deploying to netlify/cloudflare you must use environment variable. Also vite projects api keys must start with VITE_ , on the prject you must call env variables like: import.meta.env.VITE_OPENAI_API_KEY. this way worked for me. Thanks!

1 Like