Cloud
How to Build a Simple Application Powered by ChatGPT
OpenAI’s ChatGPT API enables applications to access and integrate ChatGPT, a large language model (LLM) that generates human-like responses to input. Learn how to build a web application that utilizes ChatGPT to generate useful output.
OpenAI developed the large language model (LLM) ChatGPT to generate human-like responses to input. ChatGPT uses Natural Language Processing (NLP) and deep earning algorithms trained on vast amounts of text, making it an excellent tool for conversational artificial intelligence (AI) applications like chatbots.
OpenAI advances AI technology and makes it accessible through various tools and resources. These include their ChatGPT online service as well as APIs to help developers and businesses incorporate AI into their products.
One such API is the ChatGPT API, which enables applications to access and integrate ChatGPT. In this tutorial, you’ll build a web application that connects to OpenAI’s ChatGPT API and utilizes ChatGPT to generate useful output.
Creating your first ChatGPT application
This tutorial demonstrates how ChatGPT creates a chatbot that helps users find new books to read. The bot will ask users about their favorite genres and authors, then generate recommendations based on their responses.
To see the final project, check out the complete project code.
For this tutorial, you’ll need:
- An OpenAI account
- An API key from OpenAI to access the ChatGPT API
- A terminal with Node.js installed
- OpenAI Node.js library installed. Install it by running npm install openai.
- Access to a code editor. This tutorial will use Visual Studio Code.
Note: Keep your API key secret. Don’t expose it in your code or commit it to your version control system.
OpenAI offers a free trial allowing developers to test the ChatGPT API without incurring charges. After this trial period ends, you must sign up for a paid plan to continue using the service.
The ChatGPT API typically sends a message to the API and receives a response back. To generate a response, you must pass the message along with some configuration options to the openai.createChatCompletion method.
This is an example “hello world” application demonstrating the different options:
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
organization: process.env.ORG,
apiKey: process.env.API_KEY,
});
const openai = new OpenAIApi(configuration);
const getResponse = async() => {
const response = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
max_tokens: 30
messages: [{role: "user", content: "Hello world"}]
}).catch((err)=>console.log(err.response));
console.log(response)
}
getResponse()
Here’s a description of the options you passed to the openai.createCompletion method:
- model: The ID of the GPT-3 engine to use
- max_tokens: The maximum number of tokens to use in the response
- messages: The messages the API must create responses for. The ChatGPT API introduction has a full explanation of the role property provided with the message content.
Refer to the OpenAI API documentation for details about all available options.
To create a new Node.js application, open your terminal or command prompt. First, create a new directory called recommend_a_book.
Navigate into the directory and run the following command:
npm init –y
This initializes a default Node.js app.
First, create a simple command line app to allow users to interact with the chatbot. Use the readline module in Node.js to accept input from the user and display output from the ChatGPT API.
Set the API key created earlier as an environment variable. Enter the following command in your terminal:
export API_KEY='<insert API key here>'
Now, replace <insert API key here> with your OpenAI API key.
Add the code for this application to a file called index.js in the root of your project directory. The final index.js should appear as follows:
const { Configuration, OpenAIApi } = require("openai");
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const configuration = new Configuration({
apiKey: process.env.API_KEY,
});
const openai = new OpenAIApi(configuration);
const getResponse = async(genres, authors) => {
const response = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
max_tokens: 150,
messages: [{role: "user", content: `recommend some books for someone who loves the following genres: "${genres}" and the following authors: "${authors}"`}]
}).catch((err)=>console.log(err.response));
return response.data.choices[0].message.content
}
const getGenres = () => {
return new Promise((resolve, reject) => {
rl.question('List your favourite genres with a comma after each (e.g. sci-fi, fantasy..):\n', (answer) => {
resolve(answer)
})})
}
const getAuthors = () => {
return new Promise((resolve, reject) => {
rl.question('List your favourite authors with a comma after each (e.g. phillip k dick, george rr martin..):\n', (answer) => {
resolve(answer)
})
})
}
const run = async() => {
const genres = await getGenres()
const authors = await getAuthors()
rl.close()
console.log(await getResponse(genres, authors))
}
run()
The application asks the user to provide a list of their favorite genres and authors through the getGenres and getAuthors functions. You can then capture their input from the command line and send it to the ChatGPT API:
Then, call the getResponse function interfacing with the ChatGPT API. The getResponse function uses the same createChatCompletion function in the “hello world” example. This time, you’re asking the function to recommend some books based on the genres and authors captured from the users. Then, return the response from the ChatGPT API and log it to the screen for user viewing. Depending on your inputs, the output may look like this:
Now that you created the basic functions and understand how to interface with the ChatAPI, it’s time to create a web front end. The front end will replace your command line prompts and consist of a simple form. The form will have two inputs—one for genres and one for authors—and a button to send the input to the ChatAPI.
First, in the recommand_a_book folder, create a new folder called public and add a file called style.css. Add the following CSS to the file:
body {
font-family: 'Open Sans', sans-serif;
background-color: #f8f8f8;
color: #333;
}
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
background-color: #fff;
border-radius: 5px;
box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.1);
}
input[type='text'] {
padding: 10px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 5px;
width: 100%;
margin-bottom: 20px;
}
input[type='submit'] {
background-color: #007bff;
color: #fff;
border: none;
padding: 10px 20px;
font-size: 16px;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
input[type='submit']:hover {
background-color: #0069d9;
}
.response {
margin-top: 20px;
font-size: 16px;
line-height: 1.5;
}
Now, you must update your code to create the web application. Use the express library to render the form and collect the user’s input.
First, install the express and body-parser dependencies:
npm install -s express body-parser
Then, modify the code to look as follows:
const { Configuration, OpenAIApi } = require("openai");
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 3000;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static('public'));
const configuration = new Configuration({
apiKey: process.env.API_KEY,
});
const openai = new OpenAIApi(configuration);
const headHTML = '<head><link rel="stylesheet" href="/style.css"><title>Book Recommendation App</title></head>'
const getResponse = async(genres, authors) => {
const response = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
max_tokens: 150,
messages: [{role: "user", content: `recommend some books for someone who loves the following genres: "${genres}" and the following authors: "${authors}"`}]
}).catch((err)=>console.log(err.response));
return response
}
app.get('/', (req, res) => {
res.send(`
<html>
${headHTML}
<body>
<h1>Book Recommendation App</h1>
<form method="POST" action="/recommendations">
<label for="genres">Favorite genres (separate with commas):</label>
<input type="text" id="genres" name="genres"><br>
<label for="authors">Favorite authors (separate with commas):</label>
<input type="text" id="authors" name="authors"><br>
<input type="submit" value="Get recommendations">
</form>
</body>
</html>
`);
});
app.post('/recommendations', async (req, res) => {
const genres = req.body.genres;
const authors = req.body.authors;
const response = await getResponse(genres, authors);
console.log(response.data.choices[0].message.content)
const formattedResponse = formatResponse(response, genres, authors)
res.send(formattedResponse);
});
const formatResponse = (response, genres, authors) => {
if(!response || !response.data || !response.data.choices || response.data.choices.length === 0){
return `<html>${headHTML}<body><h1>No response, please try again...</h1></body></html>`
}
const message = response.data.choices[0].message.content.replace(/\n/g,'</p><p>')
return `<html>${headHTML}<body><h1>Recommendations for genres: ${genres} and authors: ${authors}</h1><p>${message}</p></body></html>`
}
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Using the node index.js command, run the code as before. Once it’s running, navigate to http://localhost:3000/. You should see the following web page:
You used the express library to create a simple API with two endpoints. The GET endpoint returns the HTML containing the form you want to display to the user. When the user clicks the button and submits the form, it calls the POST /recommendations endpoint. The recommendations endpoint calls the getResponse function and then returns the response from the ChatGPT API. Finally, it returns and displays the response as HTML for the user.
Now, input some genres and authors into the form and click the Get recommendations button. It may take a few seconds to fetch the response. When using the same genres and authors provided in the command line app, the output may look as follows:
Conclusion
In this tutorial, you learned how to use OpenAI’s ChatGPT API to build a Node.js application that interfaces with OpenAI’s ChatGPT API. You created a simple console front end and a website that accepts user input and returns output from the ChatGPT API.
With little code overhead, ChatGPT drastically simplifies the process of building complex chat-based applications for developers. You can build applications that generate human-like responses to queries in real time, making the ChatGPT API an excellent tool for customer support and chatbots.
With the right use case and application, ChatGPT can be a powerful API for enhancing user experience and engagement.