Below is an example of how you can build a Python web server with a AI chatbot. In this example, we’ll use Flask as the web framework and integrate the OpenAI API (or any other AI model you prefer) to generate chatbot responses. We’ll also use Bootstrap for a modern, clean design.
Step 1: Set Up Your Environment
-
Install Required Packages
Open your terminal and install Flask and the OpenAI Python library:
pip install flask openai
-
Set Your API Key
Make sure you have an API key from OpenAI. Then set it as an environment variable (adjust for your operating system):
- Linux/macOS:
export OPENAI_API_KEY="your_openai_api_key_here"
- Windows (Command Prompt):
set OPENAI_API_KEY=your_openai_api_key_here
- Linux/macOS:
Step 2: Create the Flask Application
Create a file named app.py
with the following content:
import os
from flask import Flask, render_template, request, jsonify
import openai
app = Flask(__name__)
openai.api_key = os.getenv("OPENAI_API_KEY") # Ensure your API key is set
@app.route("/")
def index():
return render_template("index.html")
@app.route("/chat", methods=["POST"])
def chat():
user_message = request.json.get("message")
try:
# Generate a response using the OpenAI API
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo", # Change this if you prefer a different model
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": user_message}
],
max_tokens=150
)
chatbot_reply = response.choices[0].message["content"].strip()
return jsonify({"reply": chatbot_reply})
except Exception as e:
return jsonify({"reply": "Sorry, there was an error: " + str(e)})
if __name__ == "__main__":
app.run(debug=True)
This script sets up two routes:
/
to serve the chat interface./chat
to handle AJAX requests, send the user’s message to the OpenAI API, and return the response.
Step 3: Create the Chat Interface
Inside a folder named templates
(in the same directory as app.py
), create an index.html
file with the following content:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Fancy AI Chatbot</title>
<!-- Bootstrap CSS for a sleek design -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
body { background-color: #f8f9fa; }
.chat-container { max-width: 600px; margin: 50px auto; }
.chat-box { background: #ffffff; padding: 20px; border-radius: 5px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
.message { margin-bottom: 15px; }
.user { text-align: right; }
.bot { text-align: left; }
.message p { display: inline-block; padding: 10px; border-radius: 5px; max-width: 70%; }
.user p { background: #007bff; color: #fff; }
.bot p { background: #e9ecef; color: #343a40; }
</style>
</head>
<body>
<div class="container chat-container">
<div id="chatBox" class="chat-box">
<!-- Chat messages will be appended here -->
</div>
<div class="input-group mt-3">
<input type="text" id="userInput" class="form-control" placeholder="Type your message...">
<div class="input-group-append">
<button class="btn btn-primary" id="sendButton">Send</button>
</div>
</div>
</div>
<!-- jQuery and Bootstrap JS for handling interactions -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
// Append a message to the chat box
function appendMessage(sender, message) {
const messageHTML = '<div class="message ' + sender + '"><p>' + message + '</p></div>';
$('#chatBox').append(messageHTML);
$('#chatBox').scrollTop($('#chatBox')[0].scrollHeight);
}
// Handle the send button click event
$('#sendButton').click(function() {
const userMessage = $('#userInput').val();
if(userMessage.trim() === "") return;
appendMessage("user", userMessage);
$('#userInput').val('');
// Send the message to the server
$.ajax({
url: "/chat",
type: "POST",
contentType: "application/json",
data: JSON.stringify({ message: userMessage }),
success: function(response) {
appendMessage("bot", response.reply);
},
error: function() {
appendMessage("bot", "Sorry, there was an error processing your request.");
}
});
});
// Allow Enter key to send the message
$('#userInput').keypress(function(e) {
if(e.which == 13) {
$('#sendButton').click();
}
});
</script>
</body>
</html>
This HTML file creates:
- A chat window styled with Bootstrap.
- An input field and send button.
- jQuery-powered AJAX calls to send user messages to the
/chat
endpoint and display the AI’s response.
Step 4: Run Your Web Server
Run the Flask app by executing the following command in your terminal:
python app.py
Then, open your browser and navigate to http://127.0.0.1:5000/ to interact with your fancy AI chatbot.
This setup gives you a fully functional web server in Python that hosts a sleek chatbot interface powered by AI. You can further enhance the chatbot’s capabilities or the UI as needed. Happy coding!