Creating a simple web app to interact with the ChatGPT API involves several steps, including setting up a backend to handle API requests and a frontend to interact with users. Here's a basic outline of how to set up such an application using JavaScript (Node.js for the backend) and HTML/CSS/JavaScript for the frontend.
Prerequisites
- Node.js installed on your development machine.
- A basic understanding of JavaScript, HTML/CSS, and asynchronous programming.
Steps to Create the Web App
1. Set Up the Node.js Backend
1.1 Initialize Node.js Project
Create a new directory for your project, navigate into it, and initialize a Node.js project:
mkdir chatgpt-webapp
cd chatgpt-webapp
npm init -y
1.2 Install Required Packages
You will need express for the backend server and axios for making HTTP requests:
npm install express axios dotenv
1.3 Create a .env File
Store your API keys and secrets securely. For example, create a .env file:
OPENAI_API_KEY=your_openai_api_key_here
1.4 Create a Basic Express Server
Create a server.js file for the backend logic:
// server.js
const express = require('express');
const axios = require('axios');
require('dotenv').config();
const app = express();
app.use(express.json());
const port = 3000;
app.post('/api/chat', async (req, res) => {
const { message } = req.body;
try {
const response = await axios.post(
'https://api.openai.com/v1/engines/gpt-4/your-endpoint-here/completions',
{
prompt: message,
max_tokens: 150,
n: 1,
stop: null,
temperature: 0.7,
},
{
headers: {
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
'Content-Type': 'application/json',
},
}
);
res.json({ response: response.data.choices[0].text });
} catch (error) {
console.error('Error connecting to the API', error);
res.status(500).send('Internal Server Error');
}
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
2. Set Up the Frontend
2.1 Create an HTML File
Create an index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ChatGPT Web App</title>
</head>
<body>
<div>
<h1>Chat with GPT-4</h1>
<textarea id="userInput" placeholder="Type your message here"></textarea>
<button onclick="sendMessage()">Send</button>
<div id="chatResponse"></div>
</div>
<script>
async function sendMessage() {
const message = document.getElementById('userInput').value;
const response = await fetch('/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ message })
});
const data = await response.json();
document.getElementById('chatResponse').innerText = data.response;
}
</script>
</body>
</html>
3. Test Your Web Application
-
Start the Backend Server
Run the server using Node.js:
node server.js
-
Access the Web App
Open your web browser and navigate to http://localhost:3000 to see your simple chat interface.
Notes
- Make sure to replace
"https://api.openai.com/v1/engines/gpt-4/your-endpoint-here/completions" with the correct endpoint if your path differs or if you are using any specific model path.
- This example uses basic client-side rendering. In a real-world application, you may want to use a front-end framework like React, Vue, or Angular for more robust features.
- Implement proper error handling and input validation for production-grade applications.
- This setup is basic and for learning purposes. For a production application, ensure you secure your API keys and consider additional measures like rate limiting and authentication.
By following these steps, you should be able to create a simple web application that communicates with the ChatGPT API.