TĐN
Thành Đô Nguyễn

Chat Application Interface - Copy this Html, Tailwind Component to your project

Tạo forntend cực đẹp và phù hợp cho backend này import os import json from flask import Flask, request, jsonify from flask_cors import CORS import g4f from werkzeug.security import generate_password_hash, check_password_hash app = Flask(__name__) CORS(app, resources={ r"/*": { "origins": ["http://ntd.run.place"], "methods": ["GET", "POST", "OPTIONS"], "allow_headers": ["Content Type"] } }) MEMORY_DIR = './memory' if not os.path.exists(MEMORY_DIR): os.makedirs(MEMORY_DIR) def chat_with_g4f(prompt: str, model_choice: str) > str: try: if model_choice == "copilot": response = g4f.ChatCompletion.create( model="Copilot", provider=g4f.Provider.Copilot, messages=[{"role": "user", "content": prompt}] ) return response if isinstance(response, str) else response.choices[0].message.content else: raise ValueError("Invalid model choice") except Exception as e: raise RuntimeError(f"Error communicating with g4f: {str(e)}") @app.route('/register', methods=['POST']) def register(): data = request.json if not data: return jsonify({'error': 'No JSON data provided'}), 400 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 hashed_password = generate_password_hash(password) user_data = {'username': username, 'password': hashed_password} with open(user_file, 'w') as f: json.dump(user_data, f) return jsonify({'message': 'Registration successful'}), 201 @app.route('/login', methods=['POST']) def login(): data = request.json if not data: return jsonify({'error': 'No JSON data provided'}), 400 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 does not exist'}), 404 with open(user_file, 'r') as f: user_data = json.load(f) if not check_password_hash(user_data['password'], password): return jsonify({'error': 'Incorrect password'}), 401 # Tạo luồng chat mới ngay sau khi đăng nhập chat_id = save_chat_history(username, '', '', None) chat_history = get_chat_history(username) return jsonify({ 'message': 'Login successful', 'chat_history': chat_history, 'new_chat_id': chat_id # Trả về ID luồng mới }), 200 @app.route('/chat', methods=['POST']) def chat(): data = request.json if not data: return jsonify({'error': 'No JSON data provided'}), 400 username = data.get('username') user_prompt = data.get('prompt') model_choice = data.get('modelChoice', 'copilot') chat_id = data.get('chat_id') 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 does not exist'}), 404 try: context = "" if chat_id: chat_history = get_chat_history_by_id(username, int(chat_id)) if chat_history: # Lấy tối đa 5 tin nhắn gần nhất để làm ngữ cảnh context = " ".join([f"{msg['prompt']} {msg['response']}" for msg in chat_history[ 5:]]) # Kết hợp ngữ cảnh và prompt mới full_prompt = f"{context}\nUser: {user_prompt}" if context else user_prompt # Gửi đến mô hình g4f response = chat_with_g4f(full_prompt, model_choice) # Lưu lại lịch sử chat chat_id = save_chat_history(username, user_prompt, response, chat_id) return jsonify({'response': response, 'chat_id': chat_id}), 200 except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/load_chat', methods=['POST']) def load_chat(): username = request.json.get('username') chat_id = request.json.get('chat_id') if not chat_id: return jsonify({'error': 'chat_id is required'}), 400 chat_history = get_chat_history(username, chat_id) # Hàm này sẽ trả về lịch sử trò chuyện từ cơ sở dữ liệu if not chat_history: return jsonify({'error': 'No chat history found'}), 404 return jsonify({'chat_history': chat_history}) @app.route('/api/delete_chat', methods=['POST']) def delete_chat(): data = request.json if not data: return jsonify({'error': 'No JSON data provided'}), 400 username = data.get('username') chat_id = data.get('chat_id') if not username or not chat_id: return jsonify({'error': 'Username and chat ID are required'}), 400 chat_file = os.path.join(MEMORY_DIR, f'{username}_chat_history.json') if not os.path.exists(chat_file): return jsonify({'error': 'No chat history found'}), 404 with open(chat_file, 'r') as f: chat_history = json.load(f) # Tìm luồng chat updated_chats = [] chat_deleted = False for chat in chat_history: if chat['chat_id'] == int(chat_id): # Chỉ xóa nếu luồng rỗng (không có prompt/response) if len(chat['history']) == 0: chat_deleted = True else: updated_chats.append(chat) else: updated_chats.append(chat) if not chat_deleted: return jsonify({'error': 'Chat is not empty or does not exist'}), 404 with open(chat_file, 'w') as f: json.dump(updated_chats, f) return jsonify({'message': 'Chat deleted successfully'}), 200 @app.route('/list chats', methods=['POST']) def list_chats(): data = request.json if not data: return jsonify({'error': 'No JSON data provided'}), 400 username = data.get('username') if not username: return jsonify({'error': 'Username is required'}), 400 chat_file = os.path.join(MEMORY_DIR, f'{username}_chat_history.json') if os.path.exists(chat_file): with open(chat_file, 'r') as f: chat_history = json.load(f) chat_list = [{'chat_id': chat['chat_id'], 'preview': chat['history'][0]['prompt'][:50] + '...'} for chat in chat_history if chat['history']] return jsonify({'chats': chat_list}), 200 else: return jsonify({'chats': []}), 200 @app.route('/chat_history', methods=['POST']) def get_chat_history_route(): data = request.json if not data: return jsonify({'error': 'No JSON data provided'}), 400 username = data.get('username') chat_id = data.get('chat_id') if not username or not chat_id: return jsonify({'error': 'Username and chat ID are required'}), 400 chat_history = get_chat_history_by_id(username, int(chat_id)) if chat_history: return jsonify({'chat_id': chat_id, 'history': chat_history}), 200 else: return jsonify({'error': 'Chat history not found'}), 404 def save_chat_history(username, user_prompt, response, chat_id=None): chat_file = os.path.join(MEMORY_DIR, f'{username}_chat_history.json') if os.path.exists(chat_file): with open(chat_file, 'r') as f: chat_history = json.load(f) else: chat_history = [] if chat_id: chat_id = int(chat_id) for chat in chat_history: if chat['chat_id'] == chat_id: chat['history'].append({'prompt': user_prompt, 'response': response}) break else: chat_history.append({ 'chat_id': chat_id, 'history': [{'prompt': user_prompt, 'response': response}] }) else: new_chat_id = max([chat['chat_id'] for chat in chat_history], default=0) + 1 chat_history.append({ 'chat_id': new_chat_id, 'history': [{'prompt': user_prompt, 'response': response}] }) chat_id = new_chat_id with open(chat_file, 'w') as f: json.dump(chat_history, f) return chat_id def get_chat_history(username): chat_file = os.path.join(MEMORY_DIR, f'{username}_chat_history.json') if os.path.exists(chat_file): with open(chat_file, 'r') as f: return json.load(f) return [] def get_chat_history_by_id(username, chat_id): chat_file = os.path.join(MEMORY_DIR, f'{username}_chat_history.json') if os.path.exists(chat_file): with open(chat_file, 'r') as f: chat_history = json.load(f) for chat in chat_history: if chat['chat_id'] == chat_id: return chat['history'] return [] @app.route('/health', methods=['GET']) def health_check(): return jsonify({"status": "ok"}), 200 @app.route('/api/version', methods=['GET']) def get_version(): return jsonify({"version": "1.1.0"}), 200 @app.route('/new chat', methods=['POST']) def new_chat(): data = request.json if not data: return jsonify({'error': 'No JSON data provided'}), 400 username = data.get('username') initial_message = data.get('initial_message', '') if not username: return jsonify({'error': 'Username is required'}), 400 chat_file = os.path.join(MEMORY_DIR, f'{username}_chat_history.json') if os.path.exists(chat_file): with open(chat_file, 'r') as f: chat_history = json.load(f) new_chat_id = max([chat['chat_id'] for chat in chat_history], default=0) + 1 else: new_chat_id = 1 chat_history = [] if initial_message: response = chat_with_g4f(initial_message, 'copilot') chat_history.append({ 'chat_id': new_chat_id, 'history': [{'prompt': initial_message, 'response': response}] }) else: # Nếu không có initial_message, tạo luồng rỗng chat_history.append({ 'chat_id': new_chat_id, 'history': [] }) with open(chat_file, 'w') as f: json.dump(chat_history, f) return jsonify({'chat_id': new_chat_id, 'initial_response': response if initial_message else None}), 200 if __name__ == '__main__': app.run(host='0.0.0.0', port=5000, debug=True)

Prompt
Component Preview

About

Chat Application Interface - Create a stunning chat UI with user registration, secure login, and chat history management, built with htm. Start coding now!

Share

Last updated 1 month ago