0

I'm working on integrating the OpenAI API with a Firebase project and encountering an issue when trying to hardcode the OpenAI API key or using functions.config().openai.key in a backend scheduled function. The function fails with an error stating that the OPENAI_API_KEY environment variable is missing or empty, despite the key being hardcoded.

Here's the relevant part of my code:

.runtimeconfig file:

{
  "openai": {
    "key": "secret-openai-api-key"
  },
  "mongodb": {
    "uri": "secret-mongo-uri"
  }
}

import OpenAI from "openai";

export const generateTextWithOpenAI = async (prompt: string): Promise<string> => {
  try {
    const openai = new OpenAI({
      apiKey: "My-hard-coded-api-key",
    });

    console.log("Starting request to openai API...");
    const chatCompletion = await openai.chat.completions.create({
      messages: [
        {
          role: "user",
          content: prompt,
        },
      ],
      model: "gpt-3.5-turbo",
    });

    return chatCompletion.choices[0].message.content ? chatCompletion.choices[0].message.content : "";
  } catch (error) {
    console.error("Error in generateTextWithOpenAI:", error);
    throw error;
  }
};

The error I get is as follows:

Error in generateTextWithOpenAI: OpenAIError: The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).

Strangely, when I use the API key from Firebase environment configuration in an endpoint it works fine in local testing but in production it gives me the same error as above.

openaiRouter.post("/generate-text", async (req, res) => {
  const prompt = req.body.prompt;
  // Retrieves the API key here
  const openaiApiKey = functions.config().openai.key;
  const openai = new OpenAI(openaiApiKey);

  try {
    console.log("Starting request to openai API...");
    const chatCompletion = await openai.chat.completions.create({
      messages: [
        {
          role: "user",
          content: prompt,
        },
      ],
      model: "gpt-3.5-turbo",
    });

    res.status(200).json(chatCompletion.choices[0].message.content);
  } catch (error) {
    errorResponse(error, res);
  }
});

I've checked the API key multiple times for accuracy and can confirm it is correct. Any ideas on what might be causing this issue or how to resolve it?

1 Answer 1

1

If this is a v2 function and on a newer version of the Firebase SDKs, functions.config() is no longer a thing. You have to use .env or secrets. The error even when hardcoding it's the same issue - Firebase is looking for the env or secret and not finding it, and that's before it runs your specific hardcoded function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.