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?