Build Your First AI Chatbot Using OpenAI API

AI chatbot

Building an AI chatbot used to mean training your own model. Now it means calling an API. Complete working code Express backend, chat frontend, conversation memory plus a live cost calculator using real 2026 pricing.

AI Development AI Chatbot OpenAI API Node.js

Building an AI chatbot used to mean training your own language model. Today it means calling an API. This guide builds a genuinely working AI chatbot, backend and frontend, using the OpenAI API and Node.js, in roughly the time it takes to read through it once.

An AI chatbot built on the OpenAI API works by sending user messages to OpenAI's chat completions endpoint through a backend server, then returning the model's response to a frontend chat interface.

The backend exists specifically to keep your API key hidden from anyone viewing the page's source code.

We covered the strategic side of AI agents in our AI agent guide. This article is the hands-on build: real, working code for an actual AI chatbot, end to end.

Advertisement
Advertisement
$0.15

per 1 million input tokens using OpenAI's cost-effective gpt-4o-mini model

2

parts every AI chatbot needs: a backend that calls the API, and a frontend chat UI

1

rule above all others: never call the OpenAI API directly from frontend JavaScript

How This AI Chatbot Is Structured

1User Types a Message
2Frontend Sends fetch() to /chat
3Express Backend Calls OpenAI
4Response Returns to Chat UI
Security Warning

Never put your OpenAI API key in frontend JavaScript. Anyone viewing your page's source code could copy it and run up charges on your account. Always route requests through a backend server, as shown below.

Step 1: Project Setup

According to a tutorial on building a chatbot with the OpenAI API and Node.js, four packages cover everything this AI chatbot needs.

# Create a new project folder
mkdir ai-chatbot && cd ai-chatbot
npm init -y

# Install dependencies
npm install express openai dotenv cors

Four packages: a web server, the official OpenAI SDK, environment variable support, and CORS handling

# .env file, keep this out of version control
OPENAI_API_KEY=sk-your-actual-key-here
PORT=5000

Store your API key here, never directly in your code

Step 2: The Backend Server

This Express server exposes a single /chat endpoint that receives a message and returns the AI chatbot's response, using the official openai npm package.

// server.js
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import OpenAI from 'openai';

dotenv.config();

const app = express();
app.use(cors());
app.use(express.json());

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

app.post('/chat', async (req, res) => {
  const { message } = req.body;
  if (!message) {
    return res.status(400).json({ error: 'Message is required' });
  }

  try {
    const completion = await openai.chat.completions.create({
      model: 'gpt-4o-mini',
      messages: [
        { role: 'system', content: 'You are a helpful, concise assistant.' },
        { role: 'user', content: message }
      ],
      temperature: 0.7,
      max_tokens: 300
    });

    res.json({ reply: completion.choices[0].message.content });
  } catch (error) {
    console.error('OpenAI API error:', error.message);
    res.status(500).json({ error: 'Something went wrong' });
  }
});

app.listen(process.env.PORT || 5000, () => {
  console.log('AI chatbot server running');
});

The complete backend: receives a message, calls OpenAI, returns the reply as JSON

Step 3: The Frontend Chat Interface

<div id="chat-window"></div>
<input type="text" id="chat-input" placeholder="Type a message...">
<button onclick="sendMessage()">Send</button>

<script>
async function sendMessage() {
  const input = document.getElementById('chat-input');
  const message = input.value.trim();
  if (!message) return;

  appendMessage('user', message);
  input.value = '';

  const response = await fetch('/chat', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ message })
  });

  const data = await response.json();
  appendMessage('bot', data.reply || 'Something went wrong.');
}

function appendMessage(sender, text) {
  const window_ = document.getElementById('chat-window');
  window_.innerHTML += `<p><strong>${sender}:</strong> ${text}</p>`;
}
</script>

A minimal chat UI: no framework required, just fetch() talking to your own backend

Advertisement
Advertisement

Step 4: Adding Conversation Memory

According to Cloudinary's guide to building a developer chatbot with OpenAI, the model itself has no memory between separate API calls, so the full conversation array must be resent every time.

The basic version above forgets everything after each message. Passing the full conversation history back to the API gives the AI chatbot actual memory.

