mirror of
https://github.com/snailyp/gemini-balance.git
synced 2026-06-09 17:49:42 +08:00
- 将 `_build_payload`、`_build_tools`、`_get_safety_settings` 和 `_has_image_parts` 函数从 `OpenAIChatService` 和 `GeminiChatService` 类中提取为独立的函数。 - 将 `_handle_stream_response` 和 `_handle_normal_response` 函数从 `GeminiResponseHandler` 和 `OpenAIResponseHandler` 类中提取为独立的函数。 - 将 `_extract_text` 函数从 `OpenAIResponseHandler` 类中提取为独立的函数, 并在 `GeminiResponseHandler` 中复用。 - 将 `_convert_image` 函数从 `OpenAIMessageConverter` 类中提取为独立的函数。 - 优化 `OpenAIChatService` 和 `GeminiChatService` 中的代码结构, 使其更清晰。 - 优化 `app/api/openai_routes.py` 和 `app/api/gemini_routes.py` 中的路由函数, 移除不必要的参数。
54 lines
1.6 KiB
Python
54 lines
1.6 KiB
Python
# app/services/chat/message_converter.py
|
|
|
|
from abc import ABC, abstractmethod
|
|
from typing import List, Dict, Any
|
|
|
|
|
|
class MessageConverter(ABC):
|
|
"""消息转换器基类"""
|
|
|
|
@abstractmethod
|
|
def convert(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
|
pass
|
|
|
|
|
|
def _convert_image(image_url: str) -> Dict[str, Any]:
|
|
if image_url.startswith("data:image"):
|
|
return {
|
|
"inline_data": {
|
|
"mime_type": "image/jpeg",
|
|
"data": image_url.split(",")[1]
|
|
}
|
|
}
|
|
return {
|
|
"image_url": {
|
|
"url": image_url
|
|
}
|
|
}
|
|
|
|
|
|
class OpenAIMessageConverter(MessageConverter):
|
|
"""OpenAI消息格式转换器"""
|
|
|
|
def convert(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
|
converted_messages = []
|
|
for msg in messages:
|
|
role = "user" if msg["role"] == "user" else "model"
|
|
parts = []
|
|
|
|
if isinstance(msg["content"], str):
|
|
parts.append({"text": msg["content"]})
|
|
elif isinstance(msg["content"], list):
|
|
for content in msg["content"]:
|
|
if isinstance(content, str):
|
|
parts.append({"text": content})
|
|
elif isinstance(content, dict):
|
|
if content["type"] == "text":
|
|
parts.append({"text": content["text"]})
|
|
elif content["type"] == "image_url":
|
|
parts.append(_convert_image(content["image_url"]["url"]))
|
|
|
|
converted_messages.append({"role": role, "parts": parts})
|
|
|
|
return converted_messages
|