Download app.py from Smartlyqofficial/testchatbot: direct link, hf CLI and curl.
- Browser
- Download file 4.75 kB
-
https://huggingface.co/spaces/Smartlyqofficial/testchatbot/resolve/main/app.py
- Command line
-
hf download hf://spaces/Smartlyqofficial/testchatbot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Smartlyqofficial/testchatbot/resolve/main/app.py
4.75 kB
| # app.py (Complete Final Version) | |
| from flask import Flask, request, jsonify | |
| from celery.result import AsyncResult | |
| import redis | |
| from celery_worker import celery_app | |
| from tasks import process_and_embed_data | |
| from chat_logic import get_vector_store, get_llm, create_rag_chain_with_history, format_chat_history | |
| app = Flask(__name__) | |
| # Correct Redis URL with SSL configuration for Celery | |
| REDIS_URL = "rediss://default:AR_OAAImcDFjYjFjODg2MDdlYTI0NmY1OTc3MzMxNGM3MzU5MDgwMnAxODE0Mg@guiding-firefly-8142.upstash.io:6379?ssl_cert_reqs=CERT_NONE" | |
| # Connect to your remote Upstash database | |
| redis_client = redis.from_url(REDIS_URL, decode_responses=True) | |
| # --- HEALTH CHECK ENDPOINT --- | |
| # This is required by Hugging Face to confirm the app is running. | |
| def health_check(): | |
| """ | |
| This endpoint is for the Hugging Face health check. | |
| It tells the platform that the app is running correctly. | |
| """ | |
| return jsonify({"status": "healthy", "message": "Application is running."}), 200 | |
| # --- API ENDPOINTS --- | |
| def train_chatbot(): | |
| data = request.get_json() | |
| if not data or 'chatbot_uuid' not in data or 'openai_api_key' not in data: | |
| return jsonify({"success": False, "status": "Error", "message": "Invalid request. 'chatbot_uuid' and 'openai_api_key' are required."}), 400 | |
| chatbot_uuid = data['chatbot_uuid'] | |
| task = process_and_embed_data.delay(data) | |
| redis_client.set(f"chatbot_status:{chatbot_uuid}", task.id) | |
| return jsonify({"success": True, "status": "Processing", "message": "Training process started successfully.","data": {"chatbot_uuid": chatbot_uuid, "task_id": task.id}}), 202 | |
| def get_chatbot_status(chatbot_uuid): | |
| task_id = redis_client.get(f"chatbot_status:{chatbot_uuid}") | |
| if not task_id: | |
| return jsonify({"success": False, "status": "Not Found", "message": "No training process found for this chatbot UUID."}), 404 | |
| result = AsyncResult(task_id, app=celery_app) | |
| status_message = "Processing" | |
| if result.state == 'SUCCESS': status_message = "Complete" | |
| elif result.state == 'FAILURE': status_message = "Failed" | |
| response_data = {"success": True, "status": status_message, "data": {"chatbot_uuid": chatbot_uuid, "task_id": task_id, "celery_state": result.state}} | |
| if result.state == 'SUCCESS': | |
| response_data['data']['training_stats'] = result.get() | |
| elif result.state == 'FAILURE': | |
| response_data['success'] = False | |
| response_data['message'] = "An error occurred during processing." | |
| response_data['data']['error_info'] = str(result.info) | |
| return jsonify(response_data), 200 | |
| def chat_with_bot(): | |
| data = request.get_json() | |
| required_fields = ['chatbot_uuid', 'api_provider', 'api_model', 'api_key', 'message'] | |
| if not all(field in data for field in required_fields): | |
| return jsonify({"success": False, "message": f"Missing required fields. Required: {required_fields}"}), 400 | |
| chatbot_uuid = data['chatbot_uuid'] | |
| stored_openai_key = redis_client.get(f"chatbot_key:{chatbot_uuid}") | |
| if not stored_openai_key: | |
| return jsonify({"success": False, "message": f"Could not find a stored API key for chatbot '{chatbot_uuid}'. Has it been trained successfully?"}), 404 | |
| question = data['message'] | |
| previous_chat = data.get('previous_chat', []) | |
| behavior = data.get('behavior', 'You are a helpful expert assistant.') | |
| try: | |
| vector_store = get_vector_store(chatbot_uuid, stored_openai_key) | |
| if vector_store is None: | |
| return jsonify({"success": False, "message": f"No trained data for chatbot '{chatbot_uuid}'."}), 404 | |
| llm = get_llm(data['api_provider'], data['api_model'], data['api_key']) | |
| rag_chain = create_rag_chain_with_history(vector_store, llm, behavior) | |
| formatted_history = format_chat_history(previous_chat) | |
| full_answer = rag_chain.invoke({"question": question, "chat_history": formatted_history, "behavior": behavior}) | |
| response_payload = { | |
| "success": True, | |
| "data": { | |
| "user_id": data.get('user_id'), "chatbot_id": data.get('chatbot_id'), "chatbot_uuid": chatbot_uuid, | |
| "chat_id": data.get('chat_id'), "question": question, "answer": full_answer | |
| } | |
| } | |
| return jsonify(response_payload), 200 | |
| except Exception as e: | |
| return jsonify({"success": False, "message": f"An unexpected error occurred: {str(e)}"}), 500 | |
| if __name__ == '__main__': | |
| app.run(host='0.0.0.0', port=5001, debug=False) |