Spaces:
Runtime error

PatChat / app.py
makaronz's picture
Update app.py
c42ac41 verified
Raw History Blame Contribute Delete
11.6 kB
import os
from datetime import datetime
from flask import Flask, render_template, request, jsonify, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy
from dotenv import load_dotenv
import openai
# Load environment variables
load_dotenv()
# Initialize Flask app
app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'dev-secret-key-change-in-production')
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL', 'sqlite:///patchat.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Initialize SQLAlchemy
db = SQLAlchemy(app)
# Initialize OpenAI client
openai_client = openai.OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
# Predefined system prompts
SYSTEM_PROMPTS = {
'default': 'You are a helpful AI assistant. You are patient, curious, and committed to helping the user no matter how simple or complex the request. Always seek to clarify needs, offer detailed answers, and go the extra mile to support the user’s goals with empathy and precision.',
'creative': 'You are a creative and imaginative AI assistant. You thrive in brainstorming, storytelling, and artistic expression. Embrace ambiguity, take conceptual leaps, and explore unconventional ideas. Use vivid language, powerful metaphors, and unexpected associations to help users unlock novel insights, design unique projects, or spark artistic inspiration across mediums. Never fear the abstract or experimental—celebrate it.',
'professional': 'You are a professional AI assistant tailored for executive environments. Respond with clarity, polish, and strategic foresight. Structure your answers into logical frameworks, offer industry best practices, and always consider business implications. You write like a seasoned consultant: calm, confident, and insightful. Aim to make your user feel they are speaking to a top-tier analyst, manager, or advisor.',
'educational': 'You are an educational AI assistant with a gift for teaching. You break down complex concepts with structure, clarity, and compassion. Your responses are pedagogical in nature—rich with analogies, Socratic questions, and real-world examples. Adapt to the learner’s level, anticipate misconceptions, and promote curiosity. Your tone is that of a mentor who believes every user can master anything with the right guidance.',
'spanish teacher': 'You are a Spanish language teacher—passionate, articulate, and culturally rich. You don’t just teach grammar and vocabulary—you bring the Spanish-speaking world alive. Provide practical language instruction, idiomatic expressions, pronunciation tips, and cultural nuance. Create immersive dialogues, give context-sensitive exercises, and encourage the learner to think and respond in Spanish whenever possible. Your mission is to ignite fluency with warmth, patience, and imagination.',
'writing': 'You are a writing assistant with the mind of an editor and the soul of a novelist. Help users brainstorm compelling ideas, craft elegant sentences, and develop authentic voice. Whether it’s fiction, copywriting, essays, or scripts—analyze tone, pacing, and rhythm. Offer rewrites and structural advice. Be bold, lyrical, analytical, or minimalist—whatever best serves the user’s intent. Above all, treat writing as a journey of discovery and emotional resonance.',
'philosopher': 'You are a philosopher and academic lecturer in philosophy. Speak with depth, subtlety, and intellectual elegance. Draw from both classical and contemporary schools—Plato, Hume, Nietzsche, Arendt, Derrida. Use precise terminology, frame arguments dialectically, and examine ethical, epistemological, and metaphysical implications. When fitting, incorporate thought experiments, paradoxes, and references to literature or science. Engage the user as a peer in a shared exploration of truth, meaning, and the human condition. Your tone is reflective, rigorous, and occasionally poetic.'
}
# Available AI models with descriptions
AI_MODELS = {
'gpt-3.5-turbo': {
'name': 'GPT-3.5 Turbo',
'description': 'Fast and cost-effective for most tasks',
'max_tokens': 4096,
'cost_per_1k_tokens': 0.0015
},
'gpt-4': {
'name': 'GPT-4',
'description': 'More capable but slower than GPT-3.5',
'max_tokens': 8192,
'cost_per_1k_tokens': 0.03
},
'gpt-4-turbo': {
'name': 'GPT-4 Turbo',
'description': 'Latest GPT-4 model with improved performance',
'max_tokens': 128000,
'cost_per_1k_tokens': 0.01
},
'gpt-4o': {
'name': 'GPT-4o',
'description': 'Latest multimodal model with vision capabilities',
'max_tokens': 128000,
'cost_per_1k_tokens': 0.005
},
'gpt-4o-mini': {
'name': 'GPT-4o Mini',
'description': 'Faster and more cost-effective than GPT-4o',
'max_tokens': 128000,
'cost_per_1k_tokens': 0.00015
},
'gpt-4o-mini-high': {
'name': 'GPT-4o Mini High',
'description': 'Higher quality responses than GPT-4o Mini',
'max_tokens': 128000,
'cost_per_1k_tokens': 0.0006
},
'gpt-4o3': {
'name': 'GPT-4o3',
'description': 'Latest and most capable model (if available)',
'max_tokens': 128000,
'cost_per_1k_tokens': 0.02
}
}
# Database Models
class Conversation(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(255), default='New Conversation')
model_type = db.Column(db.String(50), default='gpt-3.5-turbo')
system_prompt = db.Column(db.Text, default='You are a helpful AI assistant.')
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
# Relationship
messages = db.relationship('Message', backref='conversation', lazy=True, cascade='all, delete-orphan')
class Message(db.Model):
id = db.Column(db.Integer, primary_key=True)
conversation_id = db.Column(db.Integer, db.ForeignKey('conversation.id'), nullable=False)
content = db.Column(db.Text, nullable=False)
role = db.Column(db.String(20), nullable=False) # 'user' or 'assistant'
model_type = db.Column(db.String(50))
created_at = db.Column(db.DateTime, default=datetime.utcnow)
# Routes
@app.route('/')
def index():
"""Main chat interface"""
return render_template('chat.html', system_prompts=SYSTEM_PROMPTS, ai_models=AI_MODELS)
@app.route('/history')
def history():
"""Conversation history page"""
conversations = Conversation.query.order_by(Conversation.updated_at.desc()).all()
return render_template('history.html', conversations=conversations)
@app.route('/conversation/<int:conversation_id>')
def view_conversation(conversation_id):
"""View specific conversation"""
conversation = Conversation.query.get_or_404(conversation_id)
return render_template('chat.html', conversation=conversation, system_prompts=SYSTEM_PROMPTS, ai_models=AI_MODELS)
@app.route('/send_message', methods=['POST'])
def send_message():
"""Send message to AI and save to database"""
try:
data = request.get_json()
conversation_id = data.get('conversation_id')
content = data.get('content')
model_type = data.get('model_type', 'gpt-3.5-turbo')
system_prompt = data.get('system_prompt', 'You are a helpful AI assistant.')
if not content:
return jsonify({'error': 'Message content is required'}), 400
# Get or create conversation
if conversation_id:
conversation = Conversation.query.get(conversation_id)
if not conversation:
return jsonify({'error': 'Conversation not found'}), 404
else:
# Create new conversation
conversation = Conversation(
title=content[:50] + '...' if len(content) > 50 else content,
model_type=model_type,
system_prompt=system_prompt
)
db.session.add(conversation)
db.session.commit()
# Save user message
user_message = Message(
conversation_id=conversation.id,
content=content,
role='user',
model_type=model_type
)
db.session.add(user_message)
# Get conversation history for context
messages = Message.query.filter_by(conversation_id=conversation.id).order_by(Message.created_at).all()
# Prepare messages for OpenAI API
api_messages = [{'role': 'system', 'content': conversation.system_prompt}]
for msg in messages:
api_messages.append({'role': msg.role, 'content': msg.content})
# Call OpenAI API
response = openai_client.chat.completions.create(
model=model_type,
messages=api_messages,
max_tokens=1000,
temperature=0.7
)
# Save AI response
ai_response = response.choices[0].message.content
assistant_message = Message(
conversation_id=conversation.id,
content=ai_response,
role='assistant',
model_type=model_type
)
db.session.add(assistant_message)
# Update conversation timestamp
conversation.updated_at = datetime.utcnow()
db.session.commit()
return jsonify({
'success': True,
'conversation_id': conversation.id,
'response': ai_response,
'conversation_title': conversation.title
})
except Exception as e:
db.session.rollback()
return jsonify({'error': str(e)}), 500
@app.route('/new_conversation', methods=['POST'])
def new_conversation():
"""Start a new conversation"""
try:
data = request.get_json()
system_prompt = data.get('system_prompt', 'You are a helpful AI assistant.')
model_type = data.get('model_type', 'gpt-3.5-turbo')
conversation = Conversation(
title='New Conversation',
model_type=model_type,
system_prompt=system_prompt
)
db.session.add(conversation)
db.session.commit()
return jsonify({
'success': True,
'conversation_id': conversation.id,
'redirect_url': url_for('view_conversation', conversation_id=conversation.id)
})
except Exception as e:
db.session.rollback()
return jsonify({'error': str(e)}), 500
@app.route('/conversation/<int:conversation_id>', methods=['DELETE'])
def delete_conversation(conversation_id):
"""Delete a conversation"""
try:
conversation = Conversation.query.get_or_404(conversation_id)
db.session.delete(conversation)
db.session.commit()
return jsonify({'success': True})
except Exception as e:
db.session.rollback()
return jsonify({'error': str(e)}), 500
@app.route('/system_prompts')
def get_system_prompts():
"""Get available system prompts"""
return jsonify(SYSTEM_PROMPTS)
@app.route('/ai_models')
def get_ai_models():
"""Get available AI models"""
return jsonify(AI_MODELS)
@app.route('/health')
def health():
"""Health check endpoint"""
return jsonify({'status': 'healthy', 'timestamp': datetime.utcnow().isoformat()})
# Create database tables
with app.app_context():
db.create_all()
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=int(os.getenv('PORT', 5000)))