tanbushi commited on
Commit
e084365
·
verified ·
1 Parent(s): 03f3ced

Upload 3 files

Browse files
Files changed (3) hide show
  1. Dockerfile +16 -0
  2. app.py +112 -0
  3. requirements.txt +5 -0
Dockerfile ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Read the doc: https://huggingface.co/docs/hub/spaces-sdks-docker
2
+ # you will also find guides on how best to write your Dockerfile
3
+
4
+ FROM python:3.9
5
+
6
+ RUN useradd -m -u 1000 user
7
+ USER user
8
+ ENV PATH="/home/user/.local/bin:$PATH"
9
+
10
+ WORKDIR /app
11
+
12
+ COPY --chown=user ./requirements.txt requirements.txt
13
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
14
+
15
+ COPY --chown=user . /app
16
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
app.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # uvicorn app:app --host 0.0.0.0 --port 7860 --reload
2
+
3
+ from fastapi import FastAPI, Request, HTTPException, Depends, status
4
+ from fastapi.responses import Response # 导入Response
5
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials # 导入HTTPBearer和HTTPAuthorizationCredentials
6
+ import httpx # 使用httpx替代requests,因为requests是同步的,而FastAPI是异步的
7
+ import os, json
8
+ from dotenv import load_dotenv
9
+ from enum import Enum
10
+
11
+ # 加载环境变量
12
+ load_dotenv()
13
+
14
+ # 从环境变量获取代理自身的API密钥
15
+ proxy_api_key = os.getenv("PROXY_API_KEY")
16
+
17
+ # 定义HTTPBearer安全方案
18
+ security = HTTPBearer()
19
+
20
+ # 枚举校验协议类型
21
+ class ProtocolType(str, Enum):
22
+ HTTP = "http"
23
+ HTTPS = "https"
24
+
25
+ # 依赖函数:验证代理的API密钥
26
+ def verify_proxy_api_key(credentials: HTTPAuthorizationCredentials = Depends(security)):
27
+ if not proxy_api_key or credentials.credentials != proxy_api_key:
28
+ raise HTTPException(
29
+ status_code=status.HTTP_401_UNAUTHORIZED,
30
+ detail="Invalid or missing proxy API key",
31
+ headers={"WWW-Authenticate": "Bearer"},
32
+ )
33
+ return credentials.credentials
34
+
35
+ app = FastAPI(title="Gemini Proxy API")
36
+
37
+ @app.get("/")
38
+ def greet_json():
39
+ return {"Hello": "World!"}
40
+
41
+ # 3. 健康检查接口(可选,用于验证服务是否正常)
42
+ @app.get("/health")
43
+ async def health_check():
44
+ return {"status": "ok", "message": "Proxy service is running."}
45
+
46
+ gemini_api_keys_str = os.getenv("GEMINI_API_KEYS_STR")
47
+ try:
48
+ gemini_api_keys_arr = json.loads(gemini_api_keys_str)
49
+ except json.JSONDecodeError as e:
50
+ print(f"JSON 解析错误:{e}")
51
+ gemini_api_keys_arr = [] # 解析失败时设置默认值
52
+ except Exception as e:
53
+ print(f"其他错误:{e}")
54
+ gemini_api_keys_arr = []
55
+
56
+ key_index = 0
57
+ keys_count = len(gemini_api_keys_arr)
58
+
59
+ @app.api_route("/v1/{protocol}/{host}/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
60
+ # @app.api_route("/v1/{protocol}/{host}/{path:path}", methods=["POST"])
61
+ async def proxy_gemini(request: Request, protocol: ProtocolType, host:str, path: str, proxy_api_key: str = Depends(verify_proxy_api_key)): # 添加代理认证依赖
62
+ global key_index # 声明使用全局变量
63
+ real_url = f"{protocol.value}://{host}/{path}"
64
+
65
+ # 提取客户端请求的headers和body,透传给Gemini
66
+ client_headers = dict(request.headers)
67
+
68
+ # 移除FastAPI自带的Host头,避免Gemini校验报错
69
+ client_headers.pop("host", None)
70
+
71
+ # 将User-Agent改为curl/8.7.1,以模拟curl请求
72
+ client_headers["User-Agent"] = "curl/8.7.1"
73
+
74
+ # 添加Authorization头,用于Gemini的OpenAI兼容API
75
+ if gemini_api_keys_arr: # 确保有可用的API密钥
76
+ print(f"key_index: {key_index}")
77
+ gemini_api_key = gemini_api_keys_arr[key_index]
78
+ key_index = (key_index + 1) % keys_count
79
+ print(f"next_key_index: {key_index}")
80
+ client_headers["Authorization"] = f"Bearer {gemini_api_key}"
81
+ elif gemini_api_key: # 如果没有API密钥列表,使用单个API密钥
82
+ client_headers["Authorization"] = f"Bearer {gemini_api_key}"
83
+ else:
84
+ raise HTTPException(status_code=500, detail="No Gemini API keys configured.")
85
+
86
+ try:
87
+ # 读取客户端请求体
88
+ client_body = await request.body()
89
+
90
+ # 使用httpx异步客户端发起请求
91
+ async with httpx.AsyncClient() as client:
92
+ response = await client.request(
93
+ method=request.method,
94
+ url=real_url,
95
+ headers=client_headers,
96
+ content=client_body, # httpx使用content参数传递请求体
97
+ timeout=30 # 超时时间,可调整
98
+ )
99
+
100
+ # 将Gemini的响应透传给客户端
101
+ return Response(
102
+ content=response.content,
103
+ status_code=response.status_code,
104
+ headers=dict(response.headers)
105
+ )
106
+
107
+ except httpx.RequestError as e:
108
+ raise HTTPException(status_code=500, detail=f"转发请求失败:{str(e)}")
109
+ except httpx.HTTPStatusError as e:
110
+ raise HTTPException(status_code=e.response.status_code, detail=f"目标API返回错误:{e.response.text}")
111
+ except Exception as e:
112
+ raise HTTPException(status_code=500, detail=f"转发失败:{str(e)}")
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn[standard]
3
+ httpx
4
+ python-dotenv
5
+ python-jose