Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
from fastapi import FastAPI, HTTPException, Request
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
import httpx
|
| 4 |
import os
|
|
@@ -21,7 +21,7 @@ app.add_middleware(
|
|
| 21 |
|
| 22 |
# 配置
|
| 23 |
class Config:
|
| 24 |
-
OPENAI_API_BASE = "https://api.x.ai/v1"
|
| 25 |
KEYS_URL = os.getenv("KEYS_URL", "")
|
| 26 |
WHITELIST_IPS = os.getenv("WHITELIST_IPS", "").split(",")
|
| 27 |
|
|
@@ -62,23 +62,49 @@ def get_next_key():
|
|
| 62 |
raise HTTPException(status_code=500, detail="No API keys available")
|
| 63 |
return next(key_cycle)
|
| 64 |
|
| 65 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
@app.api_route("/api/v1/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
|
| 67 |
async def proxy(path: str, request: Request):
|
| 68 |
# 获取请求体
|
| 69 |
body = await request.body()
|
|
|
|
|
|
|
| 70 |
# 获取查询参数
|
| 71 |
params = dict(request.query_params)
|
| 72 |
-
|
|
|
|
| 73 |
headers = dict(request.headers)
|
| 74 |
headers.pop("host", None)
|
| 75 |
-
|
| 76 |
-
# 设置API key
|
| 77 |
headers["Authorization"] = f"Bearer {get_next_key()}"
|
|
|
|
| 78 |
|
| 79 |
# 构建目标URL
|
| 80 |
url = f"{Config.OPENAI_API_BASE}/{path}"
|
| 81 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
async with httpx.AsyncClient() as client:
|
| 83 |
try:
|
| 84 |
response = await client.request(
|
|
@@ -86,13 +112,38 @@ async def proxy(path: str, request: Request):
|
|
| 86 |
url=url,
|
| 87 |
params=params,
|
| 88 |
headers=headers,
|
| 89 |
-
content=
|
| 90 |
)
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
except Exception as e:
|
| 93 |
-
print(f"Error: {str(e)}")
|
| 94 |
raise HTTPException(status_code=500, detail=str(e))
|
| 95 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
# 启动时初始化
|
| 97 |
@app.on_event("startup")
|
| 98 |
async def startup_event():
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException, Request, Response
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
import httpx
|
| 4 |
import os
|
|
|
|
| 21 |
|
| 22 |
# 配置
|
| 23 |
class Config:
|
| 24 |
+
OPENAI_API_BASE = "https://api.x.ai/v1"
|
| 25 |
KEYS_URL = os.getenv("KEYS_URL", "")
|
| 26 |
WHITELIST_IPS = os.getenv("WHITELIST_IPS", "").split(",")
|
| 27 |
|
|
|
|
| 62 |
raise HTTPException(status_code=500, detail="No API keys available")
|
| 63 |
return next(key_cycle)
|
| 64 |
|
| 65 |
+
# 模型列表路由
|
| 66 |
+
@app.get("/api/v1/models")
|
| 67 |
+
async def list_models():
|
| 68 |
+
headers = {
|
| 69 |
+
"Authorization": f"Bearer {get_next_key()}",
|
| 70 |
+
"Content-Type": "application/json"
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
async with httpx.AsyncClient() as client:
|
| 74 |
+
try:
|
| 75 |
+
response = await client.get(
|
| 76 |
+
f"{Config.OPENAI_API_BASE}/models",
|
| 77 |
+
headers=headers
|
| 78 |
+
)
|
| 79 |
+
return response.json()
|
| 80 |
+
except Exception as e:
|
| 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 ""
|
| 90 |
+
|
| 91 |
# 获取查询参数
|
| 92 |
params = dict(request.query_params)
|
| 93 |
+
|
| 94 |
+
# 获取并处理headers
|
| 95 |
headers = dict(request.headers)
|
| 96 |
headers.pop("host", None)
|
|
|
|
|
|
|
| 97 |
headers["Authorization"] = f"Bearer {get_next_key()}"
|
| 98 |
+
headers["Content-Type"] = "application/json"
|
| 99 |
|
| 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(
|
|
|
|
| 112 |
url=url,
|
| 113 |
params=params,
|
| 114 |
headers=headers,
|
| 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)}")
|
| 140 |
raise HTTPException(status_code=500, detail=str(e))
|
| 141 |
|
| 142 |
+
# 健康检查路由
|
| 143 |
+
@app.get("/api/health")
|
| 144 |
+
async def health_check():
|
| 145 |
+
return {"status": "healthy", "key_count": len(keys)}
|
| 146 |
+
|
| 147 |
# 启动时初始化
|
| 148 |
@app.on_event("startup")
|
| 149 |
async def startup_event():
|