How to Create an AI-Powered Customer Support Widget
In this tutorial, we'll create an AI-powered customer support widget using the Wingman Protocol API. This widget will allow users to interact with an AI to get instant support on your website. We'll use Python for the backend, Flask as the web framework, and a simple HTML/CSS/JavaScript frontend.
Prerequisites
1. Python 3.7+ installed on your machine. 2. Basic knowledge of Python, Flask, HTML, CSS, and JavaScript. 3. An API key from Wingman Protocol (sign up at api.wingmanprotocol.com).
Project Structure
ai_support_widget/
│
├─ app.py
├─ static/
│ ├─ style.css
│ └─ script.js
│
├─ templates/
│ └─ index.html
│
└─ requirements.txt
⚡ Get 5 free AI guides + weekly insights
Step 1: Set Up the Flask Application
First, create a virtual environment and install the required packages.
python -m venv venv
source venv/bin/activate # On Windows use `venv\Scripts\activate`
pip install Flask requests
Create a requirements.txt file with the following content:
Flask==2.3.2
requests==2.31.0
Create a file named app.py and set up a basic Flask application.
from flask import Flask, render_template, request, jsonify
import requests
app = Flask(__name__)
WINGMAN_API_KEY = 'your_api_key_here'
WINGMAN_API_URL = 'https://api.wingmanprotocol.com/v1/chat'
@app.route('/')
def index():
return render_template('index.html')
@app.route('/api/chat', methods=['POST'])
def chat():
user_message = request.json.get('message')
if not user_message:
return jsonify({'error': 'No message provided'}), 400
headers = {
'Authorization': f'Bearer {WINGMAN_API_KEY}',
'Content-Type': 'application/json',
}
data = {
'message': user_message,
}
try:
response = requests.post(WINGMAN_API_URL, headers=headers, json=data)
response.raise_for_status()
ai_response = response.json().get('response')
return jsonify({'response': ai_response})
except requests.exceptions.RequestException as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(debug=True)
Step 2: Create the Frontend
Create a directory named templates and inside it, create a file named index.html.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Support Widget</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<div id="chat-widget">
<div id="chat-header">
<h2>AI Support</h2>
</div>
<div id="chat-messages"></div>
<div id="chat-input">
<input type="text" id="user-input" placeholder="Type your message...">
<button id="send-button">Send</button>
</div>
</div>
<script src="{{ url_for('static', filename='script.js') }}"></script>
</body>
</html>
Create a directory named static and inside it, create a file named style.css.
#chat-widget {
width: 300px;
height: 400px;
border: 1px solid #ccc;
border-radius: 5px;
position: fixed;
bottom: 20px;
right: 20px;
display: flex;
flex-direction: column;
}
#chat-header {
background-color: #007bff;
color: white;
padding: 10px;
border-radius: 5px 5px 0 0;
text-align: center;
}
#chat-messages {
flex-grow: 1;
padding: 10px;
overflow-y: auto;
}
#chat-input {
display: flex;
border-top: 1px solid #ccc;
padding: 10px;
}
#user-input {
flex-grow: 1;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px 0 0 5px;
}
#send-button {
padding: 10px;
border: 1px solid #ccc;
border-radius: 0 5px 5px 0;
background-color: #007bff;
color: white;
cursor: pointer;
}
#send-button:hover {
background-color: #0056b3;
}
Create a file named script.js inside the static directory.
document.getElementById('send-button').addEventListener('click', sendMessage);
function sendMessage() {
const userInput = document.getElementById('user-input');
const message = userInput.value;
if (message.trim() === '') return;
const chatMessages = document.getElementById('chat-messages');
chatMessages.innerHTML += `<div><strong>You:</strong> ${message}</div>`;
userInput.value = '';
fetch('/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message }),
})
.then(response => response.json())
.then(data => {
if (data.error) {
chatMessages.innerHTML += `<div class="error">Error: ${data.error}</div>`;
} else {
chatMessages.innerHTML += `<div><strong>AI:</strong> ${data.response}</div>`;
}
})
.catch(error => {
chatMessages.innerHTML += `<div class="error">Error: ${error}</div>`;
});
chatMessages.scrollTop = chatMessages.scrollHeight;
}
Step 3: Run the Application
Run your Flask application using the following command:
python app.py
Open your browser and navigate to http://127.0.0.1:5000/. You should see the AI support widget, and you can start interacting with the AI.
⚡ Get 5 free AI guides + weekly insights
Best Practices
1. Error Handling: Always handle errors gracefully. In the provided code, we handle errors from the Wingman API and display them to the user. 2. Security: Never expose your API key in the frontend. Always keep it secure on the server-side. 3. Input Validation: Validate user inputs to prevent injection attacks and other security vulnerabilities. 4. Scalability: Consider using a message queue (e.g., RabbitMQ, Kafka) for handling high traffic and ensuring reliable message delivery.
Next Steps
1. Deployment: Deploy your application to a cloud provider like AWS, Heroku, or Google Cloud. 2. Customization: Customize the widget's appearance and behavior to match your website's design and requirements. 3. Advanced Features: Implement additional features like user authentication, conversation history, and sentiment analysis.
Ready to get started? Sign up at api.wingmanprotocol.com to get your API key and start building your AI-powered customer support widget today!