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