Failing to upgrade the OpenAI Node.js SDK from v3 to v4

81 Views Asked by At

I'm trying to update my app from Angular 15 and "openai": "^3.2.1" to Angular 17 and "openai": ^4.24.1".

I cannot understand what is missing. No errors occurred.

Followed links:

  1. https://platform.openai.com/docs/guides/text-generation/completions-api

  2. https://github.com/openai/openai-node/discussions/217

  3. OpenAI API error: "The model `text-davinci-003` has been deprecated"

  4. OpenAI ChatGPT (GPT-3.5) API error: "This is a chat model and not supported in the v1/completions endpoint"

Old version:

import { Configuration, OpenAIApi } from 'openai';
  readonly configuration = new Configuration({
    organization: environment.openAIOrganization,
    apiKey: environment.openAIToken,
  });


  readonly openai = new OpenAIApi(this.configuration);

  //#region -- GENERATE CHATGPT MSG --
  async getDataFromOpenAI(text: string): Promise<any> {
    try {
      const completion = await this.openai.createCompletion({
        model: "text-davinci-003",
        prompt: text,
        temperature: 0.9,
        max_tokens: 62,
      },
        {
          headers: {
            'Content-Type': 'application/json',
            //'baseOptions': 'User-Agent',
            'Authorization': 'Bearer ' + environment.openAIToken,
            'Access-Control-Allow-Origin': '*'
          }
        })

      return completion.data.choices[0].text
    }
    catch (error) {
      console.error('error.message', error);
    }
  }
  //#endregion

New version:

import OpenAI from 'openai';



 async generateSms() {
    try {
      let completion = await this.openai.completions.create({
        model: 'gpt-3.5-turbo-instruct',
        prompt: 'Create a happy birthday message',
        temperature: 0.5,
      });
      console.log(completion);
      console.log(completion.choices[0].text);
    } catch (e) {
      console.error('generateSms => ', e);      
    }
  } 
  

I created a new key but is only returning [null]

Last used in API KEY is updating: last used 12/jan

enter image description here

1

There are 1 best solutions below

3
Rok Benko On

The initialization is different with the OpenAI Node.js SDK v4 than with v3.

If you're using the OpenAI Node.js SDK v4, then the following is the correct initialization:

const OpenAI = require("openai");

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

You did the completion part correctly, as follows:

let completion = await this.openai.completions.create({
    model: "gpt-3.5-turbo-instruct",
    prompt: "Say this is a test.",
});