DEV Community
In this article, we'll guide you through the process of creating your very own "Copilot Chatbot" – a simple web application powered by the OpenAI API to provide interactive chat functionalities. We'll be using a combination of HTML for the front-end structure, PHP for handling the backend logic and communication with the OpenAI API, and JavaScript for dynamic user interactions.
This project will demonstrate the fundamental steps involved in integrating a powerful AI like OpenAI's GPT-3 into a web interface, allowing you to build a basic chatbot for various purposes.
Prerequisites:
Before we begin, ensure you have the following:
- OpenAI API Key: You'll need an API key from OpenAI to access their GPT-3 models. Visit the OpenAI website to sign up and obtain your API key.
- PHP Server Environment: You'll need a local or remote server capable of running PHP. Common options include XAMPP, WAMP (for local development on Windows), MAMP (for local development on macOS), or a web hosting service with PHP support.
- Basic Knowledge of HTML, CSS (optional), PHP, and JavaScript: While we'll provide the code, a basic understanding of these web technologies will be beneficial.
Project Structure:
We'll organize our project into the following files:
-
index.html
: The main HTML file for the chat interface. -
api.php
: A PHP file to handle the communication with the OpenAI API. -
script.js
: A JavaScript file for front-end interactivity.
Step-by-Step Guide:
1. Create index.html
(The Front-End):
This file will contain the basic structure of our chat interface. Create a file named index.html
and paste the following code into it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OpenAI Copilot</title>
</head>
<body>
<h1>Welcome to Copilot Chat</h1>
<div>
<label for="userInput">User Input:</label>
<input type="text" id="userInput">
<button onclick="sendMessage()">Send</button>
</div>
<div id="chatbox">
</div>
<script src="script.js"></script>
</body>
</html>
This HTML sets up a simple page with a heading, an input field for the user to type their message, a "Send" button, and a div
with the ID chatbox
where the conversation will be displayed. It also includes the script.js
file.
2. Create api.php
(The Backend Logic):
This PHP file will handle the crucial task of taking the user's input and sending it to the OpenAI API, then returning the API's response. Create a file named api.php
in the same directory and paste the following code. Remember to replace 'YOUR_API_KEY'
with your actual OpenAI API key.
<?php
// Make sure to replace 'YOUR_API_KEY' with your actual OpenAI API key.
$apiKey = 'YOUR_API_KEY';
function callOpenAPI($input) {
global $apiKey;
$url = 'https://api.openai.com/v1/engines/davinci-codex/completions';
$headers = array(
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey
);
$data = array(
'prompt' => $input,
'max_tokens' => 150
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$userInput = $_POST['user_input'];
// Ensure the input is not empty before making the API call
if (!empty($userInput)) {
$response = callOpenAPI($userInput);
echo json_encode(array('message' => $response));
}
}
?>
This PHP script defines a function callOpenAPI
that takes user input, sets up the necessary headers (including your OpenAI API key), and makes a POST request to the OpenAI API endpoint. It then decodes the JSON response and returns it. The script also checks if the request method is POST, retrieves the user input, and calls the callOpenAPI
function if the input is not empty. The response from the OpenAI API is then encoded as JSON and sent back to the front-end.
Note: This example uses the davinci-codex
engine, which is a powerful but potentially expensive model. You might want to explore other engines like text-ada-001
or gpt-3.5-turbo
(which requires a slightly different API call structure) for cost-effectiveness.
3. Create script.js
(The Front-End Interactivity):
This JavaScript file will handle user interaction, sending the input to the PHP backend, and updating the chatbox with the responses. Create a file named script.js
in the same directory and paste the following code:
function appendMessageToChatbox(sender, message) {
const chatbox = document.getElementById('chatbox');
const messageDiv = document.createElement('div');
messageDiv.innerHTML = `<strong>${sender}: </strong>${message}`;
chatbox.appendChild(messageDiv);
}
function sendMessage() {
const userInput = document.getElementById('userInput').value;
appendMessageToChatbox('You', userInput);
// Make an AJAX call to the API
const xhr = new XMLHttpRequest();
xhr.open('POST', 'api.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
appendMessageToChatbox('Bot', response.message);
} else {
console.error('Error:', xhr.status);
}
};
xhr.send(`user_input=${encodeURIComponent(userInput)}`);
}
This JavaScript code defines two main functions:
-
appendMessageToChatbox
: This function takes a sender (either "You" or "Bot") and a message as input, creates a newdiv
element to display the message, and appends it to thechatbox
element in our HTML. -
sendMessage
: This function gets the user's input from theuserInput
field, appends the user's message to the chatbox, and then makes an asynchronous POST request to theapi.php
script. It sends the user input as form data. When theapi.php
script responds successfully, it parses the JSON response and uses theappendMessageToChatbox
function to display the bot's message. If there's an error, it logs it to the console.
4. Set Up Your Server and Run the Application:
- Start your PHP server: If you are using XAMPP, WAMP, or MAMP, start the Apache server.
- Place the files: Ensure that the
index.html
,api.php
, andscript.js
files are all in the same directory within your server's web root directory (e.g.,htdocs
in XAMPP,www
in WAMP). - Access the application: Open your web browser and navigate to the application's URL. This is usually
http://localhost
orhttp://localhost:<port>
(replace<port>
with the port your server is running on, if necessary).
How to Use:
Once the application is running in your browser, you'll see the simple chat interface.
- Type your message in the "User Input" field.
- Click the "Send" button.
- Your message will appear in the chatbox, followed by the response from the OpenAI-powered chatbot.
- Continue the conversation by typing new messages.
Potential Enhancements:
This is a basic implementation, and there are many ways you can enhance it:
- Styling: Add CSS to make the chat interface more visually appealing.
- Error Handling: Implement more robust error handling for API requests and responses.
- User Interface Improvements: Consider features like displaying typing indicators, clearing the input field after sending a message, and automatically scrolling to the latest message.
- Conversation History: Implement a way to store and display the conversation history.
- Model Selection: Allow the user to choose different OpenAI models.
- Parameters: Expose more OpenAI API parameters (like temperature or presence penalty) to the user.
- Security: Implement proper security measures, especially if you plan to deploy this application publicly. Avoid exposing your API key on the front-end.
Conclusion:
Congratulations! You've now built a basic chatbot powered by the OpenAI API using PHP, HTML, and JavaScript. This project provides a solid foundation for exploring the exciting possibilities of integrating AI into web applications. Remember to handle your API key securely and explore the extensive capabilities of the OpenAI API to build more sophisticated and engaging chatbots.
Download Source: https://github.com/wildshark/copilot-chat
Email: iquipe@iquipedigital.com
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)