Introduction
This documentation provides a comprehensive guide on how to integrate JavaScript with OpenAI’s ChatGPT API, enabling real-time interaction in a chat-like interface. By following the steps outlined below, you will create a simple web application that allows users to send messages to the ChatGPT model and receive responses.
Prerequisites
Before starting, 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
Sign Up / Log In: Visit the OpenAI website and create an account if you don’t have one.
Get Your API Key: Navigate to the API section in your OpenAI account and generate your API key. Keep this key confidential.
Step 2: Setting Up Your Project
Create a new directory for your project.
Within that directory, create two files:
index.html
andapp.js
.
Step 3: Creating the HTML Structure
In the index.html
file, set up the user interface, which includes a text area for user input, a send button, and a display area for responses. Here is the HTML code:
<!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
In the app.js
file, implement the functionality to handle user input and interact with the ChatGPT API. Below is the JavaScript code:
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.";
}
});
Explanation of JavaScript Functionality:
API Key: Replace
YOUR_API_KEY
with your actual OpenAI API key.Event Listener: When the send button is clicked, the user's message is retrieved.
Fetch API: A POST request is made to the ChatGPT API with the user's message.
Response Handling: The bot's response is displayed in the designated area.
Step 5: Running Your Application
Insert Your API Key: Open
app.js
and replaceYOUR_API_KEY
with your actual OpenAI API key.Open index.html: Launch the
index.html
file in your web browser.Interact with ChatGPT: Type a message in the text area and click the “Send” button to see the response from ChatGPT displayed below.
Step 6: Understanding the Code
HTML Structure: A simple user interface is created with a text area, a button, and a response display area.
JavaScript Functionality:
The Fetch API is used to send a POST request to the ChatGPT API.
The request includes the user’s message, and the response is processed and displayed.
Security Note
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
This guide has successfully demonstrated how to integrate JavaScript with OpenAI’s ChatGPT API, enabling real-time user interaction. This project serves as a foundation for building more advanced applications that leverage AI for user engagement.