azr43l commited on
Commit
851c519
1 Parent(s): ea2326d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -0
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Your url for ST will be something like this:
2
+ # https://username-spaceName.hf.space/proxy/anthropic/v1
3
+ # Streaming is not supported
4
+
5
+ import logging
6
+ import json
7
+ from flask import Flask, request, Response
8
+ import requests
9
+
10
+ app = Flask(__name__)
11
+
12
+ # Configure the logging level
13
+ app.logger.setLevel(logging.INFO)
14
+
15
+ @app.route('/', defaults={'path': ''})
16
+ @app.route('/<path:path>', methods=['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
17
+ def relay_request(path):
18
+ # Extract the base URL to relay requests
19
+ base_url = 'https://claude.ai' # Replace with the URL you want to relay requests to
20
+
21
+ # Prepare the relay URL by appending the path from the original request
22
+ relay_url = base_url + '/' + path
23
+
24
+ app.logger.info(request.headers)
25
+
26
+ # If the request is an EventStream request, use the stream method
27
+ if request.headers.get('Content-Type') == 'text/event-stream':
28
+ response = requests.request(
29
+ method=request.method,
30
+ url=relay_url,
31
+ headers=request.headers,
32
+ allow_redirects=False,
33
+ stream=True # Enable streaming response
34
+ )
35
+ headers = [(name, value) for name, value in response.raw.headers.items()]
36
+
37
+ def generate():
38
+ for chunk in response.iter_content(chunk_size=8192):
39
+ yield chunk
40
+
41
+ return Response(generate(), response.status_code, headers)
42
+
43
+ # Remove the original IP from the headers
44
+ headers = {k: v for k, v in request.headers.items() if k != 'X-Forwarded-For'}
45
+
46
+ # If the request includes JSON data, relay it as JSON
47
+ if 'application/json' in request.headers.get('Content-Type', ''):
48
+ data = request.get_json()
49
+ response = requests.request(
50
+ method=request.method,
51
+ url=relay_url,
52
+ headers=headers,
53
+ json=data,
54
+ allow_redirects=False
55
+ )
56
+ else:
57
+ response = requests.request(
58
+ method=request.method,
59
+ url=relay_url,
60
+ headers=headers,
61
+ data=request.data,
62
+ allow_redirects=False
63
+ )
64
+
65
+ # Prepare the response to return to the original API call
66
+ headers = [(name, value) for name, value in response.headers.items() if name != 'Transfer-Encoding']
67
+ return Response(response.content, response.status_code, headers)
68
+
69
+ if __name__ == '__main__':
70
+ app.run(host='0.0.0.0', port=7860)