at41rv commited on
Commit
bec5ea1
·
verified ·
1 Parent(s): 35bb06b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -0
app.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify
2
+ import os
3
+ import requests # To forward requests to your original host
4
+
5
+ app = Flask(__name__)
6
+
7
+ # Retrieve secrets from environment variables
8
+ # This is the API key your *website* will send to this Hugging Face Space API
9
+ SPACE_API_KEY = os.environ.get("SPACE_API_KEY")
10
+ # This is the API key for your *original host*
11
+ ORIGINAL_HOST_API_KEY = os.environ.get("ORIGINAL_API_KEY")
12
+
13
+ @app.route("/chat/completions", methods=["POST"])
14
+ def chat_completions_proxy():
15
+ # 1. Authenticate Request from Your Website
16
+ client_api_key = request.headers.get("X-API-Key") # Or Authorization: Bearer <key>
17
+
18
+ if not client_api_key or client_api_key != SPACE_API_KEY:
19
+ return jsonify({"detail": "Unauthorized: Invalid Space API Key"}), 401
20
+
21
+ # 2. Get data from your website's request
22
+ try:
23
+ data = request.json
24
+ prompt = data.get("prompt")
25
+ model = data.get("model")
26
+ if not prompt or not model:
27
+ return jsonify({"detail": "Missing 'prompt' or 'model' in request"}), 400
28
+ except Exception as e:
29
+ return jsonify({"detail": f"Invalid JSON or request body: {str(e)}"}), 400
30
+
31
+ # 3. Forward Request to Your Original Host
32
+ original_host_url = "https://your-original-host.com/api/chat" # Replace with your original API endpoint
33
+ headers = {
34
+ "Content-Type": "application/json",
35
+ "Authorization": f"Bearer {ORIGINAL_HOST_API_KEY}" # Or whatever auth your original API uses
36
+ }
37
+ payload = {
38
+ "model": model,
39
+ "messages": [{"role": "user", "content": prompt}] # Adapt to your original API's expected payload
40
+ }
41
+
42
+ try:
43
+ response = requests.post(original_host_url, json=payload, headers=headers)
44
+ response.raise_for_status() # Raise an exception for HTTP errors
45
+ original_api_response = response.json()
46
+ return jsonify(original_api_response), 200
47
+ except requests.exceptions.RequestException as e:
48
+ return jsonify({"detail": f"Error communicating with original host: {str(e)}"}), 500
49
+ except Exception as e:
50
+ return jsonify({"detail": f"An unexpected error occurred: {str(e)}"}), 500
51
+
52
+ if __name__ == "__main__":
53
+ app.run(debug=os.environ.get("DEBUG", "False").lower() == "true", host="0.0.0.0", port=int(os.environ.get("PORT", 7860))) # Default Gradio port