Firebase函数配置OpenAI API密钥(硬编码/.runtimeconfig)报错求助
问题概述
将OpenAI API集成到Firebase项目时,后端定时函数中无论硬编码OpenAI API密钥,还是使用functions.config().openai.key读取配置,均报错提示OPENAI_API_KEY环境变量缺失或为空。另外,接口中使用Firebase环境配置密钥时,本地测试正常,但生产环境出现相同报错,已确认API密钥本身准确无误。
相关代码
.runtimeconfig文件(本地测试用)
{ "openai": { "key": "secret-openai-api-key" }, "mongodb": { "uri": "secret-mongo-uri" } }
定时函数中的OpenAI调用代码
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; } };
接口中的OpenAI调用代码
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); } });
报错信息
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' }).
原因分析与解决方法
1. OpenAI客户端初始化参数错误
接口代码中new OpenAI(openaiApiKey)的写法错误,OpenAI Node.js SDK的构造函数需要传入配置对象,而非直接传入密钥字符串。正确写法应为:
const openai = new OpenAI({ apiKey: openaiApiKey });
本地测试可能因环境变量中存在OPENAI_API_KEY而掩盖了这个错误,生产环境无该环境变量时就会触发报错。
2. 生产环境未同步配置
本地的.runtimeconfig文件仅对Firebase本地模拟器生效,生产环境需要通过命令行手动设置配置:
firebase functions:config:set openai.key="your-real-openai-api-key"
设置完成后,重新部署函数:
firebase deploy --only functions
可通过以下命令验证生产环境配置是否正确:
firebase functions:config:get
3. 硬编码密钥未生效
如果硬编码密钥后仍报错,需确认:
- 修改后的代码已重新部署到生产环境,避免部署的是旧代码
- 检查是否有代码逻辑覆盖了硬编码的密钥(如后续读取了环境变量)
4. 环境变量优先级冲突
OpenAI客户端会优先读取系统环境变量OPENAI_API_KEY,如果生产环境中该变量存在但为空值,会覆盖代码中配置的密钥。可通过Firebase函数的环境变量管理,确认未设置空的OPENAI_API_KEY。
内容的提问来源于stack exchange,提问作者TedRed

