File size: 3,531 Bytes
926730e
 
d7f4cf1
926730e
 
 
 
 
 
c0f152a
 
 
 
 
 
 
 
 
 
 
 
 
926730e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0f152a
926730e
d7f4cf1
7e1ecd0
030b814
 
 
 
 
 
 
 
3771237
d7f4cf1
926730e
 
 
 
 
 
 
 
 
 
 
 
 
 
d7f4cf1
926730e
 
 
030b814
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
from flask import Flask, request, jsonify
import hmac, hashlib, secrets, time
import requests

app = Flask(__name__)

# 🔑 Secret key for API authentication (Load from environment in production)
SECRET_KEY = "MySuperSecretKey_TrueSyncAI"

# Track API statistics
request_count = 0
start_time = time.time()

@app.route('/status', methods=['GET'])
def status():
    global request_count
    uptime = time.time() - start_time
    return jsonify({
        "status": "API is running",
        "total_requests": request_count,
        "uptime_seconds": round(uptime, 2)
    })

# Generate API Key
@app.route("/generate_api_key", methods=["POST"])
def generate_api_key():
    random_part = secrets.token_hex(16)
    signature = hmac.new(SECRET_KEY.encode(), random_part.encode(), hashlib.sha256).hexdigest()[:16]
    api_key = f"TrueSyncAI-{random_part}-{signature}"
    
    return jsonify({"api_key": api_key})

# Validate API Key
def validate_api_key(api_key):
    parts = api_key.split("-")
    if len(parts) != 3 or parts[0] != "TrueSyncAI":
        return False
    
    random_part, received_signature = parts[1], parts[2]
    expected_signature = hmac.new(SECRET_KEY.encode(), random_part.encode(), hashlib.sha256).hexdigest()[:16]
    return expected_signature == received_signature

def generate_response(query:str) -> str:
    json_data = {'model': 'meta-llama/Llama-3.3-70B-Instruct-Turbo', 'messages': [{'role': 'system', 'content': 'You are TrueSyncAI, a pioneering AI startup founded by Sujal Rajpoot and Anuj Rajpoot. The mission of TrueSyncAI is to bring virtual versions of individuals into the real world, redefining human-AI interaction.  \n\nAs TrueSyncAI, you are designed to be intelligent, engaging, and helpful in conversations. You should provide insightful, accurate, and context-aware responses while maintaining a friendly and professional tone. Your goal is to enhance the user’s experience by adapting to their needs, assisting with various tasks, and learning from interactions to improve over time.  \n\nAlways ensure clarity, relevance, and accuracy in your responses, and align with TrueSyncAI’s vision of bridging the gap between virtual intelligence and reality.'}, {'role': 'user', 'content': query}], 'stream': False, 'max_tokens': 2048, 'temperature': 0.2, 'top_p': 1}
    try:
        response = requests.post(
            'https://api.deepinfra.com/v1/openai/chat/completions',
            json=json_data, timeout=None
        )
        response.raise_for_status()
        return response.json().get('choices', [{}])[0].get('message', {}).get('content', "API Server is under maintenance. Please Try After Some Time Thank You for using TrueSyncAI Chat API. Have a great day.")
    except requests.exceptions.RequestException as e:
        return f"API Server is under maintenance. Please Try After Some Time Thank You for using TrueSyncAI Chat API. Have a great day."
    
# Chat Endpoint
@app.route("/chat", methods=["POST"])
def chat():
    data = request.json
    api_key = data.get("api_key")
    message = data.get("message", "").strip()
    
    if not api_key or not validate_api_key(api_key):
        return jsonify({"error": "Invalid API Key"}), 401
    
    if not message:
        return jsonify({"error": "Message cannot be empty"}), 400
    
    # Basic AI response (Can integrate LLMs here)
    response = generate_response(message)
    return jsonify({"response": response})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=7860)  # Hugging Face Spaces default port