How to add chatbot to website
Quick answer
Use the
OpenAI Python SDK to create a chatbot backend that handles user messages with client.chat.completions.create. Then connect this backend to your website frontend via an API endpoint to send and receive chat messages dynamically.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0Basic knowledge of HTML, JavaScript, and Flask or FastAPI
Setup
Install the openai Python package and set your OpenAI API key as an environment variable. This example uses Flask for the backend server.
pip install openai flask Step by step
Create a Flask backend that exposes a /chat API endpoint. This endpoint receives user messages, calls the OpenAI gpt-4o model, and returns the chatbot response. Then add a simple HTML + JavaScript frontend to send user input and display the chatbot replies.
import os
from flask import Flask, request, jsonify
from openai import OpenAI
app = Flask(__name__)
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
@app.route('/chat', methods=['POST'])
def chat():
data = request.json
user_message = data.get('message', '')
if not user_message:
return jsonify({'error': 'No message provided'}), 400
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": user_message}]
)
reply = response.choices[0].message.content
return jsonify({'reply': reply})
if __name__ == '__main__':
app.run(debug=True, port=5000) Common variations
You can use FastAPI instead of Flask for async support, or switch to other models like gpt-4o-mini for lower cost. For streaming responses, use stream=True in the chat.completions.create call and handle chunks on the frontend.
from fastapi import FastAPI, Request
from openai import OpenAI
import uvicorn
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-mini",
messages=[{"role": "user", "content": user_message}]
)
return {"reply": response.choices[0].message.content}
if __name__ == '__main__':
uvicorn.run(app, host='0.0.0.0', port=8000) Troubleshooting
- If you get authentication errors, verify your
OPENAI_API_KEYenvironment variable is set correctly. - If the chatbot returns empty responses, check your request payload and model name.
- For CORS issues on the frontend, configure your backend to allow cross-origin requests.
Key Takeaways
- Use the OpenAI Python SDK with
client.chat.completions.createto build chatbot backends. - Connect your backend API to a website frontend using JavaScript fetch or AJAX calls.
- Choose models like
gpt-4ofor best quality orgpt-4o-minifor cost-effective chatbots. - Implement streaming for real-time chat experiences using
stream=True. - Always secure your API key and handle errors gracefully in production.