Santaji GadeArtificial Intelligence2 weeks ago25 Views

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.
Table of Contents
ToggleBuilding 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.
per 1 million input tokens using OpenAI's cost-effective gpt-4o-mini model
parts every AI chatbot needs: a backend that calls the API, and a frontend chat UI
rule above all others: never call the OpenAI API directly from frontend JavaScript
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.
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
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
<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
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
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.
Based on gpt-4o-mini pricing: $0.15 per 1M input tokens, $0.60 per 1M output tokens
Enter your numbers above to estimate monthly cost.
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.
| Parameter | What It Controls |
|---|---|
system role message | Sets the AI chatbot's personality, tone, and behavior rules |
temperature | 0 for focused, predictable answers; up to 1+ for more creative variation |
max_tokens | Caps response length, directly controlling cost per reply |
model | gpt-4o-mini for cost-efficiency; larger models for more complex reasoning |
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.
Add your OPENAI_API_KEY as an environment variable in your hosting platform's dashboard, never committed to your code repository.
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.
An AI chatbot needs two parts: a backend calling OpenAI, and a frontend chat UI
Never expose your API key in frontend JavaScript, ever
The system role message sets the chatbot's personality and behavior rules
Conversation memory requires sending the full message history each request
gpt-4o-mini balances cost and capability for most chatbot use cases
Add rate limiting before deploying publicly to control unexpected costs










