smgc commited on
Commit
fcbf0b1
1 Parent(s): 0ba087d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -70
app.py CHANGED
@@ -1,60 +1,37 @@
 
1
  from flask import Flask, request, Response
2
  import requests
3
  import json
4
- import os
5
- import sys
6
- import logging
7
- from helper import create_jwt
8
 
9
  app = Flask(__name__)
10
 
11
- # 配置日志
12
- logging.basicConfig(
13
- level=logging.INFO,
14
- format='%(asctime)s [%(levelname)s] %(message)s',
15
- handlers=[
16
- logging.StreamHandler(sys.stdout)
17
- ]
18
- )
19
- logger = logging.getLogger(__name__)
20
-
21
  @app.route('/chat/completions', methods=['POST'])
22
- def chat():
23
  """
24
  Handle chat completion requests.
 
 
 
 
 
 
 
 
 
 
 
 
25
  """
26
- logger.info("=== Received chat completion request ===")
27
-
28
- # 记录请求信息
29
- logger.info(f"Request method: {request.method}")
30
- logger.info(f"Request URL: {request.url}")
31
- logger.info(f"Request headers: {json.dumps(dict(request.headers), indent=2)}")
32
-
33
  # Get the payload from the request
34
  payload = request.json
35
- logger.info(f"Request payload: {json.dumps(payload, indent=2)}")
36
 
37
  # Get the model from the payload, defaulting to "claude-3-5-sonnet-20240620"
38
  model = payload.get('model', 'claude-3-5-sonnet-20240620')
39
- logger.info(f"Using model: {model}")
40
-
41
- # Extract GitHub username and Zed user ID from Authorization header
42
- auth_header = request.headers.get('Authorization')
43
- if not auth_header or not auth_header.startswith('Bearer '):
44
- logger.error("Invalid Authorization header")
45
- return Response('Invalid Authorization header', status=401)
46
-
47
- try:
48
- github_username, zed_user_id = auth_header[7:].split(',')
49
- logger.info(f"Extracted GitHub username: {github_username}")
50
- logger.info(f"Extracted Zed user ID: {zed_user_id}")
51
- except ValueError:
52
- logger.error("Invalid Authorization header format")
53
- return Response('Invalid Authorization header format', status=401)
54
 
55
  # Prepare the request for the LLM API
56
- url = "https://llm.zed.dev/completion"
57
- logger.info(f"LLM API URL: {url}")
58
 
59
  llm_payload = {
60
  "provider": "anthropic",
@@ -68,10 +45,9 @@ def chat():
68
  "system": ""
69
  }
70
  }
71
- logger.info(f"LLM API payload: {json.dumps(llm_payload, indent=2)}")
72
 
73
- jwt = create_jwt(github_username, int(zed_user_id))
74
- logger.info(f"Generated JWT token: {jwt}")
75
 
76
  headers = {
77
  'Host': 'llm.zed.dev',
@@ -80,40 +56,22 @@ def chat():
80
  'authorization': f'Bearer {jwt}',
81
  'user-agent': 'Zed/0.149.3 (macos; aarch64)'
82
  }
83
- logger.info(f"Request headers for LLM API: {json.dumps(headers, indent=2)}")
84
 
85
  # Get proxy from environment variable
86
  proxy = os.environ.get('HTTP_PROXY', None)
87
  proxies = {'http': proxy, 'https': proxy} if proxy else None
88
- logger.info(f"Using proxy: {proxy}")
89
 
90
- def generate():
91
- try:
92
- logger.info("Sending request to LLM API")
93
- with requests.post(url, headers=headers, json=llm_payload, stream=True, proxies=proxies, allow_redirects=True) as response:
94
- logger.info(f"LLM API response status: {response.status_code}")
95
- logger.info(f"LLM API response headers: {json.dumps(dict(response.headers), indent=2)}")
96
-
97
- if response.status_code == 301:
98
- new_location = response.headers.get('Location')
99
- logger.warning(f"Received 301 redirect. New location: {new_location}")
100
- # 如果需要,可以在这里处理重定向
101
-
102
- for chunk in response.iter_content(chunk_size=1024):
103
- if chunk:
104
- logger.debug(f"Received chunk of size: {len(chunk)} bytes")
105
- yield chunk
106
- except Exception as e:
107
- logger.error(f"Error during API request: {str(e)}")
108
- yield str(e).encode()
109
 
110
- logger.info("Returning streaming response")
111
  return Response(generate(), content_type='application/octet-stream')
112
 
113
- @app.route('/', methods=['GET'])
114
- def home():
115
- logger.info("Received request to home page")
116
- return "Welcome to the Chat Completion API", 200
117
 
118
  if __name__ == '__main__':
119
- app.run(host='0.0.0.0', port=8000)
 
 
1
+ from asgiref.wsgi import WsgiToAsgi
2
  from flask import Flask, request, Response
3
  import requests
4
  import json
5
+ import random
6
+ from helper import create_jwt, get_github_username_zed_userid_list
 
 
7
 
8
  app = Flask(__name__)
9
 
 
 
 
 
 
 
 
 
 
 
10
  @app.route('/chat/completions', methods=['POST'])
11
+ async def chat():
12
  """
13
  Handle chat completion requests.
14
+
15
+ This function processes incoming POST requests to the '/chat/completions' endpoint.
16
+ It prepares the payload for the LLM API, generates a JWT for authentication,
17
+ and streams the response from the LLM API back to the client.
18
+
19
+ Returns:
20
+ Response: A streaming response containing the LLM API's output.
21
+
22
+ Note:
23
+ - The function uses environment variables for proxy configuration.
24
+ - It generates random GitHub username and Zed user ID for each request.
25
+ - The LLM model defaults to "claude-3-5-sonnet-20240620" if not specified.
26
  """
 
 
 
 
 
 
 
27
  # Get the payload from the request
28
  payload = request.json
 
29
 
30
  # Get the model from the payload, defaulting to "claude-3-5-sonnet-20240620"
31
  model = payload.get('model', 'claude-3-5-sonnet-20240620')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
  # Prepare the request for the LLM API
34
+ url = "https://llm.zed.dev/completion?"
 
35
 
36
  llm_payload = {
37
  "provider": "anthropic",
 
45
  "system": ""
46
  }
47
  }
 
48
 
49
+ github_username, zed_user_id = get_github_username_zed_userid_list()
50
+ jwt = create_jwt(github_username, zed_user_id)
51
 
52
  headers = {
53
  'Host': 'llm.zed.dev',
 
56
  'authorization': f'Bearer {jwt}',
57
  'user-agent': 'Zed/0.149.3 (macos; aarch64)'
58
  }
 
59
 
60
  # Get proxy from environment variable
61
  proxy = os.environ.get('HTTP_PROXY', None)
62
  proxies = {'http': proxy, 'https': proxy} if proxy else None
 
63
 
64
+ async def generate():
65
+ with requests.post(url, headers=headers, json=llm_payload, stream=True, proxies=proxies) as response:
66
+ for chunk in response.iter_content(chunk_size=1024):
67
+ if chunk:
68
+ yield chunk
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
 
70
  return Response(generate(), content_type='application/octet-stream')
71
 
72
+ # Convert the Flask app to an ASGI app
73
+ asgi_app = WsgiToAsgi(app)
 
 
74
 
75
  if __name__ == '__main__':
76
+ import uvicorn
77
+ uvicorn.run(asgi_app, host="0.0.0.0", port=8000)