File size: 27,597 Bytes
69fec20 |
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 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 |
"""
Antigravity API Client - Handles communication with Google's Antigravity API
处理与 Google Antigravity API 的通信
"""
import asyncio
import json
import uuid
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional
from fastapi import Response
from config import (
get_antigravity_api_url,
get_antigravity_stream2nostream,
get_auto_ban_error_codes,
)
from log import log
from src.credential_manager import CredentialManager
from src.httpx_client import stream_post_async, post_async
from src.models import Model, model_to_dict
from src.utils import ANTIGRAVITY_USER_AGENT
# 导入共同的基础功能
from src.api.utils import (
handle_error_with_retry,
get_retry_config,
record_api_call_success,
record_api_call_error,
parse_and_log_cooldown,
collect_streaming_response,
)
# ==================== 全局凭证管理器 ====================
# 全局凭证管理器实例(单例模式)
_credential_manager: Optional[CredentialManager] = None
async def _get_credential_manager() -> CredentialManager:
"""
获取全局凭证管理器实例
Returns:
CredentialManager实例
"""
global _credential_manager
if not _credential_manager:
_credential_manager = CredentialManager()
await _credential_manager.initialize()
return _credential_manager
# ==================== 辅助函数 ====================
def build_antigravity_headers(access_token: str, model_name: str = "") -> Dict[str, str]:
"""
构建 Antigravity API 请求头
Args:
access_token: 访问令牌
model_name: 模型名称,用于判断 request_type
Returns:
请求头字典
"""
headers = {
'User-Agent': ANTIGRAVITY_USER_AGENT,
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip',
'requestId': f"req-{uuid.uuid4()}"
}
# 根据模型名称判断 request_type
if model_name:
request_type = "image_gen" if "image" in model_name.lower() else "agent"
headers['requestType'] = request_type
return headers
# ==================== 新的流式和非流式请求函数 ====================
async def stream_request(
body: Dict[str, Any],
native: bool = False,
headers: Optional[Dict[str, str]] = None,
):
"""
流式请求函数
Args:
body: 请求体
native: 是否返回原生bytes流,False则返回str流
headers: 额外的请求头
Yields:
Response对象(错误时)或 bytes流/str流(成功时)
"""
# 获取凭证管理器
credential_manager = await _get_credential_manager()
model_name = body.get("model", "")
# 1. 获取有效凭证
cred_result = await credential_manager.get_valid_credential(
mode="antigravity", model_key=model_name
)
if not cred_result:
# 如果返回值是None,直接返回错误500
log.error("[ANTIGRAVITY STREAM] 当前无可用凭证")
yield Response(
content=json.dumps({"error": "当前无可用凭证"}),
status_code=500,
media_type="application/json"
)
return
current_file, credential_data = cred_result
access_token = credential_data.get("access_token") or credential_data.get("token")
if not access_token:
log.error(f"[ANTIGRAVITY STREAM] No access token in credential: {current_file}")
yield Response(
content=json.dumps({"error": "凭证中没有访问令牌"}),
status_code=500,
media_type="application/json"
)
return
# 2. 构建URL和请求头
antigravity_url = await get_antigravity_api_url()
target_url = f"{antigravity_url}/v1internal:streamGenerateContent?alt=sse"
auth_headers = build_antigravity_headers(access_token, model_name)
# 合并自定义headers
if headers:
auth_headers.update(headers)
# 3. 调用stream_post_async进行请求
retry_config = await get_retry_config()
max_retries = retry_config["max_retries"]
retry_interval = retry_config["retry_interval"]
DISABLE_ERROR_CODES = await get_auto_ban_error_codes() # 禁用凭证的错误码
last_error_response = None # 记录最后一次的错误响应
# 内部函数:获取新凭证并更新headers
async def refresh_credential():
nonlocal current_file, access_token, auth_headers
cred_result = await credential_manager.get_valid_credential(
mode="antigravity", model_key=model_name
)
if not cred_result:
return None
current_file, credential_data = cred_result
access_token = credential_data.get("access_token") or credential_data.get("token")
if not access_token:
return None
auth_headers = build_antigravity_headers(access_token, model_name)
if headers:
auth_headers.update(headers)
return True
for attempt in range(max_retries + 1):
success_recorded = False # 标记是否已记录成功
need_retry = False # 标记是否需要重试
try:
async for chunk in stream_post_async(
url=target_url,
body=body,
native=native,
headers=auth_headers
):
# 判断是否是Response对象
if isinstance(chunk, Response):
status_code = chunk.status_code
last_error_response = chunk # 记录最后一次错误
# 如果错误码是429或者不在禁用码当中,做好记录后进行重试
if status_code == 429 or status_code not in DISABLE_ERROR_CODES:
# 解析错误响应内容
try:
error_body = chunk.body.decode('utf-8') if isinstance(chunk.body, bytes) else str(chunk.body)
log.warning(f"[ANTIGRAVITY STREAM] 流式请求失败 (status={status_code}), 凭证: {current_file}, 响应: {error_body[:500]}")
except Exception:
log.warning(f"[ANTIGRAVITY STREAM] 流式请求失败 (status={status_code}), 凭证: {current_file}")
# 记录错误
cooldown_until = None
if status_code == 429:
# 尝试解析冷却时间
try:
error_body = chunk.body.decode('utf-8') if isinstance(chunk.body, bytes) else str(chunk.body)
cooldown_until = await parse_and_log_cooldown(error_body, mode="antigravity")
except Exception:
pass
await record_api_call_error(
credential_manager, current_file, status_code,
cooldown_until, mode="antigravity", model_key=model_name
)
# 检查是否应该重试
should_retry = await handle_error_with_retry(
credential_manager, status_code, current_file,
retry_config["retry_enabled"], attempt, max_retries, retry_interval,
mode="antigravity"
)
if should_retry and attempt < max_retries:
need_retry = True
break # 跳出内层循环,准备重试
else:
# 不重试,直接返回原始错误
log.error(f"[ANTIGRAVITY STREAM] 达到最大重试次数或不应重试,返回原始错误")
yield chunk
return
else:
# 错误码在禁用码当中,直接返回,无需重试
try:
error_body = chunk.body.decode('utf-8') if isinstance(chunk.body, bytes) else str(chunk.body)
log.error(f"[ANTIGRAVITY STREAM] 流式请求失败,禁用错误码 (status={status_code}), 凭证: {current_file}, 响应: {error_body[:500]}")
except Exception:
log.error(f"[ANTIGRAVITY STREAM] 流式请求失败,禁用错误码 (status={status_code}), 凭证: {current_file}")
await record_api_call_error(
credential_manager, current_file, status_code,
None, mode="antigravity", model_key=model_name
)
yield chunk
return
else:
# 不是Response,说明是真流,直接yield返回
# 只在第一个chunk时记录成功
if not success_recorded:
await record_api_call_success(
credential_manager, current_file, mode="antigravity", model_key=model_name
)
success_recorded = True
log.info(f"[ANTIGRAVITY STREAM] 开始接收流式响应,模型: {model_name}")
# 记录原始chunk内容(用于调试)
if isinstance(chunk, bytes):
log.debug(f"[ANTIGRAVITY STREAM RAW] chunk(bytes): {chunk}")
else:
log.debug(f"[ANTIGRAVITY STREAM RAW] chunk(str): {chunk}")
yield chunk
# 流式请求完成,检查结果
if success_recorded:
log.info(f"[ANTIGRAVITY STREAM] 流式响应完成,模型: {model_name}")
return
elif not need_retry:
# 没有收到任何数据(空回复),需要重试
log.warning(f"[ANTIGRAVITY STREAM] 收到空回复,无任何内容,凭证: {current_file}")
await record_api_call_error(
credential_manager, current_file, 200,
None, mode="antigravity", model_key=model_name
)
if attempt < max_retries:
need_retry = True
else:
log.error(f"[ANTIGRAVITY STREAM] 空回复达到最大重试次数")
yield Response(
content=json.dumps({"error": "服务返回空回复"}),
status_code=500,
media_type="application/json"
)
return
# 统一处理重试
if need_retry:
log.info(f"[ANTIGRAVITY STREAM] 重试请求 (attempt {attempt + 2}/{max_retries + 1})...")
await asyncio.sleep(retry_interval)
if not await refresh_credential():
log.error("[ANTIGRAVITY STREAM] 重试时无可用凭证或令牌")
yield Response(
content=json.dumps({"error": "当前无可用凭证"}),
status_code=500,
media_type="application/json"
)
return
continue # 重试
except Exception as e:
log.error(f"[ANTIGRAVITY STREAM] 流式请求异常: {e}, 凭证: {current_file}")
if attempt < max_retries:
log.info(f"[ANTIGRAVITY STREAM] 异常后重试 (attempt {attempt + 2}/{max_retries + 1})...")
await asyncio.sleep(retry_interval)
continue
else:
# 所有重试都失败,返回最后一次的错误(如果有)
log.error(f"[ANTIGRAVITY STREAM] 所有重试均失败,最后异常: {e}")
yield last_error_response
async def non_stream_request(
body: Dict[str, Any],
headers: Optional[Dict[str, str]] = None,
) -> Response:
"""
非流式请求函数
Args:
body: 请求体
headers: 额外的请求头
Returns:
Response对象
"""
# 检查是否启用流式收集模式
if await get_antigravity_stream2nostream():
log.info("[ANTIGRAVITY] 使用流式收集模式实现非流式请求")
# 调用stream_request获取流
stream = stream_request(body=body, native=False, headers=headers)
# 收集流式响应
# stream_request是一个异步生成器,可能yield Response(错误)或流数据
# collect_streaming_response会自动处理这两种情况
return await collect_streaming_response(stream)
# 否则使用传统非流式模式
log.info("[ANTIGRAVITY] 使用传统非流式模式")
# 获取凭证管理器
credential_manager = await _get_credential_manager()
model_name = body.get("model", "")
# 1. 获取有效凭证
cred_result = await credential_manager.get_valid_credential(
mode="antigravity", model_key=model_name
)
if not cred_result:
# 如果返回值是None,直接返回错误500
log.error("[ANTIGRAVITY] 当前无可用凭证")
return Response(
content=json.dumps({"error": "当前无可用凭证"}),
status_code=500,
media_type="application/json"
)
current_file, credential_data = cred_result
access_token = credential_data.get("access_token") or credential_data.get("token")
if not access_token:
log.error(f"[ANTIGRAVITY] No access token in credential: {current_file}")
return Response(
content=json.dumps({"error": "凭证中没有访问令牌"}),
status_code=500,
media_type="application/json"
)
# 2. 构建URL和请求头
antigravity_url = await get_antigravity_api_url()
target_url = f"{antigravity_url}/v1internal:generateContent"
auth_headers = build_antigravity_headers(access_token, model_name)
# 合并自定义headers
if headers:
auth_headers.update(headers)
# 3. 调用post_async进行请求
retry_config = await get_retry_config()
max_retries = retry_config["max_retries"]
retry_interval = retry_config["retry_interval"]
DISABLE_ERROR_CODES = await get_auto_ban_error_codes() # 禁用凭证的错误码
last_error_response = None # 记录最后一次的错误响应
# 内部函数:获取新凭证并更新headers
async def refresh_credential():
nonlocal current_file, access_token, auth_headers
cred_result = await credential_manager.get_valid_credential(
mode="antigravity", model_key=model_name
)
if not cred_result:
return None
current_file, credential_data = cred_result
access_token = credential_data.get("access_token") or credential_data.get("token")
if not access_token:
return None
auth_headers = build_antigravity_headers(access_token, model_name)
if headers:
auth_headers.update(headers)
return True
for attempt in range(max_retries + 1):
need_retry = False # 标记是否需要重试
try:
response = await post_async(
url=target_url,
json=body,
headers=auth_headers,
timeout=300.0
)
status_code = response.status_code
# 成功
if status_code == 200:
# 检查是否为空回复
if not response.content or len(response.content) == 0:
log.warning(f"[ANTIGRAVITY] 收到200响应但内容为空,凭证: {current_file}")
# 记录错误
await record_api_call_error(
credential_manager, current_file, 200,
None, mode="antigravity", model_key=model_name
)
if attempt < max_retries:
need_retry = True
else:
log.error(f"[ANTIGRAVITY] 空回复达到最大重试次数")
return Response(
content=json.dumps({"error": "服务返回空回复"}),
status_code=500,
media_type="application/json"
)
else:
# 正常响应
await record_api_call_success(
credential_manager, current_file, mode="antigravity", model_key=model_name
)
return Response(
content=response.content,
status_code=200,
headers=dict(response.headers)
)
# 失败 - 记录最后一次错误
if status_code != 200:
last_error_response = Response(
content=response.content,
status_code=status_code,
headers=dict(response.headers)
)
# 判断是否需要重试
if status_code == 429 or status_code not in DISABLE_ERROR_CODES:
try:
error_text = response.text
log.warning(f"[ANTIGRAVITY] 非流式请求失败 (status={status_code}), 凭证: {current_file}, 响应: {error_text[:500]}")
except Exception:
log.warning(f"[ANTIGRAVITY] 非流式请求失败 (status={status_code}), 凭证: {current_file}")
# 记录错误
cooldown_until = None
if status_code == 429:
# 尝试解析冷却时间
try:
error_text = response.text
cooldown_until = await parse_and_log_cooldown(error_text, mode="antigravity")
except Exception:
pass
await record_api_call_error(
credential_manager, current_file, status_code,
cooldown_until, mode="antigravity", model_key=model_name
)
# 检查是否应该重试
should_retry = await handle_error_with_retry(
credential_manager, status_code, current_file,
retry_config["retry_enabled"], attempt, max_retries, retry_interval,
mode="antigravity"
)
if should_retry and attempt < max_retries:
need_retry = True
else:
# 不重试,直接返回原始错误
log.error(f"[ANTIGRAVITY] 达到最大重试次数或不应重试,返回原始错误")
return last_error_response
else:
# 错误码在禁用码当中,直接返回,无需重试
try:
error_text = response.text
log.error(f"[ANTIGRAVITY] 非流式请求失败,禁用错误码 (status={status_code}), 凭证: {current_file}, 响应: {error_text[:500]}")
except Exception:
log.error(f"[ANTIGRAVITY] 非流式请求失败,禁用错误码 (status={status_code}), 凭证: {current_file}")
await record_api_call_error(
credential_manager, current_file, status_code,
None, mode="antigravity", model_key=model_name
)
return last_error_response
# 统一处理重试
if need_retry:
log.info(f"[ANTIGRAVITY] 重试请求 (attempt {attempt + 2}/{max_retries + 1})...")
await asyncio.sleep(retry_interval)
if not await refresh_credential():
log.error("[ANTIGRAVITY] 重试时无可用凭证或令牌")
return Response(
content=json.dumps({"error": "当前无可用凭证"}),
status_code=500,
media_type="application/json"
)
continue # 重试
except Exception as e:
log.error(f"[ANTIGRAVITY] 非流式请求异常: {e}, 凭证: {current_file}")
if attempt < max_retries:
log.info(f"[ANTIGRAVITY] 异常后重试 (attempt {attempt + 2}/{max_retries + 1})...")
await asyncio.sleep(retry_interval)
continue
else:
# 所有重试都失败,返回最后一次的错误(如果有)
log.error(f"[ANTIGRAVITY] 所有重试均失败,最后异常: {e}")
return last_error_response
# 所有重试都失败,返回最后一次的原始错误
log.error("[ANTIGRAVITY] 所有重试均失败")
return last_error_response
# ==================== 模型和配额查询 ====================
async def fetch_available_models() -> List[Dict[str, Any]]:
"""
获取可用模型列表,返回符合 OpenAI API 规范的格式
Returns:
模型列表,格式为字典列表(用于兼容现有代码)
Raises:
返回空列表如果获取失败
"""
# 获取凭证管理器和可用凭证
credential_manager = await _get_credential_manager()
cred_result = await credential_manager.get_valid_credential(mode="antigravity")
if not cred_result:
log.error("[ANTIGRAVITY] No valid credentials available for fetching models")
return []
current_file, credential_data = cred_result
access_token = credential_data.get("access_token") or credential_data.get("token")
if not access_token:
log.error(f"[ANTIGRAVITY] No access token in credential: {current_file}")
return []
# 构建请求头
headers = build_antigravity_headers(access_token)
try:
# 使用 POST 请求获取模型列表
antigravity_url = await get_antigravity_api_url()
response = await post_async(
url=f"{antigravity_url}/v1internal:fetchAvailableModels",
json={}, # 空的请求体
headers=headers
)
if response.status_code == 200:
data = response.json()
log.debug(f"[ANTIGRAVITY] Raw models response: {json.dumps(data, ensure_ascii=False)[:500]}")
# 转换为 OpenAI 格式的模型列表,使用 Model 类
model_list = []
current_timestamp = int(datetime.now(timezone.utc).timestamp())
if 'models' in data and isinstance(data['models'], dict):
# 遍历模型字典
for model_id in data['models'].keys():
model = Model(
id=model_id,
object='model',
created=current_timestamp,
owned_by='google'
)
model_list.append(model_to_dict(model))
# 添加额外的 claude-opus-4-5 模型
claude_opus_model = Model(
id='claude-opus-4-5',
object='model',
created=current_timestamp,
owned_by='google'
)
model_list.append(model_to_dict(claude_opus_model))
log.info(f"[ANTIGRAVITY] Fetched {len(model_list)} available models")
return model_list
else:
log.error(f"[ANTIGRAVITY] Failed to fetch models ({response.status_code}): {response.text[:500]}")
return []
except Exception as e:
import traceback
log.error(f"[ANTIGRAVITY] Failed to fetch models: {e}")
log.error(f"[ANTIGRAVITY] Traceback: {traceback.format_exc()}")
return []
async def fetch_quota_info(access_token: str) -> Dict[str, Any]:
"""
获取指定凭证的额度信息
Args:
access_token: Antigravity 访问令牌
Returns:
包含额度信息的字典,格式为:
{
"success": True/False,
"models": {
"model_name": {
"remaining": 0.95,
"resetTime": "12-20 10:30",
"resetTimeRaw": "2025-12-20T02:30:00Z"
}
},
"error": "错误信息" (仅在失败时)
}
"""
headers = build_antigravity_headers(access_token)
try:
antigravity_url = await get_antigravity_api_url()
response = await post_async(
url=f"{antigravity_url}/v1internal:fetchAvailableModels",
json={},
headers=headers,
timeout=30.0
)
if response.status_code == 200:
data = response.json()
log.debug(f"[ANTIGRAVITY QUOTA] Raw response: {json.dumps(data, ensure_ascii=False)[:500]}")
quota_info = {}
if 'models' in data and isinstance(data['models'], dict):
for model_id, model_data in data['models'].items():
if isinstance(model_data, dict) and 'quotaInfo' in model_data:
quota = model_data['quotaInfo']
remaining = quota.get('remainingFraction', 0)
reset_time_raw = quota.get('resetTime', '')
# 转换为北京时间
reset_time_beijing = 'N/A'
if reset_time_raw:
try:
utc_date = datetime.fromisoformat(reset_time_raw.replace('Z', '+00:00'))
# 转换为北京时间 (UTC+8)
from datetime import timedelta
beijing_date = utc_date + timedelta(hours=8)
reset_time_beijing = beijing_date.strftime('%m-%d %H:%M')
except Exception as e:
log.warning(f"[ANTIGRAVITY QUOTA] Failed to parse reset time: {e}")
quota_info[model_id] = {
"remaining": remaining,
"resetTime": reset_time_beijing,
"resetTimeRaw": reset_time_raw
}
return {
"success": True,
"models": quota_info
}
else:
log.error(f"[ANTIGRAVITY QUOTA] Failed to fetch quota ({response.status_code}): {response.text[:500]}")
return {
"success": False,
"error": f"API返回错误: {response.status_code}"
}
except Exception as e:
import traceback
log.error(f"[ANTIGRAVITY QUOTA] Failed to fetch quota: {e}")
log.error(f"[ANTIGRAVITY QUOTA] Traceback: {traceback.format_exc()}")
return {
"success": False,
"error": str(e)
} |