You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase函数调用OpenAI报错:openai.createCompletion is not a function

问题解决:OpenAI v4.x在Firebase函数中调用createCompletion报错

问题背景

Firebase定时函数需每分钟生成挑战并存入Firestore,使用OpenAI v4.26.0调用API时触发错误:openai.createCompletion is not a function。

原函数代码:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const OpenAI = require("openai");

admin.initializeApp();

const openai = new OpenAI({
  apiKey: functions.config().openai.key,
});

exports.generateDailyChallenge = functions.pubsub.schedule("* * * * *")
    .onRun(async (context) => {
      try {
        const response = await openai.createCompletion({
          model: "text-davinci-003",
          prompt: "You are an AI model powering a social media app based " +
                "around challenges. The app works in a similar way to " +
                "BeReal, meaning that once a day it generates a challenge " +
                "for the users. The challenge needs to be simple to " +
                "complete and require just a single photo taken from both " +
                "cameras, just keep this in mind, but don't mention it as " +
                "the users are used to it. The challenge is supposed to be " +
                "fun, but easy to complete so users don't have to spend " +
                "too much time on it. The goal is to connect with your " +
                "online friends in a fun and engaging way. Mainly to just " +
                "see what they were up to at that specific moment. Give me " +
                "just the challenge name and a brief description of the " +
                "challenge as if you were challenging a user to do it",
          max_tokens: 150,
        });

        const challengeText = response.data.choices[0].text.trim();
        console.log("Generated Challenge:", challengeText);

        const db = admin.firestore();
        await db.collection("challenges").add({
          text: challengeText,
          createdAt: admin.firestore.FieldValue.serverTimestamp(),
        });
      } catch (error) {
        console.error("Error generating or saving challenge:", error.message);
      }
    });

错误日志

{
  "textPayload": "Error generating or saving challenge: openai.createCompletion is not a function",
  "insertId": "65b7b5f100015b11309c47bd",
  "resource": {
    "type": "cloud_function",
    "labels": {
      "project_id": "nocena-dea56",
      "function_name": "generateDailyChallenge",
      "region": "us-central1"
    }
  },
  "timestamp": "2024-01-29T14:28:01.088849Z",
  "labels": {
    "runtime_version": "nodejs16_20240121_16_20_2_RC00",
    "instance_id": "0087599d42bd678f896459629280089ca75acae30403ae873cd7bb1e45f4fe7e158e416746bfcd7cebb55af5ab4abe7bf80c2b4277d2d0d089ec3f3e043ca6018f63",
    "execution_id": "lzchc47te50n"
  },
  "logName": "projects/nocena-dea56/logs/cloudfunctions.googleapis.com%2Fcloud-functions",
  "trace": "projects/nocena-dea56/traces/8bff527e9d2bcf302a301c3630917ee8",
  "receiveTimestamp": "2024-01-29T14:28:01.426853583Z"
}

解决方法

OpenAI v4.x重构了SDK的API结构,原v3.x的createCompletion方法被移到openai.completions.create,同时响应数据结构也简化了,无需再取data属性。

修改后的核心代码片段:

// 替换原createCompletion调用
const response = await openai.completions.create({
  model: "text-davinci-003",
  prompt: "...", // 原prompt内容不变
  max_tokens: 150,
});

// 调整响应取值方式
const challengeText = response.choices[0].text.trim();

完整修改后的函数代码:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const OpenAI = require("openai");

admin.initializeApp();

const openai = new OpenAI({
  apiKey: functions.config().openai.key,
});

exports.generateDailyChallenge = functions.pubsub.schedule("* * * * *")
    .onRun(async (context) => {
      try {
        const response = await openai.completions.create({
          model: "text-davinci-003",
          prompt: "You are an AI model powering a social media app based " +
                "around challenges. The app works in a similar way to " +
                "BeReal, meaning that once a day it generates a challenge " +
                "for the users. The challenge needs to be simple to " +
                "complete and require just a single photo taken from both " +
                "cameras, just keep this in mind, but don't mention it as " +
                "the users are used to it. The challenge is supposed to be " +
                "fun, but easy to complete so users don't have to spend " +
                "too much time on it. The goal is to connect with your " +
                "online friends in a fun and engaging way. Mainly to just " +
                "see what they were up to at that specific moment. Give me " +
                "just the challenge name and a brief description of the " +
                "challenge as if you were challenging a user to do it",
          max_tokens: 150,
        });

        const challengeText = response.choices[0].text.trim();
        console.log("Generated Challenge:", challengeText);

        const db = admin.firestore();
        await db.collection("challenges").add({
          text: challengeText,
          createdAt: admin.firestore.FieldValue.serverTimestamp(),
        });
      } catch (error) {
        console.error("Error generating or saving challenge:", error.message);
      }
    });

替代AI工具推荐

  • Google Gemini API:与Firebase生态深度兼容,Node.js SDK调用方式简洁,支持多模态文本生成
  • Anthropic Claude API:擅长生成自然流畅的对话式文本,适合挑战类内容创作,有完善的Node.js SDK
  • Cohere API:专注于文本生成与语义理解,集成门槛低,适合批量生成标准化内容

内容的提问来源于stack exchange,提问作者Louskac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 08:32:33