tanbushi commited on
Commit
1911aee
·
1 Parent(s): db5a981
Files changed (1) hide show
  1. app.py +17 -7
app.py CHANGED
@@ -1,8 +1,9 @@
1
  # uvicorn app:app --host 0.0.0.0 --port 7860 --reload
2
 
3
- from fastapi import FastAPI, Request, HTTPException
4
- import re
5
  import httpx
 
6
 
7
  app = FastAPI()
8
 
@@ -38,17 +39,26 @@ async def proxy_url(dest_url: str, request: Request):
38
  if response.status_code == 200:
39
  # 检查响应内容类型是否为 JSON
40
  if 'application/json' in response.headers.get('content-type', ''):
41
- return response.json()
 
 
 
 
 
 
42
  else:
43
- return {"error": "Response is not in JSON format"}
44
  else:
45
  # 将错误响应转换为 JSON 格式并返回给客户端
46
  try:
47
  error_data = response.json()
 
48
  except ValueError:
49
- error_data = {"status_code": response.status_code, "detail": response.text}
50
- return error_data
 
 
51
 
52
  except httpx.RequestError as e:
53
  # 处理请求错误
54
- raise HTTPException(status_code=500, detail=str(e))
 
1
  # uvicorn app:app --host 0.0.0.0 --port 7860 --reload
2
 
3
+ from fastapi import FastAPI, Request, HTTPException, Response
4
+ import re, json
5
  import httpx
6
+ import uuid
7
 
8
  app = FastAPI()
9
 
 
39
  if response.status_code == 200:
40
  # 检查响应内容类型是否为 JSON
41
  if 'application/json' in response.headers.get('content-type', ''):
42
+ json_response = response.json()
43
+ json_response['id'] = f"chatcmpl-{uuid.uuid4()}"
44
+ # resp = Response(content=str(json_response), media_type="application/json")
45
+ # resp = Response(content=str(json_response), media_type="application/json")
46
+ resp = Response(content=json.dumps(json_response), media_type="application/json")
47
+ resp.headers["Access-Control-Allow-Origin"] = "*"
48
+ return resp
49
  else:
50
+ return {"error": "Response is not in JSON format", "id": f"chatcmpl-{uuid.uuid4()}"}
51
  else:
52
  # 将错误响应转换为 JSON 格式并返回给客户端
53
  try:
54
  error_data = response.json()
55
+ error_data['id'] = f"chatcmpl-{uuid.uuid4()}"
56
  except ValueError:
57
+ error_data = {"status_code": response.status_code, "detail": response.text, "id": f"chatcmpl-{uuid.uuid4()}"}
58
+ resp = Response(content=str(error_data), media_type="application/json")
59
+ resp.headers["Access-Control-Allow-Origin"] = "*"
60
+ return resp
61
 
62
  except httpx.RequestError as e:
63
  # 处理请求错误
64
+ raise HTTPException(status_code=500, detail=str(e))