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.
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
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á?');
To run the code, run the command:
node index.js
If everything is configured correctly, you will see the ChatGPT response in the console.
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);
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!