Firebase OpenAI API error: "openai.createCompletion is not a function"

119 views Asked by At

I am having an issue with running my Firebase function. It needs to generate a challenge once a day (I have it set up to run every minute now for debug) and to save it in my realtime database. This code is like this:

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

admin.initializeApp();

// Create a new instance of the OpenAI API client
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);

        // Save to Firestore
        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);
      }
    });

However when I run it I get this error in a log:

    {
  "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"
}

When I tried debugging it I got told I don’t initialise the function properly. However that is not the case. And I also tried changing the way I initialise it so many time. I am using this to call it: https://www.npmjs.com/package/openai (it is the version 4.26.0), so I should initialise it this way.

If nobody can help me maybe you can recommend me what other ai to use, because at this point I am suspecting it might be just an issue with OpenAI api.

1

There are 1 answers

0
Rok Benko On BEST ANSWER

You have OpenAI Node.js SDK v4 or newer.

There are multiple changes in >=v4 compared to <v4, mainly:

  1. Initialization
  2. Method names
  3. Message retrieval

You did the initialization correctly. There are two problems left, plus one additional problem that is not related to the SDK version.


Problem 1: Incorrect method name

You need to change the method name from this...

openai.createCompletion

...to this.

openai.completions.create

Problem 2: Incorrect message retrieval

Change this...

response.data.choices[0].text

...to this.

response.choices[0].text

Additional problem: Using a deprecated model

Also, the text-davinci-003 has been deprecated. The gpt-3.5-turbo-instruct model is the recommended replacement.