Building a Chatbot Web App Using OpenAI’s API
### Prerequisites
– **Basic knowledge** of HTML, CSS, and JavaScript.
– **Node.js** installed to set up the server and manage dependencies.
– An **API key** from OpenAI for using their models.
### Outline of the Tutorial
1. **Set up the project structure**.
2. **Create the HTML/CSS interface** for the chatbot.
3. **Set up a Node.js server** to handle API requests.
4. **Connect the frontend to the server** and handle user inputs.
5. **Deploy the app** for others to use (optional).
### Step 1: Set Up the Project Structure
Create a new folder for your project and set up the following structure:
“`
chatbot-web-app/
│
├── public/
│ ├── index.html
│ ├── styles.css
│ └── script.js
│
├── server.js
└── package.json
“`
### Step 2: Create the HTML/CSS Interface
Create a simple interface in `public/index.html`:
“`html
“`
Add styles in `public/styles.css` to enhance the UI:
“`css
body {
font-family: Arial, sans-serif;
}
.chat-container {
max-width: 600px;
margin: 50px auto;
border: 1px solid #ccc;
padding: 20px;
border-radius: 10px;
}
#chat-box {
height: 300px;
overflow-y: scroll;
border: 1px solid #ddd;
margin-bottom: 10px;
padding: 10px;
}
input[type=”text”] {
width: 80%;
padding: 10px;
}
button {
padding: 10px;
}
“`
### Step 3: Set Up the Node.js Server
Install dependencies and create `server.js` to handle API requests.
1. Initialize your Node.js project:
“`bash
npm init -y
npm install express openai dotenv
“`
2. Create `server.js`:
“`javascript
const express = require(‘express’);
const { Configuration, OpenAIApi } = require(‘openai’);
require(‘dotenv’).config();
const app = express();
const port = 3000;
app.use(express.static(‘public’));
app.use(express.json());
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
app.post(‘/chat’, async (req, res) => {
try {
const { message } = req.body;
const response = await openai.createChatCompletion({
model: “gpt-3.5-turbo”,
messages: [{ role: “user”, content: message }],
});
res.json({ reply: response.data.choices[0].message.content });
} catch (error) {
console.error(error);
res.status(500).send(“An error occurred”);
}
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
“`
3. Add an `.env` file with your API key:
“`bash
OPENAI_API_KEY=your_openai_api_key
“`
### Step 4: Connect the Frontend to the Server
Add JavaScript in `public/script.js` to send and receive messages:
“`javascript
document.getElementById(‘send-btn’).addEventListener(‘click’, async () => {
const userInput = document.getElementById(‘user-input’).value;
if (!userInput) return;
document.getElementById(‘chat-box’).innerHTML += `
User: ${userInput}
`;
document.getElementById(‘user-input’).value = ”;
const response = await fetch(‘/chat’, {
method: ‘POST’,
headers: { ‘Content-Type’: ‘application/json’ },
body: JSON.stringify({ message: userInput })
});
const data = await response.json();
document.getElementById(‘chat-box’).innerHTML += `
Bot: ${data.reply}
`;
});
“`
### Step 5: Run and Test the App
1. Start the server:
“`bash
node server.js
“`
2. Open your browser and navigate to `http://localhost:3000`.
### Optional: Deploy the App
To make your chatbot accessible online, you can deploy it using services like **Vercel** or **Heroku**.
### Key Takeaways
– **Frontend**: Handles user input and displays the conversation.
– **Backend**: Processes requests using OpenAI’s API and sends responses.
– **API Integration**: Uses OpenAI’s `createChatCompletion` method for interaction.
This tutorial provides a solid starting point for creating a simple AI-powered chatbot web app!