Spaces:
Sleeping
Sleeping
File size: 14,340 Bytes
5868187 |
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 |
"""
OpenAI Transfer Module - Handles conversion between OpenAI and Gemini API formats
被openai-router调用,负责OpenAI格式与Gemini格式的双向转换
"""
import time
import uuid
from typing import Dict, Any
from config import (
DEFAULT_SAFETY_SETTINGS,
get_base_model_name,
get_thinking_budget,
is_search_model,
should_include_thoughts,
get_compatibility_mode_enabled
)
from log import log
from .models import ChatCompletionRequest
async def openai_request_to_gemini_payload(openai_request: ChatCompletionRequest) -> Dict[str, Any]:
"""
将OpenAI聊天完成请求直接转换为完整的Gemini API payload格式
Args:
openai_request: OpenAI格式请求对象
Returns:
完整的Gemini API payload,包含model和request字段
"""
contents = []
system_instructions = []
# 检查是否启用兼容性模式
compatibility_mode = await get_compatibility_mode_enabled()
# 处理对话中的每条消息
# 第一阶段:收集连续的system消息到system_instruction中(除非在兼容性模式下)
collecting_system = True if not compatibility_mode else False
for message in openai_request.messages:
role = message.role
# 处理系统消息
if role == "system":
if compatibility_mode:
# 兼容性模式:所有system消息转换为user消息
role = "user"
elif collecting_system:
# 正常模式:仍在收集连续的system消息
if isinstance(message.content, str):
system_instructions.append(message.content)
elif isinstance(message.content, list):
# 处理列表格式的系统消息
for part in message.content:
if part.get("type") == "text" and part.get("text"):
system_instructions.append(part["text"])
continue
else:
# 正常模式:后续的system消息转换为user消息
role = "user"
else:
# 遇到非system消息,停止收集system消息
collecting_system = False
# 将OpenAI角色映射到Gemini角色
if role == "assistant":
role = "model"
# 处理普通内容
if isinstance(message.content, list):
parts = []
for part in message.content:
if part.get("type") == "text":
parts.append({"text": part.get("text", "")})
elif part.get("type") == "image_url":
image_url = part.get("image_url", {}).get("url")
if image_url:
# 解析数据URI: "data:image/jpeg;base64,{base64_image}"
try:
mime_type, base64_data = image_url.split(";")
_, mime_type = mime_type.split(":")
_, base64_data = base64_data.split(",")
parts.append({
"inlineData": {
"mimeType": mime_type,
"data": base64_data
}
})
except ValueError:
continue
contents.append({"role": role, "parts": parts})
# log.debug(f"Added message to contents: role={role}, parts={parts}")
elif message.content:
# 简单文本内容
contents.append({"role": role, "parts": [{"text": message.content}]})
# log.debug(f"Added message to contents: role={role}, content={message.content}")
# 将OpenAI生成参数映射到Gemini格式
generation_config = {}
if openai_request.temperature is not None:
generation_config["temperature"] = openai_request.temperature
if openai_request.top_p is not None:
generation_config["topP"] = openai_request.top_p
if openai_request.max_tokens is not None:
generation_config["maxOutputTokens"] = openai_request.max_tokens
if openai_request.stop is not None:
# Gemini支持停止序列
if isinstance(openai_request.stop, str):
generation_config["stopSequences"] = [openai_request.stop]
elif isinstance(openai_request.stop, list):
generation_config["stopSequences"] = openai_request.stop
if openai_request.frequency_penalty is not None:
generation_config["frequencyPenalty"] = openai_request.frequency_penalty
if openai_request.presence_penalty is not None:
generation_config["presencePenalty"] = openai_request.presence_penalty
if openai_request.n is not None:
generation_config["candidateCount"] = openai_request.n
if openai_request.seed is not None:
generation_config["seed"] = openai_request.seed
if openai_request.response_format is not None:
# 处理JSON模式
if openai_request.response_format.get("type") == "json_object":
generation_config["responseMimeType"] = "application/json"
# 如果contents为空(只有系统消息的情况),添加一个默认的用户消息以满足Gemini API要求
if not contents:
contents.append({"role": "user", "parts": [{"text": "请根据系统指令回答。"}]})
# 构建请求数据
request_data = {
"contents": contents,
"generationConfig": generation_config,
"safetySettings": DEFAULT_SAFETY_SETTINGS,
}
# 如果有系统消息且未启用兼容性模式,添加systemInstruction
if system_instructions and not compatibility_mode:
combined_system_instruction = "\n\n".join(system_instructions)
request_data["systemInstruction"] = {"parts": [{"text": combined_system_instruction}]}
log.debug(f"Final request payload contents count: {len(contents)}, system_instruction: {bool(system_instructions and not compatibility_mode)}, compatibility_mode: {compatibility_mode}")
# 为thinking模型添加thinking配置
thinking_budget = get_thinking_budget(openai_request.model)
if thinking_budget is not None:
request_data["generationConfig"]["thinkingConfig"] = {
"thinkingBudget": thinking_budget,
"includeThoughts": should_include_thoughts(openai_request.model)
}
# 为搜索模型添加Google Search工具
if is_search_model(openai_request.model):
request_data["tools"] = [{"googleSearch": {}}]
# 移除None值
request_data = {k: v for k, v in request_data.items() if v is not None}
# 返回完整的Gemini API payload格式
return {
"model": get_base_model_name(openai_request.model),
"request": request_data
}
def _extract_content_and_reasoning(parts: list) -> tuple:
"""从Gemini响应部件中提取内容和推理内容"""
content = ""
reasoning_content = ""
for part in parts:
# 处理文本内容
if part.get("text"):
# 检查这个部件是否包含thinking tokens
if part.get("thought", False):
reasoning_content += part.get("text", "")
else:
content += part.get("text", "")
return content, reasoning_content
def _build_message_with_reasoning(role: str, content: str, reasoning_content: str) -> dict:
"""构建包含可选推理内容的消息对象"""
message = {
"role": role,
"content": content
}
# 如果有thinking tokens,添加reasoning_content
if reasoning_content:
message["reasoning_content"] = reasoning_content
return message
def gemini_response_to_openai(gemini_response: Dict[str, Any], model: str) -> Dict[str, Any]:
"""
将Gemini API响应转换为OpenAI聊天完成格式
Args:
gemini_response: 来自Gemini API的响应
model: 要在响应中包含的模型名称
Returns:
OpenAI聊天完成格式的字典
"""
choices = []
for candidate in gemini_response.get("candidates", []):
role = candidate.get("content", {}).get("role", "assistant")
# 将Gemini角色映射回OpenAI角色
if role == "model":
role = "assistant"
# 提取并分离thinking tokens和常规内容
parts = candidate.get("content", {}).get("parts", [])
content, reasoning_content = _extract_content_and_reasoning(parts)
# 构建消息对象
message = _build_message_with_reasoning(role, content, reasoning_content)
choices.append({
"index": candidate.get("index", 0),
"message": message,
"finish_reason": _map_finish_reason(candidate.get("finishReason")),
})
return {
"id": str(uuid.uuid4()),
"object": "chat.completion",
"created": int(time.time()),
"model": model,
"choices": choices,
}
def gemini_stream_chunk_to_openai(gemini_chunk: Dict[str, Any], model: str, response_id: str) -> Dict[str, Any]:
"""
将Gemini流式响应块转换为OpenAI流式格式
Args:
gemini_chunk: 来自Gemini流式响应的单个块
model: 要在响应中包含的模型名称
response_id: 此流式响应的一致ID
Returns:
OpenAI流式格式的字典
"""
choices = []
for candidate in gemini_chunk.get("candidates", []):
role = candidate.get("content", {}).get("role", "assistant")
# 将Gemini角色映射回OpenAI角色
if role == "model":
role = "assistant"
# 提取并分离thinking tokens和常规内容
parts = candidate.get("content", {}).get("parts", [])
content, reasoning_content = _extract_content_and_reasoning(parts)
# 构建delta对象
delta = {}
if content:
delta["content"] = content
if reasoning_content:
delta["reasoning_content"] = reasoning_content
choices.append({
"index": candidate.get("index", 0),
"delta": delta,
"finish_reason": _map_finish_reason(candidate.get("finishReason")),
})
return {
"id": response_id,
"object": "chat.completion.chunk",
"created": int(time.time()),
"model": model,
"choices": choices,
}
def _map_finish_reason(gemini_reason: str) -> str:
"""
将Gemini结束原因映射到OpenAI结束原因
Args:
gemini_reason: 来自Gemini API的结束原因
Returns:
OpenAI兼容的结束原因
"""
if gemini_reason == "STOP":
return "stop"
elif gemini_reason == "MAX_TOKENS":
return "length"
elif gemini_reason in ["SAFETY", "RECITATION"]:
return "content_filter"
else:
return None
def validate_openai_request(request_data: Dict[str, Any]) -> ChatCompletionRequest:
"""
验证并标准化OpenAI请求数据
Args:
request_data: 原始请求数据字典
Returns:
验证后的ChatCompletionRequest对象
Raises:
ValueError: 当请求数据无效时
"""
try:
return ChatCompletionRequest(**request_data)
except Exception as e:
raise ValueError(f"Invalid OpenAI request format: {str(e)}")
def normalize_openai_request(request_data: ChatCompletionRequest) -> ChatCompletionRequest:
"""
标准化OpenAI请求数据,应用默认值和限制
Args:
request_data: 原始请求对象
Returns:
标准化后的请求对象
"""
# 限制max_tokens
if getattr(request_data, "max_tokens", None) is not None and request_data.max_tokens > 65535:
request_data.max_tokens = 65535
# 覆写 top_k 为 64
setattr(request_data, "top_k", 64)
# 过滤空消息
filtered_messages = []
for m in request_data.messages:
content = getattr(m, "content", None)
if content:
if isinstance(content, str) and content.strip():
filtered_messages.append(m)
elif isinstance(content, list) and len(content) > 0:
has_valid_content = False
for part in content:
if isinstance(part, dict):
if part.get("type") == "text" and part.get("text", "").strip():
has_valid_content = True
break
elif part.get("type") == "image_url" and part.get("image_url", {}).get("url"):
has_valid_content = True
break
if has_valid_content:
filtered_messages.append(m)
request_data.messages = filtered_messages
return request_data
def is_health_check_request(request_data: ChatCompletionRequest) -> bool:
"""
检查是否为健康检查请求
Args:
request_data: 请求对象
Returns:
是否为健康检查请求
"""
return (len(request_data.messages) == 1 and
getattr(request_data.messages[0], "role", None) == "user" and
getattr(request_data.messages[0], "content", None) == "Hi")
def create_health_check_response() -> Dict[str, Any]:
"""
创建健康检查响应
Returns:
健康检查响应字典
"""
return {
"choices": [{
"message": {
"role": "assistant",
"content": "gcli2api正常工作中"
}
}]
}
def extract_model_settings(model: str) -> Dict[str, Any]:
"""
从模型名称中提取设置信息
Args:
model: 模型名称
Returns:
包含模型设置的字典
"""
return {
"base_model": get_base_model_name(model),
"use_fake_streaming": model.endswith("-假流式"),
"thinking_budget": get_thinking_budget(model),
"include_thoughts": should_include_thoughts(model)
} |