Integrating ChatGPT with JavaScript: A Simple Chat Application

Ayushmaan Srivastav
3 min readOct 17, 2024

--

Introduction

In the world of web development, integrating artificial intelligence can significantly enhance user experience. In this blog, we will learn how to connect JavaScript with OpenAI’s ChatGPT API, allowing users to interact with the model in a chat-like interface. This simple application will enable users to send messages and receive responses in real time.

Prerequisites

Before we dive into the implementation, ensure you have the following:

  • A basic understanding of HTML and JavaScript.
  • An API key from OpenAI to access the ChatGPT model.

Step 1: Obtaining Your API Key

  1. Sign Up / Log In: Visit the OpenAI website and create an account if you don’t have one.
  2. Get Your API Key: Navigate to the API section in your OpenAI account and generate your API key. Remember to keep this key confidential.

Step 2: Setting Up Your Project

Create a new directory for your project, and within that directory, create two files: index.html and app.js.

Step 3: Creating the HTML Structure

Let’s set up the basic HTML structure. In the index.html file, we will create a user interface that includes a text area for user input, a send button, and a display area for responses.

HTML Code (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ChatGPT Integration</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
#chat-container {
margin-top: 20px;
}
#response {
margin-top: 10px;
border: 1px solid #ccc;
padding: 10px;
min-height: 50px;
}
</style>
</head>
<body>

<h1>Chat with ChatGPT</h1>
<textarea id="user-input" rows="4" cols="50" placeholder="Type your message here..."></textarea>
<br>
<button id="send-button">Send</button>

<div id="chat-container">
<h3>Response:</h3>
<div id="response"></div>
</div>

<script src="app.js"></script>
</body>
</html>

Step 4: Implementing JavaScript Functionality

Next, let’s implement the JavaScript code to handle user input and interact with the ChatGPT API. Create the app.js file with the following code:

JavaScript Code (app.js)

const apiKey = 'YOUR_API_KEY'; // Replace with your actual API key
const sendButton = document.getElementById('send-button');
const userInput = document.getElementById('user-input');
const responseDiv = document.getElementById('response');

sendButton.addEventListener('click', async () => {
const userMessage = userInput.value;
if (!userMessage) return;

responseDiv.innerHTML = "Loading..."; // Show loading message

try {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: userMessage }]
})
});

const data = await response.json();
const botReply = data.choices[0].message.content;
responseDiv.innerHTML = botReply; // Display the bot's response
} catch (error) {
console.error('Error:', error);
responseDiv.innerHTML = "Error occurred while fetching response.";
}
});

Step 5: Running Your Application

  1. Insert Your API Key: Open app.js and replace YOUR_API_KEY with your actual OpenAI API key.
  2. Open index.html: Launch the index.html file in your web browser.
  3. Interact with ChatGPT: Type a message in the text area and click the “Send” button. You should see the response from ChatGPT displayed below.

Step 6: Understanding the Code

  • HTML Structure: We set up a simple user interface with a text area, a button, and a response display area.
  • JavaScript Functionality:
  • We use the Fetch API to send a POST request to the ChatGPT API.
  • The request includes the user’s message, and we receive a response containing the bot’s reply.
  • The bot’s response is then displayed in the designated area on the page.

Security Note

It’s important to mention that exposing your API key in frontend code can be risky. For production applications, consider implementing a backend server to handle API requests and keep your API key secure. You can use technologies like Node.js or Python Flask to create an intermediary server that communicates with OpenAI’s API.

Conclusion

In this blog, we’ve successfully integrated JavaScript with OpenAI’s ChatGPT API, allowing users to chat with the model in real time. This project serves as a great starting point for building more advanced applications that leverage AI for user interaction.

--

--

No responses yet