File size: 4,746 Bytes
8602315
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# 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.
@app.route('/')
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 ---

@app.route('/api/train-chatbot', methods=['POST'])
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

@app.route('/api/chatbot-status/<string:chatbot_uuid>', methods=['GET'])
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

@app.route('/api/chat', methods=['POST'])
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)