Use OpenAI with Node.js
Asim Hafeez
Senior Software Engineer | Lead | AI | LLMs | System Design | Blockchain | AWS
In this article, we’ll explore how to build a simple yet powerful chatbot using Node.js and the OpenAI API. This project demonstrates the integration of natural language processing capabilities into a Node.js application, providing a base for more complex conversational agents.
Prerequisites
To follow along with this tutorial, you should have a basic understanding of JavaScript and Node.js. You will also need Node.js installed on your computer. Also, you will need an API key from OpenAI, which you can get by creating an account on their OpenAI Platform.
Setting Up Your Project
First, create a new directory for your project and initialize it with npm:
mkdir node-with-openai
cd node-with-openai
npm init -y
Next, install the necessary packages:
npm install openai dotenv
Let’s Start building the Chatbot
The chatbot will interact with users through the command line using Node.js’s readline module and communicate with OpenAI’s GPT model to process and respond to user inputs.
1. Setting Up the Chatbot Interface using?Readline
To get started, create a new file named chatbot.js. This file will house the essential code for your chatbot’s interface. Begin by importing the necessary modules and setting up the readline interface.?
import readline from 'node:readline';
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
With this setup, your chatbot is ready to handle inputs and outputs directly through the command line, making interaction with users possible.
2. OpenAI Integration
Create a file named openai.js that handles communication with the OpenAI API. You would typically require an API key and set up a client as shown below (not included in this tutorial):
import { configDotenv } from 'dotenv'
configDotenv()
import OpenAI from 'openai'
export const openai = new OpenAI(process.env.OPENAI_API_KEY)
3. Building the Chat Logic
Now, let’s define the core functions that will handle the chat logic:
const newMessage = async (history, message) => {
const results = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [...history, message],
});
return results.choices[0].message;
}
const formatMessage = (userInput) => ({ role: 'user', content: userInput });
These functions are responsible for sending user messages to the OpenAI API and receiving the AI’s responses, maintaining the conversation context with a history of messages.
领英推荐
4. Start the main Chat function
The chat function is the central coordinator for managing user interactions in our Node.js chatbot application.
The chat function manages the conversation flow between the user and the AI. It starts with a system message that sets the context and then uses a loop to prompt the user for input continuously. User inputs are sent to the OpenAI API for responses, which are then displayed.
The chat continues until the user types ‘stop’, with each interaction recorded to keep the conversation contextually relevant. This setup ensures an ongoing, responsive dialogue with the AI.
First, let’s initialize the chat history with a predefined message for LLM.
const history = [{
role: 'system',
content: 'You are an AI assistant. Answer questions properly!',
}];
Recursive start Function:
const start = async () => {
rl.question('You: ', async (userInput) => {
if (userInput.toLowerCase() === 'stop') {
rl.close();
return;
}
const message = formatMessage(userInput);
const response = await newMessage(history, message);
history.push(message, response);
console.log(`\nChatbot: ${response.content}\n`);
start();
});
This section sets up an initial system message, takes user inputs, and processes them continuously until the user decides to exit the chat by typing ‘stop’.
5. Running Your Chatbot
To run your chatbot, simply execute the following command in your terminal:
node chatbot.js
You will see a prompt where you can start interacting with your AI chatbot.
Here is the final chat app working in the terminal,
Conclusion
Building a chatbot with Node.js and OpenAI is simple yet full of exciting possibilities, opening the door to a wide range of creative and powerful applications. By understanding and utilizing the OpenAI API, developers can implement sophisticated AI-driven interactions tailored to various needs, from simple Q&A bots to complex conversational agents for enterprise solutions.
This tutorial provides a foundational knowledge base to inspire and facilitate further exploration into the burgeoning field of artificial intelligence.
If you found the article helpful, don’t forget to share the knowledge with more people! ??