ChatGPT NodeJS: Quick Guide and Code Snippets

Introduction

Want to integrate artificial intelligence into your Node.js project? With OpenAI’s ChatGPT API, you can create chatbots, virtual assistants, and code generators in just a few steps. In this guide, we will cover how to set up the project and use ChatGPT NodeJS, from basic examples to advanced features like Text-to-Speech, Vision, and Image Generation. Let’s get started!

What We Will Cover:

  1. How to set up your Node.js project and get an API key.
  2. Practical examples for common use cases.
  3. Advanced capabilities for Vision, Audio, and Image Generation.

1. Setting Up the Project and Getting an API Key

1.1 Create an OpenAI Project and Get an API Key

  1. Go to https://platform.openai.com/welcome?step=create and follow the steps to get your API key.
  2. The process is simple and guided. You will need to:
    • Create an account (if you don’t already have one).
    • Set up a payment method if required.
    • Generate your API key.

1.2 Create the Project, Install Packages, and Configure apiClient.js

In this section, I will guide you step by step to create a Node.js project, install the necessary packages, and configure the apiClient.js file to manage requests to OpenAI’s API.

Create the Node.js Project

  1. Open your terminal and create a new directory for your project:
    mkdir chatgpt-node && cd chatgpt-node
  2. Initialize a new Node.js project:
    npm init -y
    This will create a package.json file with default settings.

Install Necessary Packages

To use OpenAI and manage environment variables, install the following packages:

npm install openai dotenv

Project Structure:

chatgpt-node/
β”œβ”€β”€ .env                # Environment variables file
β”œβ”€β”€ package.json        # Node.js project configuration file
β”œβ”€β”€ main.js             # Main project file
└── utils/
    └── apiClient.js    # File to configure and manage OpenAI API requests

apiClient.js:

Here is the content of the apiClient.js file:

const { OpenAI } = require('openai');
require('dotenv').config();

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

module.exports = openai;

Configure the .env File:

Create a .env file in the root of your project and add your API key:

OPENAI_API_KEY=your_api_key

2. Main Examples: chat.completions.create

This section shows how to use chat.completions.create, the core functionality of ChatGPT APIs, to build chatbots and assist in various contexts.

1. Basic Example (Simple Chat)

This example demonstrates how to send a simple prompt and receive a direct response from ChatGPT.

const openai = require('./utils/apiClient');  // Import centralized OpenAI configuration

async function basicChat(prompt) {
  try {
    const response = await openai.chat.completions.create({
      model: "gpt-4o",
      messages: [{ role: "user", content: prompt }],
      max_tokens: 200,
    });

    console.log("Response:", response.choices[0].message.content);
  } catch (error) {
    console.error("Error:", error);
  }
}

basicChat("What is Node.js?");

2. Automatic Translation

Use ChatGPT to quickly and accurately translate text into different languages.

async function translateText(text, targetLanguage) {
  try {
    const response = await openai.chat.completions.create({
      model: "gpt-4o",
      messages: [
        { role: "system", content: "You are an expert translator. Translate the following text into the requested language." },
        { role: "user", content: `Translate this text into ${targetLanguage}: ${text}` }
      ],
      max_tokens: 200,
    });

    console.log(`Translation (${targetLanguage}):`, response.choices[0].message.content);
  } catch (error) {
    console.error("Error:", error);
  }
}

translateText("Hello, how are you?", "Italian");

3. Sentiment Analysis

Analyze the emotional tone of a text to determine if it is positive, negative, or neutral.

async function analyzeSentiment(text) {
  try {
    const response = await openai.chat.completions.create({
      model: "gpt-4o",
      messages: [
        { role: "system", content: "Analyze the sentiment of the following text." },
        { role: "user", content: `Analyze the sentiment of this text: ${text}` }
      ],
      max_tokens: 100,
    });

    console.log("Sentiment:", response.choices[0].message.content);
  } catch (error) {
    console.error("Error:", error);
  }
}

analyzeSentiment("Today was a wonderful day, and I feel really happy!");

4. Automatic Code Generator

ChatGPT can help you write code and provide detailed explanations.

async function generateCode(prompt) {
  try {
    const response = await openai.chat.completions.create({
      model: "gpt-4o",
      messages: [
        { role: "system", content: "You are a coding assistant. Provide working code and clear explanations." },
        { role: "user", content: prompt }
      ],
      max_tokens: 500,
    });

    console.log("Generated Code:", response.choices[0].message.content);
  } catch (error) {
    console.error("Error:", error);
  }
}

generateCode("Write a Node.js function to read a JSON file and return an object.");

3. Advanced Capabilities

OpenAI’s advanced capabilities unlock endless possibilities, such as image analysis, content generation, and advanced audio management for more interactive and engaging experiences. Here are some examples:


1. Audio Generation (Text-to-Speech)

Convert text into an audio file using OpenAI’s Text-to-Speech API.

const fs = require('fs');
const path = require('path');

const openai = require('./utils/apiClient');
const speechFile = path.resolve('./speech.mp3');

async function textToSpeech(text) {
  try {
    const response = await openai.audio.speech.create({
      model: 'tts-1',
      voice: 'alloy',
      input: text,
    });

    const buffer = Buffer.from(await response.arrayBuffer());
    await fs.promises.writeFile(speechFile, buffer);
    console.log('Audio generated:', speechFile);
  } catch (error) {
    console.error('Error generating audio:', error);
  }
}

textToSpeech('Today is a wonderful day to build something people love!');

2. Vision (Image Analysis)

Analyze images and obtain detailed descriptions of their content.

const openai = require('./utils/apiClient');

async function analyzeImage(imageUrl) {
  try {
    const response = await openai.chat.completions.create({
        model: "gpt-4o-mini",
        messages: [
          {
            role: "user",
            content: [
              { type: "text", text: "What is in this image?" },
              {
                type: "image_url",
                image_url: {
                  "url": imageUrl,
                },
              },
            ],
          },
        ],
        store: true,
      });
    console.log('Image description:', response.choices[0]);
  } catch (error) {
    console.error('Error analyzing image:', error);
  }
}

analyzeImage("https://upload.wikimedia.org/wikipedia/commons/thumb/7/79/Winterswijk_%28NL%29%2C_Woold%2C_Boven_Slinge_--_2014_--_3170.jpg/1125px-Winterswijk_%28NL%29%2C_Woold%2C_Boven_Slinge_--_2014_--_3170.jpg");

3. Image Generation

Generate images from textual descriptions, ideal for creative content.

const openai = require('./utils/apiClient');

async function generateImage(prompt) {
  try {
    const response = await openai.images.generate({
      prompt: prompt,
      n: 1,
      size: '1024x1024'
    });
    console.log('Image URL:', response.data[0].url);
  } catch (error) {
    console.error('Error generating image:', error);
  }
}

generateImage('A cat flying through space wearing sunglasses.');

Conclusion

This guide provides an overview of ChatGPT APIs in Node.js, covering main examples (chat.completions.create) and advanced capabilities like Vision, Text-to-Speech, and Image Generation. If you want to explore these features further, check out the official documentation in the additional resources below.

Additional Resources


Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top