Update app.py
Browse files
app.py
CHANGED
|
@@ -89,29 +89,33 @@ def load_model():
|
|
| 89 |
return False
|
| 90 |
|
| 91 |
def apply_chat_template(messages):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
text = ""
|
| 93 |
|
| 94 |
-
for
|
| 95 |
role = msg.get("role", "").lower()
|
| 96 |
content = msg.get("content", "")
|
| 97 |
|
| 98 |
-
|
| 99 |
-
|
| 100 |
if isinstance(content, list):
|
| 101 |
-
|
| 102 |
text_parts = []
|
| 103 |
for item in content:
|
| 104 |
-
if isinstance(item, dict)
|
| 105 |
-
|
|
|
|
|
|
|
| 106 |
elif isinstance(item, str):
|
| 107 |
text_parts.append(item)
|
| 108 |
-
content_str = " ".join(
|
| 109 |
-
logger.info(f"从 list 中提取文本: {content_str[:80]}...")
|
| 110 |
else:
|
|
|
|
| 111 |
content_str = str(content).strip()
|
| 112 |
|
| 113 |
if not content_str:
|
| 114 |
-
logger.info(f"第 {i+1} 条消息内容为空,已跳过")
|
| 115 |
continue
|
| 116 |
|
| 117 |
if role == "system":
|
|
@@ -119,10 +123,12 @@ def apply_chat_template(messages):
|
|
| 119 |
elif role == "user":
|
| 120 |
text += f"<|im_start|>user\n{content_str}<|im_end|>\n"
|
| 121 |
elif role == "assistant":
|
| 122 |
-
text += f"<|im_start|>assistant\n{content_str}<|im_end|>\n
|
|
|
|
| 123 |
|
|
|
|
| 124 |
text += "<|im_start|>assistant\n"
|
| 125 |
-
|
| 126 |
return text
|
| 127 |
|
| 128 |
|
|
|
|
| 89 |
return False
|
| 90 |
|
| 91 |
def apply_chat_template(messages):
|
| 92 |
+
"""
|
| 93 |
+
把 OpenAI 格式的 messages 转为 Qwen 的 chat template 格式
|
| 94 |
+
支持 content 是字符串 或 列表(多模态格式只取 text)
|
| 95 |
+
"""
|
| 96 |
text = ""
|
| 97 |
|
| 98 |
+
for msg in messages:
|
| 99 |
role = msg.get("role", "").lower()
|
| 100 |
content = msg.get("content", "")
|
| 101 |
|
| 102 |
+
# 处理 content 可能是 list 的情况(多模态 / 分段文本)
|
|
|
|
| 103 |
if isinstance(content, list):
|
| 104 |
+
# 只收集所有 type=text 的内容
|
| 105 |
text_parts = []
|
| 106 |
for item in content:
|
| 107 |
+
if isinstance(item, dict):
|
| 108 |
+
if item.get("type") == "text":
|
| 109 |
+
text_parts.append(str(item.get("text", "")))
|
| 110 |
+
# 可以选择忽略 image_url 等其他类型
|
| 111 |
elif isinstance(item, str):
|
| 112 |
text_parts.append(item)
|
| 113 |
+
content_str = " ".join(text_parts).strip()
|
|
|
|
| 114 |
else:
|
| 115 |
+
# 普通字符串
|
| 116 |
content_str = str(content).strip()
|
| 117 |
|
| 118 |
if not content_str:
|
|
|
|
| 119 |
continue
|
| 120 |
|
| 121 |
if role == "system":
|
|
|
|
| 123 |
elif role == "user":
|
| 124 |
text += f"<|im_start|>user\n{content_str}<|im_end|>\n"
|
| 125 |
elif role == "assistant":
|
| 126 |
+
text += f"<|im_start|>assistant\n{content_str}<|im_end|>\n"
|
| 127 |
+
# 其他 role 忽略或按需处理
|
| 128 |
|
| 129 |
+
# 加上 assistant 开头
|
| 130 |
text += "<|im_start|>assistant\n"
|
| 131 |
+
|
| 132 |
return text
|
| 133 |
|
| 134 |
|