ChatGPT has gone viral recently, and it seems like countless companies have integrated the OpenAI chat into their websites. As a developer, it could be a very useful skill to understand how exactly this gets done. This tutorial walks through how to achieve ChatGPT integration with a Node.js backend.
Set up a Node.js Project
If you don't already have a Node.js project, create a new directory for your project and initialize it with npm:
mkdir chatgpt-integration cd chatgpt-integration npm init -yInstall Dependencies
You will need some npm packages to make HTTP requests and handle the API communication. Install express, axios, and any other necessary dependencies:
npm install express axiosCreate an OpenAI Account
If you haven't already, sign up for an account with OpenAI and create an API key. You'll need this key to authenticate your requests.
Set Up Environment Variables
Create a.env file in your project root to store your OpenAI API key and the name of the model you want to use. Choose a current model from OpenAI's model list, because older models are retired over time. It should look something like this:
OPENAI_API_KEY=your-api-key-here
OPENAI_MODEL=model-name-from-openais-model-listEnsure you never commit this file to a public repository, as it contains sensitive information.
Create an Express Server
Create a basic Express server in your project. Create a file named server.js and add the following code:
const express = require('express');
const axios = require('axios');
require('dotenv').config(); // Load environment variables
const app = express();
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const OPENAI_MODEL = process.env.OPENAI_MODEL;
app.use(express.json());
// Define a route for sending a message to ChatGPT
app.post('/chat', async (req, res) => {
const message = req.body.message;
try {
const response = await axios.post(
'https://api.openai.com/v1/chat/completions',
{
model: OPENAI_MODEL,
messages: [{ role: 'user', content: message }],
},
{
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${OPENAI_API_KEY}`,
},
}
);
res.json({ reply: response.data.choices[0].message.content });
} catch (error) {
console.error(error.message);
res.status(500).json({ error: 'An error occurred' });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});Make API Requests
You can now send a POST request to your /chat endpoint with a message as the request body to get a response from ChatGPT. You can use a tool like axios or fetch in your frontend to make these requests.
Run Your Server
Start your Node.js server:
node server.jsYour server should now be running and listening for incoming requests.
Test Your ChatGPT Integration
Use a tool like curl or Postman, or write a simple frontend application to make POST requests to your /chat endpoint with messages.
That's it! You've now integrated ChatGPT into your Node.js backend. Remember to handle any error cases, customize the API call parameters as needed, and secure your API key. Additionally, consider adding input validation and error handling for better robustness in a production environment.
