1
1
# app/services/chat/message_converter.py
2
2
3
3
from abc import ABC , abstractmethod
4
- from typing import List , Dict , Any
4
+ from typing import Any , Dict , List , Optional
5
+
6
+ SUPPORTED_ROLES = ["user" , "model" , "system" ]
5
7
6
8
7
9
class MessageConverter (ABC ):
8
10
"""消息转换器基类"""
9
11
10
12
@abstractmethod
11
- def convert (self , messages : List [Dict [str , Any ]]) -> List [Dict [str , Any ]]:
13
+ def convert (self , messages : List [Dict [str , Any ]]) -> tuple [ List [Dict [str , Any ]], Optional [ Dict [ str , Any ] ]]:
12
14
pass
13
15
14
16
@@ -30,16 +32,19 @@ def _convert_image(image_url: str) -> Dict[str, Any]:
30
32
class OpenAIMessageConverter (MessageConverter ):
31
33
"""OpenAI消息格式转换器"""
32
34
33
- def convert (self , messages : List [Dict [str , Any ]]) -> List [Dict [str , Any ]]:
35
+ def convert (self , messages : List [Dict [str , Any ]]) -> tuple [ List [Dict [str , Any ]], Optional [ Dict [ str , Any ] ]]:
34
36
converted_messages = []
37
+ system_instruction = None
38
+
35
39
for msg in messages :
36
- role = "user" if msg ["role" ] == "user" else "model"
37
- parts = []
40
+ role = msg .get ("role" , "" )
41
+ if role not in SUPPORTED_ROLES :
42
+ role = "model"
38
43
39
- if isinstance ( msg [ "content" ], str ):
40
- # 请求 gemini 接口时如果包含 content 字段但内容为空时会返回 400 错误,所以需要判断是否为空
41
- if msg [ " content" ]:
42
- parts .append ({"text" : msg ["content" ]})
44
+ parts = []
45
+ if isinstance ( msg [ " content" ], str ) and msg [ "content" ]:
46
+ # 请求 gemini 接口时如果包含 content 字段但内容为空时会返回 400 错误,所以需要判断是否为空并移除
47
+ parts .append ({"text" : msg ["content" ]})
43
48
elif isinstance (msg ["content" ], list ):
44
49
for content in msg ["content" ]:
45
50
if isinstance (content , str ) and content :
@@ -50,6 +55,10 @@ def convert(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
50
55
elif content ["type" ] == "image_url" :
51
56
parts .append (_convert_image (content ["image_url" ]["url" ]))
52
57
53
- converted_messages .append ({"role" : role , "parts" : parts })
58
+ if parts :
59
+ if role == "system" :
60
+ system_instruction = {"role" : "system" , "parts" : parts }
61
+ else :
62
+ converted_messages .append ({"role" : role , "parts" : parts })
54
63
55
- return converted_messages
64
+ return converted_messages , system_instruction
0 commit comments