bobocup commited on
Commit
329cee1
·
verified ·
1 Parent(s): 4fdfbb7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -24
app.py CHANGED
@@ -1,11 +1,13 @@
1
  from fastapi import FastAPI, HTTPException, Request, Response
2
  from fastapi.middleware.cors import CORSMiddleware
 
3
  import httpx
4
  import os
5
  import json
6
  from typing import List, Optional
7
  import requests
8
  from itertools import cycle
 
9
 
10
  # 创建FastAPI应用
11
  app = FastAPI()
@@ -81,9 +83,73 @@ async def list_models():
81
  print(f"Models Error: {str(e)}")
82
  raise HTTPException(status_code=500, detail=str(e))
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  # 代理其他请求到X.AI
85
  @app.api_route("/api/v1/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
86
  async def proxy(path: str, request: Request):
 
 
 
87
  # 获取请求体
88
  body = await request.body()
89
  body_str = body.decode() if body else ""
@@ -100,11 +166,6 @@ async def proxy(path: str, request: Request):
100
  # 构建目标URL
101
  url = f"{Config.OPENAI_API_BASE}/{path}"
102
 
103
- print(f"Proxying request to: {url}")
104
- print(f"Method: {request.method}")
105
- print(f"Headers: {headers}")
106
- print(f"Body: {body_str}")
107
-
108
  async with httpx.AsyncClient() as client:
109
  try:
110
  response = await client.request(
@@ -115,25 +176,11 @@ async def proxy(path: str, request: Request):
115
  content=body_str if body_str else None
116
  )
117
 
118
- # 获取响应内容
119
- response_content = response.text
120
- print(f"Response status: {response.status_code}")
121
- print(f"Response content: {response_content}")
122
-
123
- # 尝试解析JSON响应
124
- try:
125
- return Response(
126
- content=response_content,
127
- status_code=response.status_code,
128
- headers=dict(response.headers)
129
- )
130
- except json.JSONDecodeError as e:
131
- print(f"JSON decode error: {str(e)}")
132
- return Response(
133
- content=response_content,
134
- status_code=response.status_code,
135
- headers=dict(response.headers)
136
- )
137
 
138
  except Exception as e:
139
  print(f"Proxy Error: {str(e)}")
 
1
  from fastapi import FastAPI, HTTPException, Request, Response
2
  from fastapi.middleware.cors import CORSMiddleware
3
+ from fastapi.responses import StreamingResponse
4
  import httpx
5
  import os
6
  import json
7
  from typing import List, Optional
8
  import requests
9
  from itertools import cycle
10
+ import asyncio
11
 
12
  # 创建FastAPI应用
13
  app = FastAPI()
 
83
  print(f"Models Error: {str(e)}")
84
  raise HTTPException(status_code=500, detail=str(e))
85
 
86
+ # 流式响应生成器
87
+ async def stream_generator(response):
88
+ async for chunk in response.aiter_bytes():
89
+ yield chunk
90
+
91
+ # 聊天完成路由
92
+ @app.post("/api/v1/chat/completions")
93
+ async def chat_completions(request: Request):
94
+ # 获取请求体
95
+ body = await request.body()
96
+ body_json = json.loads(body)
97
+
98
+ # 获取headers
99
+ headers = {
100
+ "Authorization": f"Bearer {get_next_key()}",
101
+ "Content-Type": "application/json",
102
+ "Accept": "text/event-stream" if body_json.get("stream") else "application/json"
103
+ }
104
+
105
+ # 构建目标URL
106
+ url = f"{Config.OPENAI_API_BASE}/chat/completions"
107
+
108
+ print(f"Chat request to: {url}")
109
+ print(f"Headers: {headers}")
110
+ print(f"Body: {json.dumps(body_json)}")
111
+
112
+ async with httpx.AsyncClient() as client:
113
+ try:
114
+ response = await client.post(
115
+ url,
116
+ headers=headers,
117
+ json=body_json,
118
+ timeout=60.0
119
+ )
120
+
121
+ # 检查响应状态
122
+ if response.status_code != 200:
123
+ print(f"Error response: {response.status_code} - {response.text}")
124
+ return Response(
125
+ content=response.text,
126
+ status_code=response.status_code,
127
+ media_type=response.headers.get("content-type", "application/json")
128
+ )
129
+
130
+ # 处理流式响应
131
+ if body_json.get("stream"):
132
+ return StreamingResponse(
133
+ stream_generator(response),
134
+ media_type="text/event-stream"
135
+ )
136
+
137
+ # 处理普通响应
138
+ return Response(
139
+ content=response.text,
140
+ media_type=response.headers.get("content-type", "application/json")
141
+ )
142
+
143
+ except Exception as e:
144
+ print(f"Chat Error: {str(e)}")
145
+ raise HTTPException(status_code=500, detail=str(e))
146
+
147
  # 代理其他请求到X.AI
148
  @app.api_route("/api/v1/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
149
  async def proxy(path: str, request: Request):
150
+ if path == "chat/completions":
151
+ return await chat_completions(request)
152
+
153
  # 获取请求体
154
  body = await request.body()
155
  body_str = body.decode() if body else ""
 
166
  # 构建目标URL
167
  url = f"{Config.OPENAI_API_BASE}/{path}"
168
 
 
 
 
 
 
169
  async with httpx.AsyncClient() as client:
170
  try:
171
  response = await client.request(
 
176
  content=body_str if body_str else None
177
  )
178
 
179
+ return Response(
180
+ content=response.text,
181
+ status_code=response.status_code,
182
+ headers=dict(response.headers)
183
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
 
185
  except Exception as e:
186
  print(f"Proxy Error: {str(e)}")