Spaces:
Sleeping

ebdpxy / simple_proxy.py
paperplane22's picture
Update simple_proxy.py
7151903 verified
Raw History Blame Contribute Delete
7.05 kB
from fastapi import FastAPI, Request, HTTPException, Depends, Header
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi.responses import JSONResponse
import httpx
import json
from datetime import datetime
import os
import logging
from typing import Optional
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)
app = FastAPI(title="Embedding Proxy API", version="1.0.0")
# 配置
FDROID_API_URL = os.getenv("EMBEDDING_ENDPOINT", "https://xxxx.com")
PORT = int(os.getenv("PORT", 7860)) # HuggingFace 默认端口
AUTH_TOKEN = os.getenv("AUTH_TOKEN", "your-secret-token-here") # 从环境变量读取认证令牌
# HTTP Bearer 认证
security = HTTPBearer()
# HTTP 客户端
http_client = httpx.AsyncClient(
timeout=httpx.Timeout(60.0, connect=10.0),
limits=httpx.Limits(max_keepalive_connections=5, max_connections=10),
verify=False
)
# 请求统计
stats = {
"total_requests": 0,
"successful_requests": 0,
"failed_requests": 0,
"unauthorized_requests": 0
}
def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)) -> bool:
"""验证 Bearer Token"""
if credentials.credentials != AUTH_TOKEN:
stats["unauthorized_requests"] += 1
logger.warning(f"Unauthorized access attempt with token: {credentials.credentials[:10]}...")
raise HTTPException(
status_code=401,
detail="Invalid authentication token",
headers={"WWW-Authenticate": "Bearer"},
)
return True
# 可选:从 Authorization header 直接获取 token
async def get_bearer_token(authorization: Optional[str] = Header(None)) -> str:
"""从 Authorization header 获取 token"""
if not authorization:
stats["unauthorized_requests"] += 1
logger.warning("Missing authorization header")
raise HTTPException(
status_code=401,
detail="Missing authorization header",
headers={"WWW-Authenticate": "Bearer"},
)
try:
scheme, token = authorization.split()
if scheme.lower() != "bearer":
raise ValueError("Invalid authentication scheme")
except ValueError:
stats["unauthorized_requests"] += 1
logger.warning("Invalid authorization header format")
raise HTTPException(
status_code=401,
detail="Invalid authorization header format",
headers={"WWW-Authenticate": "Bearer"},
)
if token != AUTH_TOKEN:
stats["unauthorized_requests"] += 1
logger.warning(f"Invalid token: {token[:10]}...")
raise HTTPException(
status_code=401,
detail="Invalid authentication token",
headers={"WWW-Authenticate": "Bearer"},
)
return token
@app.get("/")
async def root():
"""基础信息端点(不需要认证)"""
return {
"service": "Embedding Proxy API",
"status": "running",
"authentication": "required",
"endpoint": "/v1/embeddings",
"stats": stats
}
@app.get("/health")
async def health_check():
"""健康检查端点(不需要认证)"""
return {"status": "healthy", "timestamp": datetime.now().isoformat()}
@app.post("/v1/embeddings")
async def proxy_embeddings(
request: Request,
token: str = Depends(get_bearer_token)
):
"""代理嵌入请求(需要认证)"""
stats["total_requests"] += 1
try:
# 解析请求体
body = await request.json()
model = body.get('model', 'unknown')
# 记录请求信息
input_data = body.get('input', '')
if isinstance(input_data, str):
input_info = f"text({len(input_data)} chars)"
elif isinstance(input_data, list):
input_info = f"list({len(input_data)} items)"
else:
input_info = "unknown"
logger.info(f"Authenticated request: model={model}, input={input_info}")
# 转发请求到目标端点
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": "Embedding-Proxy/1.0"
}
start_time = datetime.now()
response = await http_client.post(
FDROID_API_URL,
headers=headers,
json=body
)
elapsed = (datetime.now() - start_time).total_seconds()
response_data = response.json()
# 记录响应状态
if response.status_code == 200:
stats["successful_requests"] += 1
# 获取向量维度
embedding_dim = 0
if 'data' in response_data and response_data['data']:
embedding = response_data['data'][0].get('embedding', [])
embedding_dim = len(embedding)
logger.info(f"Success: status={response.status_code}, dim={embedding_dim}, time={elapsed:.2f}s")
else:
stats["failed_requests"] += 1
logger.warning(f"Failed: status={response.status_code}, time={elapsed:.2f}s, error={response_data}")
return JSONResponse(
content=response_data,
status_code=response.status_code
)
except httpx.TimeoutException:
stats["failed_requests"] += 1
logger.error("Request timeout after 60s")
raise HTTPException(status_code=504, detail="Gateway timeout")
except httpx.RequestError as e:
stats["failed_requests"] += 1
logger.error(f"Request error: {str(e)}")
raise HTTPException(status_code=502, detail="Bad gateway")
except json.JSONDecodeError as e:
stats["failed_requests"] += 1
logger.error(f"Invalid JSON: {str(e)}")
raise HTTPException(status_code=400, detail="Invalid JSON in request body")
except Exception as e:
stats["failed_requests"] += 1
logger.error(f"Internal error: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")
@app.post("/embeddings")
async def proxy_embeddings_alt(
request: Request,
token: str = Depends(get_bearer_token)
):
"""兼容路径(需要认证)"""
return await proxy_embeddings(request, token)
@app.on_event("startup")
async def startup_event():
"""启动事件"""
logger.info("=" * 50)
logger.info("Embedding Proxy Service Started")
logger.info(f"Port: {PORT}")
logger.info(f"Authentication: Enabled (Bearer Token)")
logger.info("=" * 50)
@app.on_event("shutdown")
async def shutdown_event():
"""关闭事件"""
await http_client.aclose()
logger.info("Service shutdown completed")
if __name__ == "__main__":
import uvicorn
uvicorn.run(
app,
host="0.0.0.0",
port=PORT,
log_level="info"
)