// Track conversation on the frontend
let conversationHistory = [
  { role: 'system', content: 'You are a helpful, concise assistant.' }
];

// Inside sendMessage(), before the fetch call:
conversationHistory.push({ role: 'user', content: message });

// Send the full history instead of a single message
body: JSON.stringify({ messages: conversationHistory })

// After getting a reply, add it to history too
conversationHistory.push({ role: 'assistant', content: data.reply });

Update the backend's messages field to accept req.body.messages instead of a single string

Cost Estimator for Your AI Chatbot

According to a complete 2026 tutorial on using the ChatGPT API, gpt-4o-mini pricing sits at $0.15 per million input tokens and $0.60 per million output tokens, making it dramatically cheaper than larger models for most AI chatbot use cases.

Estimate your monthly OpenAI API cost based on expected conversation volume.

AI Chatbot Cost Estimator

Based on gpt-4o-mini pricing: $0.15 per 1M input tokens, $0.60 per 1M output tokens

$0.00 / month

Enter your numbers above to estimate monthly cost.

Advertisement
Advertisement

Key Parameters That Shape Your AI Chatbot's Behavior

According to a complete guide to the OpenAI Chat Completion API, understanding these four parameters covers most of what shapes an AI chatbot's actual behavior.

ParameterWhat It Controls
system role messageSets the AI chatbot's personality, tone, and behavior rules
temperature0 for focused, predictable answers; up to 1+ for more creative variation
max_tokensCaps response length, directly controlling cost per reply
modelgpt-4o-mini for cost-efficiency; larger models for more complex reasoning

Deploying Your AI Chatbot

1

Choose a Hosting Platform

According to DEV Community's complete guide to building an AI chatbot, platforms supporting Node.js directly work well for small to medium chatbot deployments without added infrastructure complexity.

2

Set Environment Variables on the Host

Add your OPENAI_API_KEY as an environment variable in your hosting platform's dashboard, never committed to your code repository.

3

Add Rate Limiting Before Going Live

According to freeCodeCamp's guide to building a chatbot with OpenAI, Node.js, and React, without limits, a single visitor sending rapid requests can generate unexpected costs. Basic rate limiting middleware protects against this before real traffic arrives.

FAQs on Building an AI Chatbot With OpenAI API

Do I need to know machine learning to build an AI chatbot?
No. The OpenAI API provides a pre-trained model through a simple API call. Building an AI chatbot this way requires standard web development skills, not machine learning expertise.
Why do I need a backend server instead of calling OpenAI directly from the browser?
Calling the API directly from frontend JavaScript exposes your API key in the page's source code, where anyone could copy and misuse it. A backend keeps the key hidden and never sent to the browser.
Which OpenAI model should I use for a basic AI chatbot?
gpt-4o-mini offers strong performance at a fraction of the cost of larger models, making it the practical default for most chatbot use cases unless complex reasoning is specifically required.
How do I give my AI chatbot memory of the conversation?
Pass the full conversation history, not just the latest message, back to the API on every request. The model has no memory of its own between separate API calls.
How much does running an AI chatbot actually cost?
It depends entirely on volume and message length. Using gpt-4o-mini, costs stay low for moderate traffic, roughly cents to a few dollars per thousand typical conversations, though costs scale with usage.
Can this same approach work with other AI providers?
Yes. The same backend-proxy pattern applies to Anthropic's Claude API or other providers, generally requiring only changes to the SDK import and the specific API call syntax.

> what_we_learn_today.log

[OK]

An AI chatbot needs two parts: a backend calling OpenAI, and a frontend chat UI

[OK]

Never expose your API key in frontend JavaScript, ever

[OK]

The system role message sets the chatbot's personality and behavior rules

[OK]

Conversation memory requires sending the full message history each request

[OK]

gpt-4o-mini balances cost and capability for most chatbot use cases

[OK]

Add rate limiting before deploying publicly to control unexpected costs

0 Votes: 0 Upvotes, 0 Downvotes (0 Points)

Leave a reply

Loading Next Post...
Search
Popular Now
Loading

Signing-in 3 seconds...

Signing-up 3 seconds...