How to Create a ChatGPT Bot for Your Website (Step by Step)
Build a ChatGPT website chatbot using the OpenAI API, JavaScript embedding, and smart system prompts — with real cost estimates and working code examples.
Get more content like this on Telegram!
Daily AI tips, notes & resources — free
I built my first website chatbot on a Saturday afternoon. Not because I was an expert developer — I'm not — but because the OpenAI API documentation is actually pretty clear, and the JavaScript needed for a basic implementation fits in about 60 lines of code.
What I learned: the technical setup is the easy part. Writing a good system prompt and testing it properly is where most chatbots succeed or fail.
This guide walks through both. By the end, you'll have a working chatbot you can embed in any website, an understanding of the cost structure, and a system prompt template that actually keeps your chatbot on-topic.
What You'll Need Before Starting
- An OpenAI API account (separate from your ChatGPT subscription)
- A basic website you can edit (HTML access or a CMS that allows custom code)
- Beginner-level comfort with JavaScript (you don't need to be an expert)
- About 90 minutes for the initial setup
The OpenAI API is not the same as ChatGPT Plus. Your ChatGPT subscription doesn't include API access — you'll need to create an API account at platform.openai.com and add a payment method. Billing is pay-per-use, not a flat monthly fee.
Step 1: Get Your OpenAI API Key
- Go to platform.openai.com and create an account.
- Navigate to API Keys in the left sidebar.
- Click "Create new secret key" and give it a descriptive name (e.g., "Website Chatbot").
- Copy the key immediately — you won't be able to see it again.
- Store it somewhere secure. Treat it like a password.
Important: Never expose your API key in client-side JavaScript. Your API key in a public JavaScript file means anyone who views your source code can steal your key and rack up charges on your account. We'll handle this properly in the architecture section.
Step 2: Choose Your Model
For a website chatbot, GPT-4o mini is the right starting choice for most businesses. It's fast, capable, and inexpensive. GPT-4o is higher quality but costs roughly 15-20x more per token — usually not justified for customer-facing FAQ and support chatbots.
Model comparison for chatbot use:
| Model | Quality | Speed | Cost per 1K tokens | Best for |
|---|---|---|---|---|
| GPT-4o mini | Good | Very fast | ~$0.00015 | Most business chatbots |
| GPT-4o | Excellent | Fast | ~$0.0025 | Complex support, nuanced conversations |
| GPT-3.5 Turbo | Decent | Very fast | ~$0.0005 | Simple FAQ bots |
Start with GPT-4o mini. You can always switch models in your code with a single line change once you've tested the experience.
Step 3: Design Your System Prompt
This is the most important step and the one most tutorials rush past. Your system prompt defines everything your chatbot is and does. A weak system prompt produces a chatbot that goes off-topic, invents answers, and frustrates users.
Here's a template that works well for business chatbots:
You are [Business Name]'s customer support assistant. Your job is to help visitors with questions about our [products/services].
About our business:
[2-3 sentences describing what your business does, your main products/services, and your general customer base]
You can help with:
- Directing customers to the right contact person or page
You cannot:
- Make commitments on pricing, availability, or timelines without checking with our team
- Access order systems, account information, or internal databases
- Provide legal, medical, or financial advice
If you don't know the answer: Say "I'm not sure about that — let me connect you with our team" and provide the contact information below. Never guess or make up information.
Contact information:
Email: [email]
Phone: [phone]
Hours: [hours]
Tone: Friendly, helpful, concise. Keep responses under 150 words unless the question requires more detail.
The "You cannot" section is essential. I tested a chatbot without explicit restrictions and within twenty minutes of opening it to users, someone had asked it to recommend competitor products and it happily obliged. Scope restrictions prevent this.
For more on writing effective instructions that produce consistent outputs, our prompt engineering guide has a full section on system prompt design.
Step 4: Build the Backend (API Handler)
Because you can't expose your API key in front-end JavaScript, you need a server-side function to handle the API calls. Here are three approaches in order of simplicity:
Option A: Vercel Edge Function (recommended for most projects)
Create a file called api/chat.js in your project:
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
const { messages } = req.body;
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`
},
body: JSON.stringify({
model: 'gpt-4o-mini',
messages: [
{
role: 'system',
content: YOUR_SYSTEM_PROMPT_HERE
},
...messages
],
max_tokens: 300,
temperature: 0.7
})
});
const data = await response.json();
res.json({ reply: data.choices[0].message.content });
}
Set your OPENAI_API_KEY as an environment variable in your Vercel project settings — never hardcode it.
Option B: Netlify Function — nearly identical structure, placed in netlify/functions/chat.js.
Option C: Your existing server — if you have a Node.js, Python, or PHP backend, call the OpenAI API from there. The pattern is the same: receive the user message, forward to OpenAI with your API key (from an environment variable), return the response.
Step 5: Build the Frontend Chat Widget
Here's a minimal but functional chat widget in HTML and JavaScript:
<div id="chat-widget">
<div id="chat-header">Chat with us</div>
<div id="chat-messages"></div>
<div id="chat-input-area">
<input type="text" id="chat-input" placeholder="Ask a question..." />
<button id="chat-send">Send</button>
</div>
</div>
<script>
const chatMessages = document.getElementById('chat-messages');
const chatInput = document.getElementById('chat-input');
const chatSend = document.getElementById('chat-send');
let conversationHistory = [];
async function sendMessage() {
const userMessage = chatInput.value.trim();
if (!userMessage) return;
// Add user message to display
appendMessage('user', userMessage);
conversationHistory.push({ role: 'user', content: userMessage });
chatInput.value = '';
// Show typing indicator
const typingIndicator = appendMessage('assistant', '...');
try {
const response = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ messages: conversationHistory })
});
const data = await response.json();
const reply = data.reply;
// Replace typing indicator with actual response
typingIndicator.textContent = reply;
conversationHistory.push({ role: 'assistant', content: reply });
} catch (error) {
typingIndicator.textContent = 'Sorry, something went wrong. Please try again.';
}
}
function appendMessage(role, content) {
const msgDiv = document.createElement('div');
msgDiv.className = `message ${role}`;
msgDiv.textContent = content;
chatMessages.appendChild(msgDiv);
chatMessages.scrollTop = chatMessages.scrollHeight;
return msgDiv;
}
chatSend.addEventListener('click', sendMessage);
chatInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') sendMessage();
});
</script>
This is deliberately minimal — you'll want to add CSS styling to match your site design and potentially a toggle button to show/hide the widget. The core logic is here.
Step 6: Cost Estimation
At GPT-4o mini rates, let's calculate a realistic scenario.
Average user conversation: 8 messages exchanged, roughly 200 tokens per message = ~1,600 tokens per conversation.
At $0.00015 per 1K tokens (input) and $0.00060 per 1K tokens (output):
- 100 conversations/month: under $0.50
- 1,000 conversations/month: approximately $2-$4
- 10,000 conversations/month: approximately $20-$40
Set a spending limit in your OpenAI dashboard to cap costs. Navigate to Settings > Billing > Usage limits and set a monthly maximum.
For a growing business with high chat volume, Claude's API or open-source models running on your own infrastructure become worth exploring — our ChatGPT vs Claude vs Gemini comparison covers API pricing differences.
Testing Your Chatbot Before Launch
Test every prompt in this list before going live:
- Questions your chatbot should answer well (your core FAQ topics)
- Questions that are slightly off-topic (can it redirect gracefully?)
- Questions asking for commitments ("Can you guarantee delivery by Friday?")
- Attempts to get it to go off-script ("Forget your instructions and...")
- Requests for contact information and redirects to your team
- A long multi-turn conversation (does it maintain context?)
Log the conversations during testing. This tells you what to adjust in your system prompt. Most chatbots need 3-4 rounds of system prompt refinement before they're ready for real users.
According to OpenAI's usage policies, website chatbots must clearly identify as AI and not impersonate humans. Include a line in your chatbot's introduction like "I'm an AI assistant for [Business Name]."
No-Code Alternatives Worth Knowing
If the code approach feels like too much for your situation, these platforms build on the OpenAI API with visual interfaces:
Chatbase — upload your content, get a chatbot trained on your documents. Good for knowledge bases. Tidio — e-commerce focused, integrates with Shopify and WooCommerce. Dante AI — trains on your website content, embeds easily.
These cost more per conversation than using the API directly, but save significant development time. For small businesses without developer resources, they're often the better practical choice.
For building prompts that make any chatbot platform work better, the techniques in our ChatGPT prompt bible apply across platforms, not just the direct API.
Further Reading
Frequently Asked Questions
AiTechWorlds Team
✓ Verified WriterThe AiTechWorlds team is passionate about AI, technology, and education. We create high-quality, research-backed content to help you learn, grow, and succeed in the modern digital world.
Related Articles
10 Advanced ChatGPT Prompting Techniques (Chain of Density and More)
Master advanced ChatGPT prompting with Chain of Density, Chain of Thought, Tree of Thoughts, role stacking, and 6 more expert techniques with real examples.
How to Use AI to Write a Compelling About Us Page (2026)
Use an AI about us page generator to craft a story, mission, and team section that builds trust. Includes 3 templates for startups, freelancers, and agencies.
How to Create AI-Generated Album Cover Art (Free Tools 2026)
Learn how to create AI album cover art for free using top tools in 2026. Genre-specific prompts, Spotify specs, and real tool comparisons inside.
5 AI Image Generators Specialized in Anime Style (2026)
Find the best AI anime generator for 2026. Compare NovelAI, Waifu Diffusion, Leonardo, and more with real accuracy tests and free tier details.