tianlong12 commited on
Commit
f91b12b
·
verified ·
1 Parent(s): 16c57b0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -30
app.py CHANGED
@@ -1,4 +1,5 @@
1
  from flask import Flask, request, Response, stream_with_context, jsonify
 
2
  import requests
3
  import json
4
 
@@ -11,20 +12,24 @@ def index():
11
  @app.route('/<path:subpath>', methods=['POST'])
12
  def forward_to_target(subpath):
13
  try:
 
 
 
 
14
  # 获取请求数据
15
  data = request.json
16
  print(f"Request data: {data}") # 调试信息
17
 
18
  # 检查是否是特定路径需要特殊处理
19
- if True:
20
  auth_header = request.headers.get('Authorization')
21
  if not auth_header or not auth_header.startswith('Bearer '):
22
  return jsonify({"error": "Unauthorized"}), 401
23
 
24
  api_key = auth_header.split(" ")[1]
25
- target_url = f"https://{subpath.split('/')[1]}"
26
- print(f"Adjusted target URL for special handling: {target_url}") # 调试信息
27
-
28
  model = data['model']
29
  messages = data['messages']
30
  temperature = data.get('temperature', 0.7) # 默认值0.7
@@ -33,11 +38,7 @@ def forward_to_target(subpath):
33
  stream = data.get('stream', False) # 默认值False
34
  functions = data.get('functions', None) # Functions for function calling
35
  function_call = data.get('function_call', None) # Specific function call request
36
-
37
- headers = {
38
- 'Authorization': f'Bearer {api_key}',
39
- 'Content-Type': 'application/json'
40
- }
41
 
42
  payload = {
43
  'model': model,
@@ -50,30 +51,28 @@ def forward_to_target(subpath):
50
  'function_call': function_call
51
  }
52
  print(f"Payload: {payload}") # 调试信息
53
-
 
 
 
 
 
 
54
  if stream:
 
55
  def generate():
56
- with requests.post(target_url, headers=headers, json=payload, stream=True) as r:
57
- for chunk in r.iter_content(chunk_size=8192):
58
- if chunk:
59
- yield f"data: {chunk.decode('utf-8')}\n\n"
60
- return Response(stream_with_context(generate()), content_type='text/event-stream')
61
- else:
62
- response = requests.post(target_url, headers=headers, json=payload)
63
- response.raise_for_status() # 确保抛出请求错误
64
- return jsonify(response.json())
65
-
66
- else:
67
- # 获取请求头
68
- headers = {key: value for key, value in request.headers if key != 'Host'}
69
- print(f"Headers: {headers}") # 调试信息
70
 
71
- # 转发请求到目标 URL
72
- response = requests.post(target_url, headers=headers, json=data)
73
- response.raise_for_status() # 确保抛出请求错误
74
 
75
- # 返回目标 URL 的响应
76
- return Response(response.content, status=response.status_code, content_type=response.headers['Content-Type'])
 
 
 
 
 
77
 
78
  except requests.exceptions.RequestException as e:
79
  print(f"RequestException: {e}") # 调试信息
@@ -82,5 +81,6 @@ def forward_to_target(subpath):
82
  print(f"Exception: {e}") # 调试信息
83
  return jsonify({"error": str(e)}), 500
84
 
 
85
  if __name__ == "__main__":
86
- app.run(host='0.0.0.0', port=7860, threaded=True)
 
1
  from flask import Flask, request, Response, stream_with_context, jsonify
2
+ from openai import OpenAI
3
  import requests
4
  import json
5
 
 
12
  @app.route('/<path:subpath>', methods=['POST'])
13
  def forward_to_target(subpath):
14
  try:
15
+ # 构建目标 URL
16
+ target_url = f'https://{subpath}'
17
+ print(f"Target URL: {target_url}") # 调试信息
18
+
19
  # 获取请求数据
20
  data = request.json
21
  print(f"Request data: {data}") # 调试信息
22
 
23
  # 检查是否是特定路径需要特殊处理
24
+ if 'v1/chat/completions' in subpath:
25
  auth_header = request.headers.get('Authorization')
26
  if not auth_header or not auth_header.startswith('Bearer '):
27
  return jsonify({"error": "Unauthorized"}), 401
28
 
29
  api_key = auth_header.split(" ")[1]
30
+ #target_url = f"https://{subpath.split('/')[0]}"
31
+ target_url = f"https://{subpath.split('/')[0]}/v1"
32
+ '''
33
  model = data['model']
34
  messages = data['messages']
35
  temperature = data.get('temperature', 0.7) # 默认值0.7
 
38
  stream = data.get('stream', False) # 默认值False
39
  functions = data.get('functions', None) # Functions for function calling
40
  function_call = data.get('function_call', None) # Specific function call request
41
+
 
 
 
 
42
 
43
  payload = {
44
  'model': model,
 
51
  'function_call': function_call
52
  }
53
  print(f"Payload: {payload}") # 调试信息
54
+ '''
55
+ # 创建每个请求的 OpenAI 客户端实例
56
+ client = OpenAI(
57
+ api_key=api_key,
58
+ base_url=target_url
59
+ )
60
+ stream = data.get('stream',False) # 默认值False
61
  if stream:
62
+ # 处理流式响应
63
  def generate():
64
+ response = client.chat.completions.create(**data)
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
+ for chunk in response:
67
+ yield f"data: {json.dumps(chunk)}\n\n"
 
68
 
69
+ return Response(stream_with_context(generate()), content_type='text/event-stream')
70
+ else:
71
+ response = client.chat.completions.create(**data)
72
+ response_dict = response.to_dict() # 转换为字典
73
+ #print(f"Response: {response_dict}") # 调试信息
74
+ return jsonify(response_dict)
75
+
76
 
77
  except requests.exceptions.RequestException as e:
78
  print(f"RequestException: {e}") # 调试信息
 
81
  print(f"Exception: {e}") # 调试信息
82
  return jsonify({"error": str(e)}), 500
83
 
84
+
85
  if __name__ == "__main__":
86
+ app.run(host='0.0.0.0', port=4500, threaded=True)