Simple AI Chat
body {
font-family: sans-serif;
margin: 20px;
}
#chat-container {
max-width: 600px;
margin: 0 auto;
border: 1px solid #ccc;
border-radius: 5px;
overflow: hidden;
}
#chat-log {
padding: 10px;
height: 300px;
overflow-y: scroll;
background-color: #f9f9f9;
}
.user-message, .ai-message {
padding: 8px 12px;
margin-bottom: 8px;
border-radius: 5px;
clear: both;
}
.user-message {
background-color: #e0f7fa;
float: right;
text-align: right;
}
.ai-message {
background-color: #f0f0f0;
float: left;
}
.input-area {
display: flex;
padding: 10px;
background-color: #eee;
}
#user-input {
flex-grow: 1;
padding: 8px;
border: 1px solid #ccc;
border-radius: 3px;
}
button {
padding: 8px 15px;
margin-left: 10px;
border: none;
border-radius: 3px;
background-color: #007bff;
color: white;
cursor: pointer;
}
const chatLog = document.getElementById('chat-log');
const userInput = document.getElementById('user-input');
function appendMessage(sender, message) {
const messageDiv = document.createElement('div');
messageDiv.classList.add(`${sender}-message`);
messageDiv.textContent = message;
chatLog.appendChild(messageDiv);
chatLog.scrollTop = chatLog.scrollHeight; // Scroll to the bottom
}
async function sendMessage() {
const message = userInput.value.trim();
if (message) {
appendMessage('user', message);
userInput.value = '';
// Show loading indicator (you'd need to implement this visually)
const loadingDiv = document.createElement('div');
loadingDiv.classList.add('ai-message');
loadingDiv.textContent = 'Thinking...';
chatLog.appendChild(loadingDiv);
chatLog.scrollTop = chatLog.scrollHeight;
try {
const response = await fetch('/api/chat', { // Assuming your backend endpoint is /api/chat
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message: message }),
});
const data = await response.json();
// Remove loading indicator
chatLog.removeChild(loadingDiv);
if (data.response) {
appendMessage('ai', data.response);
} else {
appendMessage('ai', 'Error: Could not get response.');
}
} catch (error) {
console.error('Error sending message:', error);
// Remove loading indicator
chatLog.removeChild(loadingDiv);
appendMessage('ai', 'Error: Could not connect to the server.');
}
}
}
// Allow sending message with Enter key
userInput.addEventListener('keypress', function(event) {
if (event.key === 'Enter') {
sendMessage();
}
});
from flask import Flask, request, jsonify
from flask_cors import CORS # For handling cross-origin requests
app = Flask(__name__)
CORS(app) # Enable CORS for development purposes
# Replace with your actual OpenAI API key
OPENAI_API_KEY = "YOUR_OPENAI_API_KEY"
@app.route('/api/chat', methods=['POST'])
def chat():
data = request.get_json()
user_message = data.get('message')
if not user_message:
return jsonify({'error': 'Message is required'}), 400
# --- Here you would integrate with the OpenAI API ---
# Example using a hypothetical openai library:
# try:
# import openai
# openai.api_key = OPENAI_API_KEY
# response = openai.Completion.create(
# model="gpt-3.5-turbo", # Or another suitable model
# prompt=user_message,
# max_tokens=150,
# n=1,
# stop=None,
# temperature=0.7,
# )
# ai_response = response.choices[0].text.strip()
# return jsonify({'response': ai_response})
# except ImportError:
# return jsonify({'response': 'Error: OpenAI library not installed.'})
# except Exception as e:
# return jsonify({'response': f'Error communicating with OpenAI: {str(e)}'})
# --- Placeholder response if OpenAI integration is not done yet ---
ai_response = f"AI response to: '{user_message}' (OpenAI integration pending)"
return jsonify({'response': ai_response})
if __name__ == '__main__':
app.run(debug=True) # Only use debug mode during development
0 Comments