Introduction
In this tutorial, you'll learn how to build a basic group chat platform similar to Buzz that integrates human and AI agent interactions. This intermediate-level tutorial will guide you through creating a chat interface with AI agent capabilities using Python, Flask, and OpenAI's API. You'll build a foundation for understanding how modern workplace chat platforms integrate AI agents into team conversations.
Prerequisites
- Basic Python programming knowledge
- Familiarity with Flask web framework
- OpenAI API key (available from platform.openai.com)
- Basic understanding of REST APIs and web sockets
- Python virtual environment set up
Step-by-Step Instructions
Step 1: Set Up Your Development Environment
1.1 Create a new Python project directory
First, create a new directory for your project and navigate into it:
mkdir buzz-chat-platform
cd buzz-chat-platform
1.2 Set up a virtual environment
Creating a virtual environment isolates your project dependencies:
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
1.3 Install required packages
Install the necessary Python packages for our chat platform:
pip install flask flask-socketio openai python-dotenv
Why: We're using Flask for the web framework, Flask-SocketIO for real-time communication, OpenAI for AI agent capabilities, and python-dotenv to manage environment variables securely.
Step 2: Configure Environment Variables
2.1 Create a .env file
Create a file named .env in your project root to store your API keys:
OPENAI_API_KEY=your_openai_api_key_here
SECRET_KEY=your_secret_key_for_flask
2.2 Load environment variables in your application
Create a config.py file to load your environment variables:
import os
from dotenv import load_dotenv
load_dotenv()
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
SECRET_KEY = os.getenv('SECRET_KEY')
Why: Storing API keys in environment variables keeps them secure and prevents accidental exposure in version control.
Step 3: Create the Main Flask Application
3.1 Build the basic Flask app structure
Create app.py with the core application structure:
from flask import Flask, render_template
from flask_socketio import SocketIO, emit, join_room, leave_room
import os
from config import OPENAI_API_KEY
app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
socketio = SocketIO(app, cors_allowed_origins="*")
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
socketio.run(app, debug=True)
3.2 Create the HTML template
Create a templates directory and add index.html:
<!DOCTYPE html>
<html>
<head>
<title>Buzz Chat Platform</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
#chat { height: 400px; overflow-y: scroll; border: 1px solid #ccc; padding: 10px; margin-bottom: 10px; }
#messageInput { width: 70%; padding: 10px; }
#sendButton { width: 25%; padding: 10px; }
.message { margin: 5px 0; }
.user { color: blue; }
.ai { color: green; }
</style>
</head>
<body>
<h1>Buzz Chat Platform</h1>
<div id="chat"></div>
<input type="text" id="messageInput" placeholder="Type your message...">
<button id="sendButton">Send</button>
<script>
const socket = io();
const chat = document.getElementById('chat');
const messageInput = document.getElementById('messageInput');
const sendButton = document.getElementById('sendButton');
socket.on('connect', function() {
console.log('Connected to server');
});
socket.on('new_message', function(data) {
const messageDiv = document.createElement('div');
messageDiv.className = 'message ' + data.sender;
messageDiv.innerHTML = '<b>' + data.sender + ':</b> ' + data.text;
chat.appendChild(messageDiv);
chat.scrollTop = chat.scrollHeight;
});
sendButton.onclick = function() {
const message = messageInput.value;
if (message.trim()) {
socket.emit('user_message', { text: message });
messageInput.value = '';
}
};
messageInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
sendButton.click();
}
});
</script>
</body>
</html>
Why: This creates the basic frontend interface with real-time communication capabilities using SocketIO.
Step 4: Implement AI Agent Integration
4.1 Create AI agent service
Create ai_service.py to handle OpenAI interactions:
import openai
from config import OPENAI_API_KEY
openai.api_key = OPENAI_API_KEY
class AIAgent:
def __init__(self):
self.conversation_history = []
def get_response(self, user_message):
# Add user message to conversation history
self.conversation_history.append({"role": "user", "content": user_message})
# Call OpenAI API
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=self.conversation_history,
max_tokens=150,
temperature=0.7
)
ai_response = response.choices[0].message.content.strip()
# Add AI response to conversation history
self.conversation_history.append({"role": "assistant", "content": ai_response})
return ai_response
except Exception as e:
return f"Error: {str(e)}"
4.2 Integrate AI agent with SocketIO
Update your app.py to include AI agent handling:
from flask import Flask, render_template
from flask_socketio import SocketIO, emit, join_room, leave_room
import os
from config import OPENAI_API_KEY
from ai_service import AIAgent
app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
socketio = SocketIO(app, cors_allowed_origins="*")
# Initialize AI agent
ai_agent = AIAgent()
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('user_message')
def handle_user_message(data):
user_message = data['text']
# Emit user message to all clients
emit('new_message', {'sender': 'user', 'text': user_message}, broadcast=True)
# Get AI response
ai_response = ai_agent.get_response(user_message)
# Emit AI response to all clients
emit('new_message', {'sender': 'ai', 'text': ai_response}, broadcast=True)
if __name__ == '__main__':
socketio.run(app, debug=True)
Why: This implementation allows the AI agent to respond to user messages and maintain conversation context, simulating how Buzz would integrate AI agents into team conversations.
Step 5: Run and Test Your Chat Platform
5.1 Start the Flask application
Run your application using:
python app.py
5.2 Test the chat functionality
Open your browser and navigate to http://localhost:5000. You should see the chat interface where you can send messages that will be responded to by both human users and the AI agent.
Why: Testing ensures your real-time communication and AI integration work as expected, providing a foundation for more complex features.
Step 6: Enhance with Additional Features
6.1 Add conversation history persistence
Enhance your ai_service.py to maintain conversation history for each user:
import openai
from config import OPENAI_API_KEY
import uuid
openai.api_key = OPENAI_API_KEY
class AIAgent:
def __init__(self):
self.conversations = {}
def get_response(self, user_message, user_id):
if user_id not in self.conversations:
self.conversations[user_id] = []
# Add user message to conversation history
self.conversations[user_id].append({"role": "user", "content": user_message})
# Call OpenAI API
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=self.conversations[user_id],
max_tokens=150,
temperature=0.7
)
ai_response = response.choices[0].message.content.strip()
# Add AI response to conversation history
self.conversations[user_id].append({"role": "assistant", "content": ai_response})
return ai_response
except Exception as e:
return f"Error: {str(e)}"
Why: Maintaining separate conversation histories per user provides a more realistic chat experience similar to professional platforms.
Summary
In this tutorial, you've built a foundational chat platform that integrates human and AI agent interactions, similar to Buzz. You've learned how to set up a Flask web application with real-time communication using SocketIO, implement AI agent capabilities with OpenAI's API, and create a user-friendly interface. This hands-on experience demonstrates core concepts behind modern workplace chat platforms that blend human collaboration with AI assistance.



