How to beginner · 3 min read

How to add AI chatbot to website

Quick answer
Use the OpenAI API to create a chatbot backend that processes user messages and returns AI-generated responses. Embed a simple frontend chat interface on your website that sends user input to this backend and displays the AI replies in real time.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install openai>=1.0
  • Basic HTML, JavaScript knowledge

Setup

Install the openai Python package and set your API key as an environment variable for secure access.

bash
pip install openai

Step by step

Create a Python backend that receives chat messages, calls the gpt-4o model via the OpenAI API, and returns the AI response. Then, build a simple HTML/JavaScript frontend to send user input and display replies.

python
import os
from openai import OpenAI
from flask import Flask, request, jsonify

app = Flask(__name__)
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

@app.route('/chat', methods=['POST'])
def chat():
    user_message = request.json.get('message')
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": user_message}]
    )
    ai_reply = response.choices[0].message.content
    return jsonify({"reply": ai_reply})

if __name__ == '__main__':
    app.run(port=5000)

/* Frontend HTML + JS snippet */

"""
<!DOCTYPE html>
<html lang=\"en\">
<head><title>AI Chatbot</title></head>
<body>
  <div>
    <textarea id=\"chatInput\" rows=\"3\" cols=\"40\"></textarea><br>
    <button onclick=\"sendMessage()\">Send</button>
  </div>
  <div id=\"chatOutput\"></div>

  <script>
    async function sendMessage() {
      const input = document.getElementById('chatInput').value;
      const response = await fetch('/chat', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({message: input})
      });
      const data = await response.json();
      const outputDiv = document.getElementById('chatOutput');
      outputDiv.innerHTML += `<p><strong>You:</strong> ${input}</p>`;
      outputDiv.innerHTML += `<p><strong>AI:</strong> ${data.reply}</p>`;
      document.getElementById('chatInput').value = '';
    }
  </script>
</body>
</html>
"""
output
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

// Frontend loads in browser, user types message, AI replies appear below

Common variations

You can use async frameworks like FastAPI for better performance or switch to streaming responses for real-time token display. Also, try different models like claude-3-5-haiku-20241022 or gemini-1.5-pro depending on your use case.

python
import os
import asyncio
from openai import OpenAI
from fastapi import FastAPI, Request

app = FastAPI()
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

@app.post('/chat')
async def chat(request: Request):
    data = await request.json()
    user_message = data.get('message')
    response = await client.chat.completions.acreate(
        model="gpt-4o",
        messages=[{"role": "user", "content": user_message}]
    )
    return {"reply": response.choices[0].message.content}

# For streaming, use client.chat.completions.acreate with stream=True and handle chunks asynchronously.

Troubleshooting

  • If you get authentication errors, verify your OPENAI_API_KEY environment variable is set correctly.
  • For CORS issues on the frontend, configure your backend to allow cross-origin requests.
  • If responses are slow, consider using a smaller model or enabling streaming.

Key Takeaways

  • Use the OpenAI API gpt-4o model to power chatbot responses.
  • Build a simple backend API to handle chat messages securely with your API key.
  • Embed a lightweight frontend that sends user input and displays AI replies dynamically.
  • Consider async frameworks and streaming for better user experience and scalability.
  • Always secure your API key and handle CORS properly for web deployment.
Verified 2026-04 · gpt-4o, claude-3-5-haiku-20241022, gemini-1.5-pro
Verify ↗