Chat Application Interface - Copy this Html, Tailwind Component to your project
Hãy thiết kế thêm các chức năng và liên kết với back end dựa vào from flask import Flask, request, jsonify, render_template import g4f import os import json from flask_cors import CORS import spacy from textblob import TextBlob # Khởi tạo Flask app app = Flask(__name__) CORS(app, resources={r"/*": { "origins": ["http://ntd.run.place"], "methods": ["GET", "POST", "OPTIONS"], "allow_headers": ["Content Type"] }}) # Thư mục lưu file JSON MEMORY_DIR = './memory' if not os.path.exists(MEMORY_DIR): os.makedirs(MEMORY_DIR) # Tải mô hình spaCy nlp = spacy.load("en_core_web_sm") # Hàm phân tích ý định def analyze_intent(message): doc = nlp(message) intents = [token.lemma_ for token in doc if token.pos_ in ["VERB", "NOUN"] and not token.is_stop] return intents # Hàm tạo tên đoạn chat def generate_chat_name(prompt): intents = analyze_intent(prompt) if intents: return " ".join(intents[:3]) # Ghép 3 ý chính đầu tiên làm tên đoạn chat return "New Chat" # Hàm phân tích cảm xúc def analyze_sentiment(text): blob = TextBlob(text) polarity = blob.sentiment.polarity sentiment = "positive" if polarity > 0 else "negative" if polarity < 0 else "neutral" return sentiment, polarity # Hàm tối ưu hóa prompt def refine_prompt(user_prompt, history=None): context = "" if history: # Chỉ lấy các đoạn chat có liên quan để giảm dư thừa relevant_history = [ msg for chat in history for msg in chat["messages"] if user_prompt.lower() in msg["content"].lower() ] # Lấy tối đa 200 ký tự cho mỗi tin nhắn context = "\n\n".join([f"{msg['role']}: {msg['content'][:200]}" for msg in relevant_history]) refined_prompt = ( "Bạn là trợ lý thông minh, cung cấp câu trả lời chi tiết, có ví dụ cụ thể và dễ hiểu." f"\n\nNgữ cảnh trước đó:\n{context}\n\n" f"Người dùng hỏi: {user_prompt}. Trả lời chi tiết và logic." ) return refined_prompt # Hàm sử dụng g4f để tạo phản hồi def chat_with_g4f(prompt, model_choice, history=None): try: refined_prompt = refine_prompt(prompt, history) if model_choice == "copilot": model = "Copilot" provider = g4f.Provider.Copilot else: raise ValueError(f"Model {model_choice} không hợp lệ") messages = [{"role": "user", "content": refined_prompt}] response = g4f.ChatCompletion.create( model=model, provider=provider, messages=messages ) if isinstance(response, str): return response elif hasattr(response, 'choices') and response.choices: return response.choices[0].message.content else: raise ValueError("Unexpected response format from API") except Exception as e: raise RuntimeError(f"Error communicating with g4f: {str(e)}") @app.route('/') def index(): return render_template('index.html') @app.route('/register', methods=['POST']) def register(): data = request.json username = data.get('username') password = data.get('password') if not username or not password: return jsonify({'error': 'Username and password are required'}), 400 user_file = os.path.join(MEMORY_DIR, f'{username}.json') if os.path.exists(user_file): return jsonify({'error': 'Username already exists'}), 400 user_data = { 'username': username, 'password': password, 'chats': [] } with open(user_file, 'w') as f: json.dump(user_data, f) return jsonify({'message': 'User registered successfully'}), 201 @app.route('/login', methods=['POST']) def login(): data = request.json username = data.get('username') password = data.get('password') if not username or not password: return jsonify({'error': 'Username and password are required'}), 400 user_file = os.path.join(MEMORY_DIR, f'{username}.json') if not os.path.exists(user_file): return jsonify({'error': 'User not found'}), 404 with open(user_file, 'r') as f: user_data = json.load(f) if user_data['password'] != password: return jsonify({'error': 'Incorrect password'}), 401 return jsonify({'message': 'Login successful'}), 200 @app.route('/chat', methods=['POST']) def chat(): data = request.json username = data.get('username') user_prompt = data.get('prompt') model_choice = data.get('modelChoice', 'copilot') if not username or not user_prompt: return jsonify({'error': 'Username and prompt are required'}), 400 user_file = os.path.join(MEMORY_DIR, f'{username}.json') if not os.path.exists(user_file): return jsonify({'error': 'User not found'}), 404 with open(user_file, 'r') as f: user_data = json.load(f) try: # Lấy lịch sử gần nhất previous_chats = user_data['chats'][ 3:] if user_data.get('chats') else [] response = chat_with_g4f(user_prompt, model_choice, previous_chats) # Kiểm tra lặp nội dung for chat in previous_chats: for message in chat['messages']: if message['content'] == response: response = "Câu trả lời này đã được cung cấp trước đó. Vui lòng đặt câu hỏi khác." break chat_name = generate_chat_name(user_prompt) # Tạo gợi ý sau câu trả lời def generate_suggestions(prompt, response): suggestions = [ "Bạn muốn tôi giải thích thêm về chủ đề này không?", "Hãy cung cấp thêm thông tin để tôi có thể giúp bạn tốt hơn.", "Bạn cần hỗ trợ thêm về phần nào?" ] if "code" in prompt.lower() or "programming" in prompt.lower(): suggestions.extend([ "Bạn có muốn xem thêm ví dụ mã nguồn không?", "Tôi có thể giúp bạn debug mã của mình, hãy chia sẻ đoạn code của bạn.", "Bạn cần gợi ý tài liệu học lập trình không?" ]) elif "problem" in prompt.lower() or "issue" in prompt.lower(): suggestions.extend([ "Hãy mô tả chi tiết hơn về vấn đề bạn gặp phải.", "Bạn có muốn tôi đề xuất các cách giải quyết khác không?", "Tôi có thể giải thích khái niệm liên quan nếu bạn cần." ]) return suggestions chat_entry = { "name": chat_name, "messages": [ {"role": "user", "content": user_prompt}, {"role": "assistant", "content": response} ] } user_data['chats'].append(chat_entry) with open(user_file, 'w') as f: json.dump(user_data, f) return jsonify({ 'response': response, 'chat_name': chat_name, 'suggestions': suggestions }) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/chat/history', methods=['GET']) def chat_history(): username = request.args.get('username') chat_name = request.args.get('chat_name', None) if not username: return jsonify({'error': 'Username is required'}), 400 user_file = os.path.join(MEMORY_DIR, f'{username}.json') if not os.path.exists(user_file): return jsonify({'error': 'User not found'}), 404 with open(user_file, 'r') as f: user_data = json.load(f) chats = user_data.get('chats', []) if chat_name: chats = [chat for chat in chats if chat['name'] == chat_name] if not chats: return jsonify({'error': 'Chat not found'}), 404 return jsonify({'chats': chats}), 200 @app.route('/chats', methods=['GET']) def list_chats(): username = request.args.get('username') if not username: return jsonify({'error': 'Username is required'}), 400 user_file = os.path.join(MEMORY_DIR, f'{username}.json') if not os.path.exists(user_file): return jsonify({'error': 'User not found'}), 404 with open(user_file, 'r') as f: user_data = json.load(f) chats = [ { "name": chat["name"], "preview": chat["messages"][0]["content"] if chat["messages"] else "No messages" } for chat in user_data.get('chats', []) ] return jsonify({'chats': chats}), 200 @app.route('/health', methods=['GET']) def health_check(): return jsonify({"status": "ok"}), 200 if __name__ == '__main__': app.run(host='0.0.0.0', port=5000, debug=True)