In this tutorial, we’ll build a Node.js API and integrate it with OpenAI’s API to enable AI interactions. You’ll also learn best practices and how to customize the responses.
To begin, we need to organize our project. Open your terminal and run the following commands to create a folder named my-server
and move inside it:
mkdir my-server cd my-server
This will help keep all the project files in one place.
Now, initialize the Node.js project with the following command:
npm init -y
This will generate a package.json
file with the default configuration. This file is essential for keeping track of dependencies and scripts for your project.
Next, we install some essential dependencies for our server:
npm install express dotenv cors
It’s a good practice to keep sensitive configurations out of the source code. Create a .env
file in the root directory of the project:
touch .env
Inside the .env
file, define the port for your server:
PORT=8080
Remember not to share this file if it contains sensitive information, such as API keys.
package.json
to Use ES6 ModulesTo use modern JavaScript syntax (import/export), add the following line to your package.json
:
{ "type": "module", "scripts": { "start": "node index.js" } }
This will allow the use of ES6 syntax in your project.
Now, create the main file for the server. This file will contain the server’s code:
touch index.js
In index.js
, start by importing the necessary dependencies:
import express from 'express'; import { config } from 'dotenv'; import cors from 'cors';
express
: To create the server.dotenv
: To load environment variables.cors
: To enable CORS in the application.Next, initialize dotenv to access the environment variables:
config();
Now, configure Express and set the port where the server will run:
const app = express(); const port = process.env.PORT || 8080;
Add middleware to enable CORS and handle JSON requests:
app.use(cors()); app.use(express.json());
Define a GET route that responds with a simple message to verify that the server is working properly:
app.get('/api/chat', async (req, res) => { res.json('The server is running'); });
Finally, make the application listen on the configured port:
app.listen(port, () => { console.log(`The server is running on port ${port}`); });
To start the server, go back to the terminal and run the following command:
npm start
You should see the message: The server is running on port 8080
in the console.
Open your browser and navigate to the following address to test that the server is working:
http://localhost:8080/api/chat
You should see the message: "The server is running"
.
To add artificial intelligence functionality, install OpenAI’s official package:
npm install openai
Import OpenAI into your project and configure it with the API key found in your .env
file:
import OpenAI from 'openai'; const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, });
Make sure to add your OpenAI API key in the .env
file:
OPENAI_API_KEY=your_api_key_here
Modify the /api/chat
route to send requests to OpenAI and return responses generated by the model:
app.post('/api/chat', async (req, res) => { try { const { messages } = req.body; const completion = await openai.chat.completions.create({ model: 'gpt-3.5-turbo', messages: [{ role: 'system', content: 'You are a helpful assistant.' }, ...messages], }); res.json(completion.choices[0].message); } catch (error) { res.status(500).send('Error generating the response.'); } });
By following these steps, you will have created a basic server with Node.js and Express, and integrated it with the OpenAI API to generate automatic responses. Congratulations!
Subscribe to our Newsletter
To receive news, updates, code challenges, tech trends
© 2024 Codding Nutella. All rights reserved.