Spaces:
Running
Running
Upload 4 files
Browse files- Dockerfile +11 -0
- docker-compose.yml +9 -0
- main.py +483 -0
- requirements.txt +4 -0
Dockerfile
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
WORKDIR /app
|
| 3 |
+
COPY requirements.txt .
|
| 4 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 5 |
+
gcc \
|
| 6 |
+
&& pip install --no-cache-dir -r requirements.txt \
|
| 7 |
+
&& apt-get purge -y gcc \
|
| 8 |
+
&& apt-get autoremove -y \
|
| 9 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 10 |
+
COPY main.py .
|
| 11 |
+
CMD ["python", "-u", "main.py"]
|
docker-compose.yml
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
geminibusiness:
|
| 3 |
+
build: .
|
| 4 |
+
container_name: geminibusiness
|
| 5 |
+
restart: unless-stopped
|
| 6 |
+
ports:
|
| 7 |
+
- "3003:8000"
|
| 8 |
+
env_file: .env
|
| 9 |
+
|
main.py
ADDED
|
@@ -0,0 +1,483 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json, time, hmac, hashlib, base64, os, asyncio, uuid, ssl, re
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
from typing import List, Optional, Union, Dict, Any
|
| 4 |
+
import logging
|
| 5 |
+
|
| 6 |
+
import httpx
|
| 7 |
+
from fastapi import FastAPI, HTTPException, Request
|
| 8 |
+
from fastapi.responses import StreamingResponse
|
| 9 |
+
from pydantic import BaseModel
|
| 10 |
+
|
| 11 |
+
# ---------- 日志配置 ----------
|
| 12 |
+
logging.basicConfig(
|
| 13 |
+
level=logging.INFO,
|
| 14 |
+
format="%(asctime)s | %(levelname)s | %(message)s",
|
| 15 |
+
datefmt="%H:%M:%S",
|
| 16 |
+
)
|
| 17 |
+
logger = logging.getLogger("gemini")
|
| 18 |
+
|
| 19 |
+
# ---------- 配置 ----------
|
| 20 |
+
SECURE_C_SES = os.getenv("SECURE_C_SES")
|
| 21 |
+
HOST_C_OSES = os.getenv("HOST_C_OSES")
|
| 22 |
+
CSESIDX = os.getenv("CSESIDX")
|
| 23 |
+
CONFIG_ID = os.getenv("CONFIG_ID")
|
| 24 |
+
PROXY = os.getenv("PROXY") or None
|
| 25 |
+
TIMEOUT_SECONDS = 600
|
| 26 |
+
|
| 27 |
+
# ---------- 模型映射配置 ----------
|
| 28 |
+
MODEL_MAPPING = {
|
| 29 |
+
"gemini-auto": None,
|
| 30 |
+
"gemini-2.5-flash": "gemini-2.5-flash",
|
| 31 |
+
"gemini-2.5-pro": "gemini-2.5-pro",
|
| 32 |
+
"gemini-3-pro-preview": "gemini-3-pro-preview"
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
# ---------- 全局 Session 缓存 ----------
|
| 36 |
+
SESSION_CACHE: Dict[str, dict] = {}
|
| 37 |
+
|
| 38 |
+
# ---------- HTTP 客户端 ----------
|
| 39 |
+
http_client = httpx.AsyncClient(
|
| 40 |
+
proxies=PROXY,
|
| 41 |
+
verify=False,
|
| 42 |
+
http2=False,
|
| 43 |
+
timeout=httpx.Timeout(TIMEOUT_SECONDS, connect=60.0),
|
| 44 |
+
limits=httpx.Limits(max_keepalive_connections=20, max_connections=50)
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
# ---------- 工具函数 ----------
|
| 48 |
+
def get_common_headers(jwt: str) -> dict:
|
| 49 |
+
return {
|
| 50 |
+
"accept": "*/*",
|
| 51 |
+
"accept-encoding": "gzip, deflate, br, zstd",
|
| 52 |
+
"accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
|
| 53 |
+
"authorization": f"Bearer {jwt}",
|
| 54 |
+
"content-type": "application/json",
|
| 55 |
+
"origin": "https://business.gemini.google",
|
| 56 |
+
"referer": "https://business.gemini.google/",
|
| 57 |
+
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36",
|
| 58 |
+
"x-server-timeout": "1800",
|
| 59 |
+
"sec-ch-ua": '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"',
|
| 60 |
+
"sec-ch-ua-mobile": "?0",
|
| 61 |
+
"sec-ch-ua-platform": '"Windows"',
|
| 62 |
+
"sec-fetch-dest": "empty",
|
| 63 |
+
"sec-fetch-mode": "cors",
|
| 64 |
+
"sec-fetch-site": "cross-site",
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
def urlsafe_b64encode(data: bytes) -> str:
|
| 68 |
+
return base64.urlsafe_b64encode(data).decode().rstrip("=")
|
| 69 |
+
|
| 70 |
+
def kq_encode(s: str) -> str:
|
| 71 |
+
b = bytearray()
|
| 72 |
+
for ch in s:
|
| 73 |
+
v = ord(ch)
|
| 74 |
+
if v > 255:
|
| 75 |
+
b.append(v & 255)
|
| 76 |
+
b.append(v >> 8)
|
| 77 |
+
else:
|
| 78 |
+
b.append(v)
|
| 79 |
+
return urlsafe_b64encode(bytes(b))
|
| 80 |
+
|
| 81 |
+
def create_jwt(key_bytes: bytes, key_id: str, csesidx: str) -> str:
|
| 82 |
+
now = int(time.time())
|
| 83 |
+
header = {"alg": "HS256", "typ": "JWT", "kid": key_id}
|
| 84 |
+
payload = {
|
| 85 |
+
"iss": "https://business.gemini.google",
|
| 86 |
+
"aud": "https://biz-discoveryengine.googleapis.com",
|
| 87 |
+
"sub": f"csesidx/{csesidx}",
|
| 88 |
+
"iat": now,
|
| 89 |
+
"exp": now + 300,
|
| 90 |
+
"nbf": now,
|
| 91 |
+
}
|
| 92 |
+
header_b64 = kq_encode(json.dumps(header, separators=(",", ":")))
|
| 93 |
+
payload_b64 = kq_encode(json.dumps(payload, separators=(",", ":")))
|
| 94 |
+
message = f"{header_b64}.{payload_b64}"
|
| 95 |
+
sig = hmac.new(key_bytes, message.encode(), hashlib.sha256).digest()
|
| 96 |
+
return f"{message}.{urlsafe_b64encode(sig)}"
|
| 97 |
+
|
| 98 |
+
# ---------- JWT 管理 ----------
|
| 99 |
+
class JWTManager:
|
| 100 |
+
def __init__(self) -> None:
|
| 101 |
+
self.jwt: str = ""
|
| 102 |
+
self.expires: float = 0
|
| 103 |
+
self._lock = asyncio.Lock()
|
| 104 |
+
|
| 105 |
+
async def get(self) -> str:
|
| 106 |
+
async with self._lock:
|
| 107 |
+
if time.time() > self.expires:
|
| 108 |
+
await self._refresh()
|
| 109 |
+
return self.jwt
|
| 110 |
+
|
| 111 |
+
async def _refresh(self) -> None:
|
| 112 |
+
cookie = f"__Secure-C_SES={SECURE_C_SES}"
|
| 113 |
+
if HOST_C_OSES:
|
| 114 |
+
cookie += f"; __Host-C_OSES={HOST_C_OSES}"
|
| 115 |
+
|
| 116 |
+
logger.debug("🔑 正在刷新 JWT...")
|
| 117 |
+
r = await http_client.get(
|
| 118 |
+
"https://business.gemini.google/auth/getoxsrf",
|
| 119 |
+
params={"csesidx": CSESIDX},
|
| 120 |
+
headers={
|
| 121 |
+
"cookie": cookie,
|
| 122 |
+
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36",
|
| 123 |
+
"referer": "https://business.gemini.google/"
|
| 124 |
+
},
|
| 125 |
+
)
|
| 126 |
+
if r.status_code != 200:
|
| 127 |
+
logger.error(f"❌ getoxsrf 失败: {r.status_code} {r.text}")
|
| 128 |
+
raise HTTPException(r.status_code, "getoxsrf failed")
|
| 129 |
+
|
| 130 |
+
txt = r.text[4:] if r.text.startswith(")]}'") else r.text
|
| 131 |
+
data = json.loads(txt)
|
| 132 |
+
|
| 133 |
+
key_bytes = base64.urlsafe_b64decode(data["xsrfToken"] + "==")
|
| 134 |
+
self.jwt = create_jwt(key_bytes, data["keyId"], CSESIDX)
|
| 135 |
+
self.expires = time.time() + 270
|
| 136 |
+
logger.info(f"✅ JWT 刷新成功")
|
| 137 |
+
|
| 138 |
+
jwt_mgr = JWTManager()
|
| 139 |
+
|
| 140 |
+
# ---------- Session & File 管理 ----------
|
| 141 |
+
async def create_google_session() -> str:
|
| 142 |
+
jwt = await jwt_mgr.get()
|
| 143 |
+
headers = get_common_headers(jwt)
|
| 144 |
+
body = {
|
| 145 |
+
"configId": CONFIG_ID,
|
| 146 |
+
"additionalParams": {"token": "-"},
|
| 147 |
+
"createSessionRequest": {
|
| 148 |
+
"session": {"name": "", "displayName": ""}
|
| 149 |
+
}
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
logger.debug("🌐 申请新 Session...")
|
| 153 |
+
r = await http_client.post(
|
| 154 |
+
"https://biz-discoveryengine.googleapis.com/v1alpha/locations/global/widgetCreateSession",
|
| 155 |
+
headers=headers,
|
| 156 |
+
json=body,
|
| 157 |
+
)
|
| 158 |
+
if r.status_code != 200:
|
| 159 |
+
logger.error(f"❌ createSession 失败: {r.status_code} {r.text}")
|
| 160 |
+
raise HTTPException(r.status_code, "createSession failed")
|
| 161 |
+
sess_name = r.json()["session"]["name"]
|
| 162 |
+
return sess_name
|
| 163 |
+
|
| 164 |
+
async def upload_context_file(session_name: str, mime_type: str, base64_content: str) -> str:
|
| 165 |
+
"""上传文件到指定 Session,返回 fileId"""
|
| 166 |
+
jwt = await jwt_mgr.get()
|
| 167 |
+
headers = get_common_headers(jwt)
|
| 168 |
+
|
| 169 |
+
# 生成随机文件名
|
| 170 |
+
ext = mime_type.split('/')[-1] if '/' in mime_type else "bin"
|
| 171 |
+
file_name = f"upload_{int(time.time())}_{uuid.uuid4().hex[:6]}.{ext}"
|
| 172 |
+
|
| 173 |
+
body = {
|
| 174 |
+
"configId": CONFIG_ID,
|
| 175 |
+
"additionalParams": {"token": "-"},
|
| 176 |
+
"addContextFileRequest": {
|
| 177 |
+
"name": session_name,
|
| 178 |
+
"fileName": file_name,
|
| 179 |
+
"mimeType": mime_type,
|
| 180 |
+
"fileContents": base64_content
|
| 181 |
+
}
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
logger.info(f"📤 上传图片 [{mime_type}] 到 Session...")
|
| 185 |
+
r = await http_client.post(
|
| 186 |
+
"https://biz-discoveryengine.googleapis.com/v1alpha/locations/global/widgetAddContextFile",
|
| 187 |
+
headers=headers,
|
| 188 |
+
json=body,
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
if r.status_code != 200:
|
| 192 |
+
logger.error(f"❌ 上传文件失败: {r.status_code} {r.text}")
|
| 193 |
+
raise HTTPException(r.status_code, f"Upload failed: {r.text}")
|
| 194 |
+
|
| 195 |
+
data = r.json()
|
| 196 |
+
file_id = data.get("addContextFileResponse", {}).get("fileId")
|
| 197 |
+
logger.info(f"✅ 图片上传成功, ID: {file_id}")
|
| 198 |
+
return file_id
|
| 199 |
+
|
| 200 |
+
# ---------- 消息处理逻辑 ----------
|
| 201 |
+
def get_conversation_key(messages: List[dict]) -> str:
|
| 202 |
+
if not messages: return "empty"
|
| 203 |
+
# 仅使用第一条消息的内容生成指纹,忽略图片数据防止指纹过大
|
| 204 |
+
first_msg = messages[0].copy()
|
| 205 |
+
if isinstance(first_msg.get("content"), list):
|
| 206 |
+
# 如果第一条是多模态,只取文本部分做 Hash
|
| 207 |
+
text_part = "".join([x["text"] for x in first_msg["content"] if x["type"] == "text"])
|
| 208 |
+
first_msg["content"] = text_part
|
| 209 |
+
|
| 210 |
+
key_str = json.dumps(first_msg, sort_keys=True)
|
| 211 |
+
return hashlib.md5(key_str.encode()).hexdigest()
|
| 212 |
+
|
| 213 |
+
def parse_last_message(messages: List['Message']):
|
| 214 |
+
"""解析最后一条消息,分离文本和图片"""
|
| 215 |
+
if not messages:
|
| 216 |
+
return "", []
|
| 217 |
+
|
| 218 |
+
last_msg = messages[-1]
|
| 219 |
+
content = last_msg.content
|
| 220 |
+
|
| 221 |
+
text_content = ""
|
| 222 |
+
images = [] # List of {"mime": str, "data": str_base64}
|
| 223 |
+
|
| 224 |
+
if isinstance(content, str):
|
| 225 |
+
text_content = content
|
| 226 |
+
elif isinstance(content, list):
|
| 227 |
+
for part in content:
|
| 228 |
+
if part.get("type") == "text":
|
| 229 |
+
text_content += part.get("text", "")
|
| 230 |
+
elif part.get("type") == "image_url":
|
| 231 |
+
url = part.get("image_url", {}).get("url", "")
|
| 232 |
+
# 解析 Data URI: data:image/png;base64,xxxxxx
|
| 233 |
+
match = re.match(r"data:(image/[^;]+);base64,(.+)", url)
|
| 234 |
+
if match:
|
| 235 |
+
images.append({"mime": match.group(1), "data": match.group(2)})
|
| 236 |
+
else:
|
| 237 |
+
logger.warning(f"⚠️ 暂不支持非 Base64 图片链接: {url[:30]}...")
|
| 238 |
+
|
| 239 |
+
return text_content, images
|
| 240 |
+
|
| 241 |
+
def build_full_context_text(messages: List['Message']) -> str:
|
| 242 |
+
"""仅拼接历史文本,图片只处理当次请求的"""
|
| 243 |
+
prompt = ""
|
| 244 |
+
for msg in messages:
|
| 245 |
+
role = "User" if msg.role in ["user", "system"] else "Assistant"
|
| 246 |
+
content_str = ""
|
| 247 |
+
if isinstance(msg.content, str):
|
| 248 |
+
content_str = msg.content
|
| 249 |
+
elif isinstance(msg.content, list):
|
| 250 |
+
for part in msg.content:
|
| 251 |
+
if part.get("type") == "text":
|
| 252 |
+
content_str += part.get("text", "")
|
| 253 |
+
elif part.get("type") == "image_url":
|
| 254 |
+
content_str += "[图片]"
|
| 255 |
+
|
| 256 |
+
prompt += f"{role}: {content_str}\n\n"
|
| 257 |
+
return prompt
|
| 258 |
+
|
| 259 |
+
# ---------- OpenAI 兼容接口 ----------
|
| 260 |
+
app = FastAPI(title="Gemini-Business OpenAI Gateway")
|
| 261 |
+
|
| 262 |
+
class Message(BaseModel):
|
| 263 |
+
role: str
|
| 264 |
+
content: Union[str, List[Dict[str, Any]]]
|
| 265 |
+
|
| 266 |
+
class ChatRequest(BaseModel):
|
| 267 |
+
model: str = "gemini-auto"
|
| 268 |
+
messages: List[Message]
|
| 269 |
+
stream: bool = False
|
| 270 |
+
temperature: Optional[float] = 0.7
|
| 271 |
+
top_p: Optional[float] = 1.0
|
| 272 |
+
|
| 273 |
+
def create_chunk(id: str, created: int, model: str, delta: dict, finish_reason: Union[str, None]) -> str:
|
| 274 |
+
chunk = {
|
| 275 |
+
"id": id,
|
| 276 |
+
"object": "chat.completion.chunk",
|
| 277 |
+
"created": created,
|
| 278 |
+
"model": model,
|
| 279 |
+
"choices": [{
|
| 280 |
+
"index": 0,
|
| 281 |
+
"delta": delta,
|
| 282 |
+
"finish_reason": finish_reason
|
| 283 |
+
}]
|
| 284 |
+
}
|
| 285 |
+
return json.dumps(chunk)
|
| 286 |
+
|
| 287 |
+
@app.get("/v1/models")
|
| 288 |
+
async def list_models():
|
| 289 |
+
data = []
|
| 290 |
+
now = int(time.time())
|
| 291 |
+
for m in MODEL_MAPPING.keys():
|
| 292 |
+
data.append({
|
| 293 |
+
"id": m,
|
| 294 |
+
"object": "model",
|
| 295 |
+
"created": now,
|
| 296 |
+
"owned_by": "google",
|
| 297 |
+
"permission": []
|
| 298 |
+
})
|
| 299 |
+
return {"object": "list", "data": data}
|
| 300 |
+
|
| 301 |
+
@app.get("/health")
|
| 302 |
+
async def health():
|
| 303 |
+
return {"status": "ok", "time": datetime.utcnow().isoformat()}
|
| 304 |
+
|
| 305 |
+
@app.post("/v1/chat/completions")
|
| 306 |
+
async def chat(req: ChatRequest):
|
| 307 |
+
# 1. 模型校验
|
| 308 |
+
if req.model not in MODEL_MAPPING:
|
| 309 |
+
raise HTTPException(status_code=404, detail=f"Model '{req.model}' not found.")
|
| 310 |
+
|
| 311 |
+
# 2. 解析请求内容
|
| 312 |
+
last_text, current_images = parse_last_message(req.messages)
|
| 313 |
+
|
| 314 |
+
# 3. 锚定 Session
|
| 315 |
+
conv_key = get_conversation_key([m.dict() for m in req.messages])
|
| 316 |
+
cached = SESSION_CACHE.get(conv_key)
|
| 317 |
+
|
| 318 |
+
if cached:
|
| 319 |
+
google_session = cached["session_id"]
|
| 320 |
+
text_to_send = last_text
|
| 321 |
+
logger.info(f"♻️ 延续旧对话 [{req.model}]: {google_session[-12:]}")
|
| 322 |
+
SESSION_CACHE[conv_key]["updated_at"] = time.time()
|
| 323 |
+
is_retry_mode = False
|
| 324 |
+
else:
|
| 325 |
+
logger.info(f"🆕 开启新对话 [{req.model}]")
|
| 326 |
+
google_session = await create_google_session()
|
| 327 |
+
# 新对话使用全量文本上下文 (图片只传当前的)
|
| 328 |
+
text_to_send = build_full_context_text(req.messages)
|
| 329 |
+
SESSION_CACHE[conv_key] = {"session_id": google_session, "updated_at": time.time()}
|
| 330 |
+
is_retry_mode = True
|
| 331 |
+
|
| 332 |
+
chat_id = f"chatcmpl-{uuid.uuid4()}"
|
| 333 |
+
created_time = int(time.time())
|
| 334 |
+
|
| 335 |
+
# 封装生成器 (含图片上传和重试逻辑)
|
| 336 |
+
async def response_wrapper():
|
| 337 |
+
retry_count = 0
|
| 338 |
+
max_retries = 2
|
| 339 |
+
|
| 340 |
+
current_text = text_to_send
|
| 341 |
+
current_retry_mode = is_retry_mode
|
| 342 |
+
|
| 343 |
+
# 图片 ID 列表 (每次 Session 变化都需要重新上传,因为 fileId 绑定在 Session 上)
|
| 344 |
+
current_file_ids = []
|
| 345 |
+
|
| 346 |
+
while retry_count <= max_retries:
|
| 347 |
+
try:
|
| 348 |
+
current_session = SESSION_CACHE[conv_key]["session_id"]
|
| 349 |
+
|
| 350 |
+
# A. 如果有图片且还没上传到当前 Session,先上传
|
| 351 |
+
# 注意:每次重试如果是新 Session,都需要重新上传图片
|
| 352 |
+
if current_images and not current_file_ids:
|
| 353 |
+
for img in current_images:
|
| 354 |
+
fid = await upload_context_file(current_session, img["mime"], img["data"])
|
| 355 |
+
current_file_ids.append(fid)
|
| 356 |
+
|
| 357 |
+
# B. 准备文本 (重试模式下发全文)
|
| 358 |
+
if current_retry_mode:
|
| 359 |
+
current_text = build_full_context_text(req.messages)
|
| 360 |
+
|
| 361 |
+
# C. 发起对话
|
| 362 |
+
async for chunk in stream_chat_generator(
|
| 363 |
+
current_session,
|
| 364 |
+
current_text,
|
| 365 |
+
current_file_ids,
|
| 366 |
+
req.model,
|
| 367 |
+
chat_id,
|
| 368 |
+
created_time,
|
| 369 |
+
req.stream
|
| 370 |
+
):
|
| 371 |
+
yield chunk
|
| 372 |
+
break
|
| 373 |
+
|
| 374 |
+
except (httpx.ConnectError, httpx.ReadTimeout, ssl.SSLError, HTTPException) as e:
|
| 375 |
+
retry_count += 1
|
| 376 |
+
logger.warning(f"⚠️ 请求异常 (重试 {retry_count}/{max_retries}): {e}")
|
| 377 |
+
|
| 378 |
+
if retry_count <= max_retries:
|
| 379 |
+
logger.info("🔄 尝试重建 Session...")
|
| 380 |
+
try:
|
| 381 |
+
new_sess = await create_google_session()
|
| 382 |
+
SESSION_CACHE[conv_key] = {"session_id": new_sess, "updated_at": time.time()}
|
| 383 |
+
current_retry_mode = True
|
| 384 |
+
current_file_ids = [] # 清空 ID,强制下次循环重新上传到新 Session
|
| 385 |
+
except Exception as create_err:
|
| 386 |
+
logger.error(f"❌ 重建失败: {create_err}")
|
| 387 |
+
if req.stream: yield f"data: {json.dumps({'error': {'message': 'Session Recovery Failed'}})}\n\n"
|
| 388 |
+
return
|
| 389 |
+
else:
|
| 390 |
+
if req.stream: yield f"data: {json.dumps({'error': {'message': f'Final Error: {e}'}})}\n\n"
|
| 391 |
+
return
|
| 392 |
+
|
| 393 |
+
if req.stream:
|
| 394 |
+
return StreamingResponse(response_wrapper(), media_type="text/event-stream")
|
| 395 |
+
|
| 396 |
+
full_content = ""
|
| 397 |
+
async for chunk_str in response_wrapper():
|
| 398 |
+
if chunk_str.startswith("data: [DONE]"): break
|
| 399 |
+
if chunk_str.startswith("data: "):
|
| 400 |
+
try:
|
| 401 |
+
data = json.loads(chunk_str[6:])
|
| 402 |
+
delta = data["choices"][0]["delta"]
|
| 403 |
+
if "content" in delta: full_content += delta["content"]
|
| 404 |
+
except: pass
|
| 405 |
+
|
| 406 |
+
return {
|
| 407 |
+
"id": chat_id,
|
| 408 |
+
"object": "chat.completion",
|
| 409 |
+
"created": created_time,
|
| 410 |
+
"model": req.model,
|
| 411 |
+
"choices": [{"index": 0, "message": {"role": "assistant", "content": full_content}, "finish_reason": "stop"}],
|
| 412 |
+
"usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
async def stream_chat_generator(session: str, text_content: str, file_ids: List[str], model_name: str, chat_id: str, created_time: int, is_stream: bool = True):
|
| 416 |
+
jwt = await jwt_mgr.get()
|
| 417 |
+
headers = get_common_headers(jwt)
|
| 418 |
+
|
| 419 |
+
body = {
|
| 420 |
+
"configId": CONFIG_ID,
|
| 421 |
+
"additionalParams": {"token": "-"},
|
| 422 |
+
"streamAssistRequest": {
|
| 423 |
+
"session": session,
|
| 424 |
+
"query": {"parts": [{"text": text_content}]},
|
| 425 |
+
"filter": "",
|
| 426 |
+
"fileIds": file_ids, # 注入文件 ID
|
| 427 |
+
"answerGenerationMode": "NORMAL",
|
| 428 |
+
"toolsSpec": {
|
| 429 |
+
"webGroundingSpec": {},
|
| 430 |
+
"toolRegistry": "default_tool_registry",
|
| 431 |
+
"imageGenerationSpec": {},
|
| 432 |
+
"videoGenerationSpec": {}
|
| 433 |
+
},
|
| 434 |
+
"languageCode": "zh-CN",
|
| 435 |
+
"userMetadata": {"timeZone": "Asia/Shanghai"},
|
| 436 |
+
"assistSkippingMode": "REQUEST_ASSIST"
|
| 437 |
+
}
|
| 438 |
+
}
|
| 439 |
+
|
| 440 |
+
target_model_id = MODEL_MAPPING.get(model_name)
|
| 441 |
+
if target_model_id:
|
| 442 |
+
body["streamAssistRequest"]["assistGenerationConfig"] = {
|
| 443 |
+
"modelId": target_model_id
|
| 444 |
+
}
|
| 445 |
+
|
| 446 |
+
if is_stream:
|
| 447 |
+
chunk = create_chunk(chat_id, created_time, model_name, {"role": "assistant"}, None)
|
| 448 |
+
yield f"data: {chunk}\n\n"
|
| 449 |
+
|
| 450 |
+
r = await http_client.post(
|
| 451 |
+
"https://biz-discoveryengine.googleapis.com/v1alpha/locations/global/widgetStreamAssist",
|
| 452 |
+
headers=headers,
|
| 453 |
+
json=body,
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
if r.status_code != 200:
|
| 457 |
+
raise HTTPException(status_code=r.status_code, detail=f"Upstream Error {r.text}")
|
| 458 |
+
|
| 459 |
+
try:
|
| 460 |
+
data_list = r.json()
|
| 461 |
+
except Exception as e:
|
| 462 |
+
logger.error(f"❌ JSON 解析失败: {e}")
|
| 463 |
+
raise HTTPException(status_code=502, detail="Invalid JSON response")
|
| 464 |
+
|
| 465 |
+
for data in data_list:
|
| 466 |
+
for reply in data.get("streamAssistResponse", {}).get("answer", {}).get("replies", []):
|
| 467 |
+
text = reply.get("groundedContent", {}).get("content", {}).get("text", "")
|
| 468 |
+
if text and not reply.get("thought"):
|
| 469 |
+
chunk = create_chunk(chat_id, created_time, model_name, {"content": text}, None)
|
| 470 |
+
if is_stream:
|
| 471 |
+
yield f"data: {chunk}\n\n"
|
| 472 |
+
|
| 473 |
+
if is_stream:
|
| 474 |
+
final_chunk = create_chunk(chat_id, created_time, model_name, {}, "stop")
|
| 475 |
+
yield f"data: {final_chunk}\n\n"
|
| 476 |
+
yield "data: [DONE]\n\n"
|
| 477 |
+
|
| 478 |
+
if __name__ == "__main__":
|
| 479 |
+
if not all([SECURE_C_SES, CSESIDX, CONFIG_ID]):
|
| 480 |
+
print("Error: Missing required environment variables.")
|
| 481 |
+
exit(1)
|
| 482 |
+
import uvicorn
|
| 483 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi==0.110.0
|
| 2 |
+
uvicorn[standard]==0.29.0
|
| 3 |
+
httpx==0.27.0
|
| 4 |
+
pydantic==2.7.0
|