Spaces:
Sleeping
Sleeping
update
Browse files- .gitignore +2 -0
- app.py +52 -2
.gitignore
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.env
|
| 2 |
+
__pycache__/
|
app.py
CHANGED
|
@@ -1,7 +1,57 @@
|
|
| 1 |
-
|
| 2 |
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
@app.get("/")
|
| 6 |
def greet_json():
|
| 7 |
return {"Hello": "World!"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# uvicorn app:app --host 0.0.0.0 --port 7860 --reload
|
| 2 |
|
| 3 |
+
from fastapi import FastAPI, Request, HTTPException
|
| 4 |
+
import requests
|
| 5 |
+
import os
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
|
| 8 |
+
# 加载环境变量(存储Gemini API密钥)
|
| 9 |
+
load_dotenv()
|
| 10 |
+
app = FastAPI(title="Gemini Proxy API")
|
| 11 |
|
| 12 |
@app.get("/")
|
| 13 |
def greet_json():
|
| 14 |
return {"Hello": "World!"}
|
| 15 |
+
|
| 16 |
+
# 1. 配置Gemini真实信息
|
| 17 |
+
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") # 从环境变量获取密钥
|
| 18 |
+
GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta/models" # Gemini真实Base URL
|
| 19 |
+
|
| 20 |
+
# 2. 通用转发接口(匹配Gemini的/predict等端点,路径动态匹配)
|
| 21 |
+
@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
|
| 22 |
+
async def proxy_gemini(request: Request, path: str):
|
| 23 |
+
# 拼接Gemini真实请求URL(如客户端访问 /models/gemini-pro:generateContent → 转发到Gemini的对应路径)
|
| 24 |
+
gemini_url = f"{GEMINI_BASE_URL}/{path}?key={GEMINI_API_KEY}"
|
| 25 |
+
|
| 26 |
+
# 提取客户端请求的headers和body,透传给Gemini
|
| 27 |
+
client_headers = dict(request.headers)
|
| 28 |
+
# 移除FastAPI自带的Host头,避免Gemini校验报错
|
| 29 |
+
client_headers.pop("host", None)
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
# 读取客户端请求体
|
| 33 |
+
client_body = await request.body()
|
| 34 |
+
|
| 35 |
+
# 向Gemini发起请求(转发)
|
| 36 |
+
response = requests.request(
|
| 37 |
+
method=request.method,
|
| 38 |
+
url=gemini_url,
|
| 39 |
+
headers=client_headers,
|
| 40 |
+
data=client_body,
|
| 41 |
+
timeout=30 # 超时时间,可调整
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
# 将Gemini的响应透传给客户端
|
| 45 |
+
return Response(
|
| 46 |
+
content=response.content,
|
| 47 |
+
status_code=response.status_code,
|
| 48 |
+
headers=dict(response.headers)
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
except Exception as e:
|
| 52 |
+
raise HTTPException(status_code=500, detail=f"转发失败:{str(e)}")
|
| 53 |
+
|
| 54 |
+
# 3. 健康检查接口(可选,用于验证服务是否正常)
|
| 55 |
+
@app.get("/health")
|
| 56 |
+
async def health_check():
|
| 57 |
+
return {"status": "ok", "proxy_target": "Google Gemini"}
|