支持gimini格式,优化debug日志

This commit is contained in:
h88782481 2026-03-14 09:27:15 +08:00
parent e726f11bad
commit 4de6db13f9
16 changed files with 1783 additions and 55 deletions

View file

@ -44,6 +44,16 @@ def build_anthropic_headers(api_key: str) -> dict[str, str]:
return headers
def build_gemini_headers(api_key: str) -> dict[str, str]:
"""构建 Gemini 请求头,根据密钥前缀选择鉴权方式"""
headers = {'Content-Type': 'application/json'}
if api_key.startswith('AIza'):
headers['x-goog-api-key'] = api_key
else:
headers['Authorization'] = f'Bearer {api_key}'
return headers
# ─── 响应构建 ──────────────────────────────────────
@ -125,6 +135,26 @@ def iter_responses_sse(response) -> Iterator[tuple[str, dict[str, Any]]]:
yield from _iter_event_sse(response)
def iter_gemini_sse(response) -> Iterator[dict[str, Any]]:
"""解析 Gemini SSE 流yield 完整的 GenerateContentResponse 字典。
Gemini 流式使用 ?alt=sse每个 data: 行是一个完整的 JSON 响应
"""
for line in response.iter_lines():
if not line:
continue
decoded = line.decode('utf-8', errors='replace')
if not decoded.startswith('data:'):
continue
data_str = decoded[5:].strip()
if not data_str:
continue
try:
yield json.loads(data_str)
except json.JSONDecodeError:
continue
def _iter_event_sse(response) -> Iterator[tuple[str, dict[str, Any]]]:
"""解析带 event/data 的通用 SSE 流。