"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Integrate the ChatGPT API with Node.js

How to Integrate the ChatGPT API with Node.js

Published on 2024-11-09
Browse:206

Como Integrar a API do ChatGPT com Node.js

Integrating the ChatGPT API with Node.js is a powerful way to add natural language processing capabilities to your application. In this post, we'll explore how to set up the integration, from installing the necessary libraries to implementing ChatGPT API calls.

1. Prerequisites

  • Node.js installed on your machine.
  • An OpenAI account and a valid API key.
  • Basic familiarity with JavaScript and Node.js.

2. Installing Dependencies

First, create a new Node.js project and install the necessary dependencies. We will use axios to make HTTP requests and dotenv to manage environment variables.

mkdir chatgpt-nodejs
cd chatgpt-nodejs
npm init -y
npm install axios dotenv

3. Configuring the Project

Within your project directory, create a .env file to store your OpenAI API key:

OPENAI_API_KEY=your-api-key-here

Now, create an index.js file and add the basic code to configure the use of dotenv and axios:

require('dotenv').config();
const axios = require('axios');

const apiKey = process.env.OPENAI_API_KEY;
const apiUrl = 'https://api.openai.com/v1/chat/completions';

async function getChatGPTResponse(prompt) {
    try {
        const response = await axios.post(apiUrl, {
            model: "gpt-4",
            messages: [{ role: "user", content: prompt }],
            max_tokens: 150,
        }, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        const reply = response.data.choices[0].message.content;
        console.log('ChatGPT:', reply);
    } catch (error) {
        console.error('Error fetching response:', error.response ? error.response.data : error.message);
    }
}

getChatGPTResponse('Olá, como você está?');

4. Understanding the Code

  • dotenv: Loads environment variables from .env file.
  • axios: Makes a POST call to the ChatGPT API.
  • apiKey: Stores the API key that is used in the request.
  • apiUrl: ChatGPT API URL.
  • getChatGPTResponse: Asynchronous function that sends the prompt to ChatGPT and displays the response.

5. Running the Code

To run the code, run the command:

node index.js

If everything is configured correctly, you will see the ChatGPT response in the console.

6. Customizing Integration

You can adjust several parameters in the API call, such as the model, the number of response tokens (max_tokens), and even include context messages in the message list. For example:

const conversation = [
    { role: "system", content: "Você é um assistente útil." },
    { role: "user", content: "Me explique o que é uma API." }
];

async function getChatGPTResponse(messages) {
    try {
        const response = await axios.post(apiUrl, {
            model: "gpt-4",
            messages: messages,
            max_tokens: 150,
        }, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        const reply = response.data.choices[0].message.content;
        console.log('ChatGPT:', reply);
    } catch (error) {
        console.error('Error fetching response:', error.response ? error.response.data : error.message);
    }
}

getChatGPTResponse(conversation);

7. Conclusion

Integrating the ChatGPT API with Node.js is a relatively simple task that can add advanced AI capabilities to your application. With the flexibility of the API, you can create everything from conversational assistants to complex natural language processing systems.

Try different prompts and settings to see how ChatGPT can adapt to your specific needs!


This is a basic example to start the integration. As you become more familiar with the API, you can explore more advanced features, such as fine-tuning models and using more complex conversational contexts.

Release Statement This article is reproduced at: https://dev.to/lucaspereiradesouzat/como-integrar-a-api-do-chatgpt-com-nodejs-4g7l?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3