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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Main Web Integration - Integrates all routers and modules
|
| 3 |
+
集合router并开启主服务
|
| 4 |
+
"""
|
| 5 |
+
import asyncio
|
| 6 |
+
from contextlib import asynccontextmanager
|
| 7 |
+
|
| 8 |
+
from fastapi import FastAPI, Response
|
| 9 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 10 |
+
from fastapi.staticfiles import StaticFiles
|
| 11 |
+
|
| 12 |
+
# Import all routers
|
| 13 |
+
from src.openai_router import router as openai_router
|
| 14 |
+
from src.gemini_router import router as gemini_router
|
| 15 |
+
from src.web_routes import router as web_router
|
| 16 |
+
|
| 17 |
+
# Import managers and utilities
|
| 18 |
+
from src.credential_manager import CredentialManager
|
| 19 |
+
from src.task_manager import shutdown_all_tasks
|
| 20 |
+
from config import get_server_host, get_server_port
|
| 21 |
+
from log import log
|
| 22 |
+
|
| 23 |
+
# 全局凭证管理器
|
| 24 |
+
global_credential_manager = None
|
| 25 |
+
|
| 26 |
+
@asynccontextmanager
|
| 27 |
+
async def lifespan(app: FastAPI):
|
| 28 |
+
"""应用生命周期管理"""
|
| 29 |
+
global global_credential_manager
|
| 30 |
+
|
| 31 |
+
log.info("启动 GCLI2API 主服务")
|
| 32 |
+
|
| 33 |
+
# 初始化全局凭证管理器
|
| 34 |
+
try:
|
| 35 |
+
global_credential_manager = CredentialManager()
|
| 36 |
+
await global_credential_manager.initialize()
|
| 37 |
+
log.info("凭证管理器初始化成功")
|
| 38 |
+
except Exception as e:
|
| 39 |
+
log.error(f"凭证管理器初始化失败: {e}")
|
| 40 |
+
global_credential_manager = None
|
| 41 |
+
|
| 42 |
+
# 自动从环境变量加载凭证(异步执行)
|
| 43 |
+
try:
|
| 44 |
+
from src.auth import auto_load_env_credentials_on_startup
|
| 45 |
+
import asyncio
|
| 46 |
+
|
| 47 |
+
# 在后台任务中执行异步加载
|
| 48 |
+
async def load_env_creds():
|
| 49 |
+
try:
|
| 50 |
+
await auto_load_env_credentials_on_startup()
|
| 51 |
+
except Exception as e:
|
| 52 |
+
log.error(f"自动加载环境变量凭证失败: {e}")
|
| 53 |
+
|
| 54 |
+
# 创建后台任务
|
| 55 |
+
asyncio.create_task(load_env_creds())
|
| 56 |
+
except Exception as e:
|
| 57 |
+
log.error(f"创建自动加载环境变量凭证任务失败: {e}")
|
| 58 |
+
|
| 59 |
+
# OAuth回调服务器将在需要时按需启动
|
| 60 |
+
|
| 61 |
+
yield
|
| 62 |
+
|
| 63 |
+
# 清理资源
|
| 64 |
+
log.info("开始关闭 GCLI2API 主服务")
|
| 65 |
+
|
| 66 |
+
# 首先关闭所有异步任务
|
| 67 |
+
try:
|
| 68 |
+
await shutdown_all_tasks(timeout=10.0)
|
| 69 |
+
log.info("所有异步任务已关闭")
|
| 70 |
+
except Exception as e:
|
| 71 |
+
log.error(f"关闭异步任务时出错: {e}")
|
| 72 |
+
|
| 73 |
+
# 然后关闭凭证管理器
|
| 74 |
+
if global_credential_manager:
|
| 75 |
+
try:
|
| 76 |
+
await global_credential_manager.close()
|
| 77 |
+
log.info("凭证管理器已关闭")
|
| 78 |
+
except Exception as e:
|
| 79 |
+
log.error(f"关闭凭证管理器时出错: {e}")
|
| 80 |
+
|
| 81 |
+
log.info("GCLI2API 主服务已停止")
|
| 82 |
+
|
| 83 |
+
# 创建FastAPI应用
|
| 84 |
+
app = FastAPI(
|
| 85 |
+
title="GCLI2API",
|
| 86 |
+
description="Gemini API proxy with OpenAI compatibility",
|
| 87 |
+
version="2.0.0",
|
| 88 |
+
lifespan=lifespan
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
# CORS中间件
|
| 92 |
+
app.add_middleware(
|
| 93 |
+
CORSMiddleware,
|
| 94 |
+
allow_origins=["*"],
|
| 95 |
+
allow_credentials=True,
|
| 96 |
+
allow_methods=["*"],
|
| 97 |
+
allow_headers=["*"],
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
# 挂载路由器
|
| 101 |
+
# OpenAI兼容路由 - 处理OpenAI格式请求
|
| 102 |
+
app.include_router(
|
| 103 |
+
openai_router,
|
| 104 |
+
prefix="",
|
| 105 |
+
tags=["OpenAI Compatible API"]
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
# Gemini原生路由 - 处理Gemini格式请求
|
| 109 |
+
app.include_router(
|
| 110 |
+
gemini_router,
|
| 111 |
+
prefix="",
|
| 112 |
+
tags=["Gemini Native API"]
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
# Web路由 - 包含认证、凭证管理和控制面板功能
|
| 116 |
+
app.include_router(
|
| 117 |
+
web_router,
|
| 118 |
+
prefix="",
|
| 119 |
+
tags=["Web Interface"]
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
# 静态文件路由 - 服务docs目录下的文件(如捐赠图片)
|
| 123 |
+
app.mount("/docs", StaticFiles(directory="docs"), name="docs")
|
| 124 |
+
|
| 125 |
+
# 保活接口(仅响应 HEAD)
|
| 126 |
+
@app.head("/keepalive")
|
| 127 |
+
async def keepalive() -> Response:
|
| 128 |
+
return Response(status_code=200)
|
| 129 |
+
|
| 130 |
+
def get_credential_manager():
|
| 131 |
+
"""获取全局凭证管理器实例"""
|
| 132 |
+
return global_credential_manager
|
| 133 |
+
|
| 134 |
+
# 导出给其他模块使用
|
| 135 |
+
__all__ = ['app', 'get_credential_manager']
|
| 136 |
+
|
| 137 |
+
async def main():
|
| 138 |
+
"""异步主启动函数"""
|
| 139 |
+
from hypercorn.asyncio import serve
|
| 140 |
+
from hypercorn.config import Config
|
| 141 |
+
|
| 142 |
+
# 日志系统现在直接使用环境变量,无需初始化
|
| 143 |
+
|
| 144 |
+
# 从环境变量或配置获取端口和主机
|
| 145 |
+
port = await get_server_port()
|
| 146 |
+
host = await get_server_host()
|
| 147 |
+
|
| 148 |
+
log.info("=" * 60)
|
| 149 |
+
log.info("启动 GCLI2API")
|
| 150 |
+
log.info("=" * 60)
|
| 151 |
+
log.info(f"控制面板: http://127.0.0.1:{port}")
|
| 152 |
+
log.info("=" * 60)
|
| 153 |
+
log.info("API端点:")
|
| 154 |
+
log.info(f" OpenAI兼容: http://127.0.0.1:{port}/v1")
|
| 155 |
+
log.info(f" Gemini原生: http://127.0.0.1:{port}")
|
| 156 |
+
|
| 157 |
+
# 配置hypercorn
|
| 158 |
+
config = Config()
|
| 159 |
+
config.bind = [f"{host}:{port}"]
|
| 160 |
+
config.accesslog = "-"
|
| 161 |
+
config.errorlog = "-"
|
| 162 |
+
config.loglevel = "INFO"
|
| 163 |
+
config.use_colors = True
|
| 164 |
+
|
| 165 |
+
# 设置请求体大小限制为100MB
|
| 166 |
+
config.max_request_body_size = 100 * 1024 * 1024
|
| 167 |
+
|
| 168 |
+
# 设置连接超时
|
| 169 |
+
config.keep_alive_timeout = 300 # 5分钟
|
| 170 |
+
config.read_timeout = 300 # 5分钟读取超时
|
| 171 |
+
config.write_timeout = 300 # 5分钟写入超时
|
| 172 |
+
|
| 173 |
+
# 增加启���超时时间以支持大量凭证的场景
|
| 174 |
+
config.startup_timeout = 120 # 2分钟启动超时
|
| 175 |
+
|
| 176 |
+
await serve(app, config)
|
| 177 |
+
|
| 178 |
+
if __name__ == "__main__":
|
| 179 |
+
asyncio.run(main())
|