node.jsopenai-api

Got an error when I tried to use the Openai SDK in Node.js


I am trying to use Openai api with nodejs, I follow the tutorial and want to add a simple gpt text completion feauture using the openai SDK, but I got an error says: /node_modules/openai/core.js:44 const isJSON = contentType?.includes('application/json') || contentType?.includes('application/vnd.api+json');

It results in a crash of the app, I didn't find out why.

This is the code:

import OpenAI from 'openai';

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

export const gptResponse = async (req, res) => {
    try {
        const { message } = req.body;
        const getResponse = await openai.chat.completions.create({
            model: 'gpt-3.5-turbo',
            messages: [
                {
                    role: 'system',
                    content: 'You are a helpful assistant.',
                },
                {
                    role: 'user',
                    content: message,
                },
            ],
        });
        console.log(getResponse.data.choices[0].message.content);
        return res.json(getResponse.data.choices[0].message.content);
    } catch (err) {
        console.log(err);
        return res.status(400).send('Error. Try again.');
    }
};

Solution

  • This code will work.

    Save as `demo.js'

    import OpenAI from 'openai';
    
    const openai = new OpenAI({
        apiKey: process.env.OPENAI_API_KEY,
    });
    
    const requestData = {
        model: 'gpt-3.5-turbo',
        messages: [
            {
                role: 'system',
                content: 'You are a helpful assistant.',
            },
            {
                role: 'user',
                content: 'Hello!',
            },
        ],
    };
    
    async function getGPTResponse() {
        try {
            const response = await openai.chat.completions.create(requestData);
            console.log("Response from OpenAI:", response.choices[0].message.content);
        } catch (error) {
            console.error("Error:", error.message);
        }
    }
    
    getGPTResponse();
    

    In package.json

    {
      "type": "module",
      "dependencies": {
        "openai": "^4.28.0"
      }
    }
    

    Install dependencies

    npm install
    

    Run it

    node demo.js
    

    Result

    enter image description here

    Confirm by Postman

    You can see the response message's hierarchy

    url

    POST https://api.openai.com/v1/chat/completions
    

    In body

    {
        "model": "gpt-3.5-turbo",
        "messages": [
          {
            "role": "system",
            "content": "You are a helpful assistant."
          },
          {
            "role": "user",
            "content": "Hello!"
          }
        ]
      }
    

    enter image description here

    enter image description here


    insufficient permissions cases

    #1 Read Only API_KEY

    enter image description here

    Error

    Error: 401 You have insufficient permissions for this operation. Missing scopes: model.request
    

    enter image description here

    #2 Model capabilities Write API_KEY

    enter image description here

    No Error enter image description here

    #3 All Permissions API_KEY

    enter image description here

    No Error enter image description here