DEV Community

Cover image for Build an AI Chatbot with OpenAI GPT-4o
Gate of AI
Gate of AI

Posted on • Originally published at gateofai.com

Build an AI Chatbot with OpenAI GPT-4o

🚀 Technical Briefing: This tutorial is part of our deep-dive series on Agentic Workflows at Gate of AI. For the full technical breakdown, interactive code sandbox, and the native Arabic translation, visit the original article here.

<span>Tutorial</span>
<span>Intermediate</span>
<span>⏱ 45 min read</span>
<span>© Gate of AI 2026-07-11</span>
Enter fullscreen mode Exit fullscreen mode

In this comprehensive tutorial, you will build a responsive AI chatbot using JavaScript and OpenAI's latest GPT-4o, enhancing user interaction through seamless AI integration.

Prerequisites


  • Node.js version 18 or higher
  • OpenAI API key
  • Intermediate JavaScript knowledge

What We're Building


This tutorial guides you through creating a dynamic AI-powered chatbot. The chatbot will leverage OpenAI's GPT-4o model for generating human-like responses, including recognizing emotional cues and engaging in rapid voice interactions. The end product will be a web-based chatbot capable of understanding and responding to user queries in a conversational manner.


The chatbot will be built using modern JavaScript practices, ensuring it is both efficient and easy to maintain. You'll learn how to set up the OpenAI client, handle asynchronous operations, and manage state effectively in a chat application context.

Setup and Installation


To get started, you will need to set up a Node.js environment and install the necessary packages. This includes the OpenAI SDK, which allows us to interact with the GPT-4o model.


npm install openai dotenv express

Next, configure your environment variables to securely store your OpenAI API key. Create a .env file in the root of your project directory.



OPENAI_API_KEY=your_openai_api_key_here

Step 1: Setting Up the Server


This step involves creating a simple Express server to handle HTTP requests. The server will act as the backend for our chatbot, interfacing with the OpenAI API.



const express = require('express');
const dotenv = require('dotenv');
const { OpenAI } = require('openai');

dotenv.config();
const app = express();
app.use(express.json());

const client = new OpenAI(process.env.OPENAI_API_KEY);

app.post('/api/chat', async (req, res) => {
const { message } = req.body;
try {
const response = await client.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: message }]
});
res.json({ reply: response.choices[0].message.content });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Error processing request' });
}
});

app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});


This code sets up an Express server that listens for POST requests on the /api/chat endpoint. It uses the OpenAI client to send the user message to the GPT-4o model and returns the AI's response.

Step 2: Creating the Frontend


In this step, you'll create a basic HTML page with a form for user input and an area to display the chatbot's responses.





AI Chatbot
body { font-family: Arial, sans-serif; }
#chat { max-width: 600px; margin: 20px auto; }
#messages { border: 1px solid #ccc; padding: 10px; height: 300px; overflow-y: scroll; }
#user-input { width: 100%; padding: 10px; }








document.getElementById('user-input').addEventListener('keydown', async function(e) {
  if (e.key === 'Enter') {
    const message = e.target.value;
    e.target.value = '';
    const messagesDiv = document.getElementById('messages');
    messagesDiv.innerHTML += `&lt;div&gt;&lt;strong&gt;You:&lt;/strong&gt; ${message}&lt;/div&gt;`;

    const response = await fetch('/api/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ message })
    });
    const data = await response.json();
    messagesDiv.innerHTML += `&lt;div&gt;&lt;strong&gt;Bot:&lt;/strong&gt; ${data.reply}&lt;/div&gt;`;
    messagesDiv.scrollTop = messagesDiv.scrollHeight;
  }
});
Enter fullscreen mode Exit fullscreen mode

This HTML page includes a simple chat interface. When the user presses Enter, the message is sent to the server, and the response is displayed in the chat window.

Step 3: Enhancing the Chat Experience


To improve user experience, we'll add features like loading indicators and error handling in the frontend.




const userInput = document.getElementById('user-input');
const messagesDiv = document.getElementById('messages');

userInput.addEventListener('keydown', async function(e) {
if (e.key === 'Enter') {
const message = e.target.value;
e.target.value = '';
messagesDiv.innerHTML += &lt;div&gt;&lt;strong&gt;You:&lt;/strong&gt; ${message}&lt;/div&gt;;
messagesDiv.innerHTML += &lt;div id="loading"&gt;Bot is typing...&lt;/div&gt;;

  try {
    const response = await fetch('/api/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ message })
    });
    const data = await response.json();
    document.getElementById('loading').remove();
    messagesDiv.innerHTML += `&lt;div&gt;&lt;strong&gt;Bot:&lt;/strong&gt; ${data.reply}&lt;/div&gt;`;
  } catch (error) {
    document.getElementById('loading').remove();
    messagesDiv.innerHTML += `&lt;div&gt;&lt;strong&gt;Error:&lt;/strong&gt; Unable to fetch response&lt;/div&gt;`;
  }
  messagesDiv.scrollTop = messagesDiv.scrollHeight;
}
Enter fullscreen mode Exit fullscreen mode

});


This script adds a "Bot is typing..." indicator while waiting for the response and handles any errors that occur during the fetch operation.

⚠️ Common Mistake: Ensure that the server is running and accessible from the frontend. Network errors can occur if the server is not active or if there are CORS issues.

Testing Your Implementation


To verify that your chatbot works, open the HTML file in a browser and try sending a few messages. You should see your input and the bot's responses in the chat window.



Ensure your server is running

node server.js

Open the HTML file in a browser and interact with the chatbot

What to Build Next


  • Add a database to store chat history and analyze user interactions.
  • Integrate speech recognition to allow voice input and output, aligning with the capabilities of GPT-4o.
  • Expand the chatbot's capabilities by integrating additional APIs for more diverse responses.

Incorporating AI technologies like GPT-4o can significantly enhance digital transformation initiatives in the GCC region, supporting goals such as Saudi Vision 2030 and the UAE's National Strategy for AI. By leveraging these advanced AI capabilities, businesses can improve customer engagement and operational efficiency.

Top comments (0)