Home  >  Article  >  Web Front-end  >  How to Integrate the ChatGPT API with Node.js

How to Integrate the ChatGPT API with Node.js

王林
王林Original
2024-08-13 06:41:41298browse

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 the .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 functionality 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.

The above is the detailed content of How to Integrate the ChatGPT API with Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn