Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -778,13 +778,12 @@ def send_message(message, model, think=False):
|
|
| 778 |
|
| 779 |
def generate():
|
| 780 |
think_message_id = None
|
| 781 |
-
think_state = 2
|
| 782 |
-
think_buffer = io.StringIO()
|
| 783 |
-
content_buffer = io.StringIO()
|
| 784 |
-
current_content = ""
|
| 785 |
code_block_active = False
|
| 786 |
-
|
| 787 |
-
|
| 788 |
yield format_sse_chunk(json.dumps({"object": "chat.completion.chunk", "choices": [{"delta": {"role": "assistant"}}]}))
|
| 789 |
|
| 790 |
if think:
|
|
@@ -795,105 +794,105 @@ def send_message(message, model, think=False):
|
|
| 795 |
decoded_line = line.decode("utf-8")
|
| 796 |
try:
|
| 797 |
data = json.loads(decoded_line)
|
| 798 |
-
|
| 799 |
-
|
|
|
|
| 800 |
|
| 801 |
-
|
| 802 |
-
|
| 803 |
-
|
| 804 |
-
|
| 805 |
-
|
| 806 |
-
|
| 807 |
-
|
| 808 |
-
|
| 809 |
-
|
| 810 |
-
|
| 811 |
-
|
| 812 |
-
|
| 813 |
-
|
| 814 |
-
|
| 815 |
-
|
| 816 |
-
|
| 817 |
-
|
| 818 |
-
|
| 819 |
-
|
| 820 |
-
|
| 821 |
-
|
| 822 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 823 |
else:
|
| 824 |
-
#
|
| 825 |
-
|
| 826 |
-
|
| 827 |
-
|
| 828 |
-
|
| 829 |
-
yield format_sse_chunk(json.dumps({'object': 'chat.completion.chunk', 'choices': [{'delta': {'content': "\n</think>\n"}}]})) # 先发送结束标签
|
| 830 |
-
content_buffer.write("\n</think>\n") # 写入缓冲区
|
| 831 |
think_state = 0
|
| 832 |
think_message_id = None
|
| 833 |
|
| 834 |
-
#
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
if
|
| 838 |
-
code_block_active = True
|
| 839 |
-
code_block_buffer = io.StringIO()
|
| 840 |
-
code_block_buffer.write(segment)
|
| 841 |
-
content_buffer.write(segment)
|
| 842 |
-
yield format_sse_chunk(json.dumps({'object': 'chat.completion.chunk', 'choices': [{'delta': {'content': segment}}]}))
|
| 843 |
-
continue
|
| 844 |
-
# 检查是否是代码块结束
|
| 845 |
-
elif segment.strip() == "```" and code_block_active:
|
| 846 |
-
code_block_active = False
|
| 847 |
-
code_block_buffer.write(segment)
|
| 848 |
-
content_buffer.write(segment)
|
| 849 |
-
yield format_sse_chunk(json.dumps({'object': 'chat.completion.chunk', 'choices': [{'delta': {'content': segment}}]}))
|
| 850 |
-
continue
|
| 851 |
-
|
| 852 |
-
# 处理代码块内的内容
|
| 853 |
-
if code_block_active:
|
| 854 |
-
code_block_buffer.write(segment)
|
| 855 |
-
content_buffer.write(segment)
|
| 856 |
-
current_content += segment
|
| 857 |
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
|
| 862 |
-
|
| 863 |
-
|
| 864 |
-
|
| 865 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 866 |
except Exception as e:
|
| 867 |
print(f"处理响应出错: {e}")
|
| 868 |
|
| 869 |
-
#
|
| 870 |
-
|
| 871 |
-
yield format_sse_chunk(json.dumps({'object': 'chat.completion.chunk', 'choices': [{'delta': {'content': current_content}}]}))
|
| 872 |
-
|
| 873 |
-
# 如果思维链还在进行中,添加结束标签
|
| 874 |
if think and think_state == 1:
|
| 875 |
yield format_sse_chunk(json.dumps({"object": "chat.completion.chunk", "choices": [{"delta": {"content": "\n</think>\n"}}]}))
|
|
|
|
| 876 |
|
| 877 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 878 |
print("\n----- 计算 Tokens (流式结束后) -----")
|
| 879 |
prompt_tokens, calculation_method = num_tokens_from_string(message, model)
|
| 880 |
print(f"输入 token 数: {prompt_tokens} (方法: {calculation_method})")
|
| 881 |
|
|
|
|
| 882 |
completion_content = content_buffer.getvalue()
|
| 883 |
completion_tokens, comp_calc_method = num_tokens_from_string(completion_content, model)
|
| 884 |
print(f"输出 token 数: {completion_tokens} (方法: {comp_calc_method})")
|
| 885 |
|
| 886 |
-
# 决定最终使用的计算方法 (优先使用精确)
|
| 887 |
final_calculation_method = "精确" if calculation_method == "精确" and comp_calc_method == "精确" else "估算"
|
| 888 |
-
|
| 889 |
-
|
| 890 |
yield format_sse_chunk(json.dumps({"object": "chat.completion.chunk", "choices": [{"delta": {}, "finish_reason": "stop"}]}))
|
| 891 |
yield format_sse_chunk("[DONE]")
|
| 892 |
|
| 893 |
-
# 保存对话历史并获取计算点数
|
| 894 |
_, compute_points_used = save_conversation_history(session, cookies, session_token, conversation_id)
|
| 895 |
-
|
| 896 |
-
# 更新统计信息
|
| 897 |
update_model_stats(model, prompt_tokens, completion_tokens, final_calculation_method, compute_points_used)
|
| 898 |
|
| 899 |
# Use stream_with_context to ensure context is available during generation
|
|
@@ -954,9 +953,16 @@ def send_message(message, model, think=False):
|
|
| 954 |
for line in response.iter_lines():
|
| 955 |
if line:
|
| 956 |
decoded_line = line.decode("utf-8")
|
| 957 |
-
|
| 958 |
-
|
| 959 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 960 |
|
| 961 |
response_content = buffer.getvalue()
|
| 962 |
|
|
@@ -1099,6 +1105,8 @@ def send_message_non_stream(message, model, think=False):
|
|
| 1099 |
think_state = 2
|
| 1100 |
think_buffer = io.StringIO()
|
| 1101 |
content_buffer = io.StringIO()
|
|
|
|
|
|
|
| 1102 |
content_buffer.write("<think>\n")
|
| 1103 |
|
| 1104 |
for line in response.iter_lines():
|
|
@@ -1106,165 +1114,148 @@ def send_message_non_stream(message, model, think=False):
|
|
| 1106 |
decoded_line = line.decode("utf-8")
|
| 1107 |
try:
|
| 1108 |
data = json.loads(decoded_line)
|
| 1109 |
-
|
| 1110 |
-
|
|
|
|
| 1111 |
|
| 1112 |
-
|
| 1113 |
-
|
| 1114 |
-
|
| 1115 |
-
if data.get("
|
| 1116 |
-
|
| 1117 |
-
|
| 1118 |
-
|
| 1119 |
-
|
| 1120 |
-
if data.get("title"):
|
| 1121 |
-
segment = f"{data.get('title')}\n"
|
| 1122 |
-
if data.get("segment") and isinstance(data.get("segment"), dict):
|
| 1123 |
-
if data.get("segment").get("segment"):
|
| 1124 |
-
segment += data.get("segment").get("segment")
|
| 1125 |
-
|
| 1126 |
-
think_buffer.write(segment)
|
| 1127 |
-
think_state = 1
|
| 1128 |
-
# 普通思维链文本内容
|
| 1129 |
-
elif think_message_id == data.get("messageId") and think_state == 1:
|
| 1130 |
-
segment = data.get("segment", "")
|
| 1131 |
-
think_buffer.write(segment)
|
| 1132 |
-
# 处理非思维链内容
|
| 1133 |
else:
|
| 1134 |
-
|
| 1135 |
-
|
| 1136 |
-
|
| 1137 |
-
|
| 1138 |
-
|
| 1139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1140 |
think_state = 0
|
| 1141 |
think_message_id = None
|
| 1142 |
-
continue
|
| 1143 |
|
| 1144 |
-
#
|
| 1145 |
-
|
| 1146 |
-
|
| 1147 |
-
if
|
| 1148 |
-
code_block_active = True
|
| 1149 |
-
code_block_buffer = io.StringIO()
|
| 1150 |
-
# 检查是否是代码块结束
|
| 1151 |
-
elif segment.strip() == "```" and code_block_active:
|
| 1152 |
-
code_block_active = False
|
| 1153 |
-
|
| 1154 |
-
# 处理代码块内容或普通内容
|
| 1155 |
-
if code_block_active:
|
| 1156 |
-
code_block_buffer.write(segment)
|
| 1157 |
-
content_buffer.write(segment)
|
| 1158 |
|
| 1159 |
-
|
| 1160 |
-
|
| 1161 |
-
|
| 1162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1163 |
except Exception as e:
|
| 1164 |
print(f"处理响应出错: {e}")
|
| 1165 |
|
| 1166 |
-
#
|
| 1167 |
if think_state == 1:
|
| 1168 |
content_buffer.write("\n</think>\n")
|
| 1169 |
|
| 1170 |
think_content = think_buffer.getvalue()
|
| 1171 |
response_content = content_buffer.getvalue()
|
| 1172 |
-
|
| 1173 |
-
# ---- Token 计算 ----
|
| 1174 |
-
print("\n----- 计算 Tokens (非流式, think模式) -----")
|
| 1175 |
-
prompt_tokens, calculation_method = num_tokens_from_string(message, model)
|
| 1176 |
-
print(f"输入 token 数: {prompt_tokens} (方法: {calculation_method})")
|
| 1177 |
-
# 计算输出token并更新统计信息
|
| 1178 |
-
completion_tokens, comp_calc_method = num_tokens_from_string(think_content + response_content, model)
|
| 1179 |
-
print(f"输出 token 数: {completion_tokens} (方法: {comp_calc_method})")
|
| 1180 |
-
# 决定最终使用的计算方法
|
| 1181 |
-
final_calculation_method = "精确" if calculation_method == "精确" and comp_calc_method == "精确" else "估算"
|
| 1182 |
-
# ---- Token 计算结束 ----
|
| 1183 |
-
|
| 1184 |
-
# 保存对话历史并获取计算点数
|
| 1185 |
-
_, compute_points_used = save_conversation_history(session, cookies, session_token, conversation_id)
|
| 1186 |
-
|
| 1187 |
-
# 更新统计信息
|
| 1188 |
-
update_model_stats(model, prompt_tokens, completion_tokens, final_calculation_method, compute_points_used)
|
| 1189 |
-
|
| 1190 |
-
return jsonify({
|
| 1191 |
-
"id": f"chatcmpl-{str(uuid.uuid4())}",
|
| 1192 |
-
"object": "chat.completion",
|
| 1193 |
-
"created": int(time.time()),
|
| 1194 |
-
"model": model,
|
| 1195 |
-
"choices": [{
|
| 1196 |
-
"index": 0,
|
| 1197 |
-
"message": {
|
| 1198 |
-
"role": "assistant",
|
| 1199 |
-
"content": response_content # 这里是完整的响应,包括思维链
|
| 1200 |
-
},
|
| 1201 |
-
"finish_reason": "stop"
|
| 1202 |
-
}],
|
| 1203 |
-
"usage": {
|
| 1204 |
-
"prompt_tokens": prompt_tokens,
|
| 1205 |
-
"completion_tokens": completion_tokens,
|
| 1206 |
-
"total_tokens": prompt_tokens + completion_tokens
|
| 1207 |
-
}
|
| 1208 |
-
})
|
| 1209 |
else:
|
| 1210 |
-
#
|
| 1211 |
buffer = io.StringIO()
|
|
|
|
| 1212 |
|
| 1213 |
for line in response.iter_lines():
|
| 1214 |
if line:
|
| 1215 |
decoded_line = line.decode("utf-8")
|
| 1216 |
try:
|
| 1217 |
data = json.loads(decoded_line)
|
| 1218 |
-
segment
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1219 |
|
| 1220 |
-
if
|
| 1221 |
-
|
| 1222 |
-
|
| 1223 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1224 |
|
| 1225 |
-
if segment:
|
| 1226 |
-
buffer.write(segment)
|
| 1227 |
except Exception as e:
|
| 1228 |
print(f"处理响应出错: {e}")
|
| 1229 |
|
| 1230 |
response_content = buffer.getvalue()
|
| 1231 |
|
| 1232 |
-
|
| 1233 |
-
|
| 1234 |
-
|
| 1235 |
-
|
| 1236 |
-
|
| 1237 |
-
|
| 1238 |
-
|
| 1239 |
-
|
| 1240 |
-
|
| 1241 |
-
|
| 1242 |
-
|
| 1243 |
-
|
| 1244 |
-
|
| 1245 |
-
|
| 1246 |
-
|
| 1247 |
-
|
| 1248 |
-
|
| 1249 |
-
|
| 1250 |
-
|
| 1251 |
-
|
| 1252 |
-
|
| 1253 |
-
|
| 1254 |
-
|
| 1255 |
-
|
| 1256 |
-
|
| 1257 |
-
|
| 1258 |
-
|
| 1259 |
-
|
| 1260 |
-
|
| 1261 |
-
|
| 1262 |
-
|
| 1263 |
-
|
| 1264 |
-
|
| 1265 |
-
|
| 1266 |
-
|
| 1267 |
-
|
| 1268 |
except requests.exceptions.RequestException as e:
|
| 1269 |
error_details = str(e)
|
| 1270 |
if hasattr(e, 'response') and e.response is not None:
|
|
|
|
| 778 |
|
| 779 |
def generate():
|
| 780 |
think_message_id = None
|
| 781 |
+
think_state = 2 # 2: Haven't started thinking, 1: Thinking, 0: Finished thinking
|
| 782 |
+
think_buffer = io.StringIO() # Stores thinking content for token calculation
|
| 783 |
+
content_buffer = io.StringIO() # Stores final output content for token calculation
|
|
|
|
| 784 |
code_block_active = False
|
| 785 |
+
# current_code_block_buffer = io.StringIO() # Buffer for yielding code blocks chunk by chunk
|
| 786 |
+
|
| 787 |
yield format_sse_chunk(json.dumps({"object": "chat.completion.chunk", "choices": [{"delta": {"role": "assistant"}}]}))
|
| 788 |
|
| 789 |
if think:
|
|
|
|
| 794 |
decoded_line = line.decode("utf-8")
|
| 795 |
try:
|
| 796 |
data = json.loads(decoded_line)
|
| 797 |
+
# --- 1. Extract segment content ---
|
| 798 |
+
segment_content = ""
|
| 799 |
+
event_type = data.get("type")
|
| 800 |
|
| 801 |
+
if event_type == "collapsible_component":
|
| 802 |
+
if data.get("title"):
|
| 803 |
+
segment_content = f"{data.get('title')}\n"
|
| 804 |
+
if data.get("segment") and isinstance(data.get("segment"), dict):
|
| 805 |
+
if data.get("segment").get("segment"):
|
| 806 |
+
segment_content += data.get("segment").get("segment")
|
| 807 |
+
elif event_type == "text":
|
| 808 |
+
segment_content = data.get("segment", "")
|
| 809 |
+
else: # Ignore other event types
|
| 810 |
+
continue
|
| 811 |
+
|
| 812 |
+
if not segment_content: # Skip empty segments
|
| 813 |
+
continue
|
| 814 |
+
|
| 815 |
+
# --- 2. Determine message context ---
|
| 816 |
+
is_thinking_content = data.get("external", False)
|
| 817 |
+
current_message_id = data.get("messageId")
|
| 818 |
+
|
| 819 |
+
# --- 3. Process based on context ---
|
| 820 |
+
if is_thinking_content:
|
| 821 |
+
# --- Handle Thinking Content ---
|
| 822 |
+
if think_state == 2 and event_type == "collapsible_component": # Start of thinking
|
| 823 |
+
think_message_id = current_message_id
|
| 824 |
+
think_buffer.write(segment_content)
|
| 825 |
+
yield format_sse_chunk(json.dumps({'object': 'chat.completion.chunk', 'choices': [{'delta': {'content': segment_content}}]}))
|
| 826 |
+
think_state = 1
|
| 827 |
+
elif think_state == 1 and think_message_id == current_message_id: # Continuation of thinking
|
| 828 |
+
think_buffer.write(segment_content)
|
| 829 |
+
yield format_sse_chunk(json.dumps({'object': 'chat.completion.chunk', 'choices': [{'delta': {'content': segment_content}}]}))
|
| 830 |
+
# Ignore unexpected thinking content (e.g., type text when expecting collapsible, or wrong messageId)
|
| 831 |
else:
|
| 832 |
+
# --- Handle Non-Thinking Content (potential end of think + regular content) ---
|
| 833 |
+
if think_state == 1:
|
| 834 |
+
# Thinking just ended with this message
|
| 835 |
+
yield format_sse_chunk(json.dumps({'object': 'chat.completion.chunk', 'choices': [{'delta': {'content': "\n</think>\n"}}]})) # Yield closing tag first
|
| 836 |
+
content_buffer.write("\n</think>\n")
|
|
|
|
|
|
|
| 837 |
think_state = 0
|
| 838 |
think_message_id = None
|
| 839 |
|
| 840 |
+
# --- Apply code block processing to segment_content ---
|
| 841 |
+
parts = re.split('(```)', segment_content)
|
| 842 |
+
for part in parts:
|
| 843 |
+
if not part: continue # Skip empty parts from split
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 844 |
|
| 845 |
+
if part == '```':
|
| 846 |
+
if not code_block_active:
|
| 847 |
+
# Start of code block
|
| 848 |
+
code_block_active = True
|
| 849 |
+
content_buffer.write('```')
|
| 850 |
+
yield format_sse_chunk(json.dumps({'object': 'chat.completion.chunk', 'choices': [{'delta': {'content': '```'}}]}))
|
| 851 |
+
else:
|
| 852 |
+
# End of code block
|
| 853 |
+
code_block_active = False
|
| 854 |
+
content_buffer.write('```')
|
| 855 |
+
yield format_sse_chunk(json.dumps({'object': 'chat.completion.chunk', 'choices': [{'delta': {'content': '```'}}]}))
|
| 856 |
+
elif code_block_active:
|
| 857 |
+
# Inside code block
|
| 858 |
+
content_buffer.write(part)
|
| 859 |
+
yield format_sse_chunk(json.dumps({'object': 'chat.completion.chunk', 'choices': [{'delta': {'content': part}}]}))
|
| 860 |
+
else:
|
| 861 |
+
# Outside code block
|
| 862 |
+
content_buffer.write(part)
|
| 863 |
+
yield format_sse_chunk(json.dumps({'object': 'chat.completion.chunk', 'choices': [{'delta': {'content': part}}]}))
|
| 864 |
+
# --- End code block processing ---
|
| 865 |
+
|
| 866 |
except Exception as e:
|
| 867 |
print(f"处理响应出错: {e}")
|
| 868 |
|
| 869 |
+
# --- Final cleanup ---
|
| 870 |
+
# If thinking was active until the very end
|
|
|
|
|
|
|
|
|
|
| 871 |
if think and think_state == 1:
|
| 872 |
yield format_sse_chunk(json.dumps({"object": "chat.completion.chunk", "choices": [{"delta": {"content": "\n</think>\n"}}]}))
|
| 873 |
+
content_buffer.write("\n</think>\n") # Ensure buffer consistency
|
| 874 |
|
| 875 |
+
# Ensure any open code block is implicitly closed (though ideally the stream should provide the closing ```)
|
| 876 |
+
# if code_block_active:
|
| 877 |
+
# yield format_sse_chunk(json.dumps({'object': 'chat.completion.chunk', 'choices': [{'delta': {'content': '\n```'}}]}))
|
| 878 |
+
# content_buffer.write('\n```')
|
| 879 |
+
|
| 880 |
+
# ---- Token Calculation ----
|
| 881 |
print("\n----- 计算 Tokens (流式结束后) -----")
|
| 882 |
prompt_tokens, calculation_method = num_tokens_from_string(message, model)
|
| 883 |
print(f"输入 token 数: {prompt_tokens} (方法: {calculation_method})")
|
| 884 |
|
| 885 |
+
# Use content_buffer which should now accurately reflect the final output
|
| 886 |
completion_content = content_buffer.getvalue()
|
| 887 |
completion_tokens, comp_calc_method = num_tokens_from_string(completion_content, model)
|
| 888 |
print(f"输出 token 数: {completion_tokens} (方法: {comp_calc_method})")
|
| 889 |
|
|
|
|
| 890 |
final_calculation_method = "精确" if calculation_method == "精确" and comp_calc_method == "精确" else "估算"
|
| 891 |
+
|
|
|
|
| 892 |
yield format_sse_chunk(json.dumps({"object": "chat.completion.chunk", "choices": [{"delta": {}, "finish_reason": "stop"}]}))
|
| 893 |
yield format_sse_chunk("[DONE]")
|
| 894 |
|
|
|
|
| 895 |
_, compute_points_used = save_conversation_history(session, cookies, session_token, conversation_id)
|
|
|
|
|
|
|
| 896 |
update_model_stats(model, prompt_tokens, completion_tokens, final_calculation_method, compute_points_used)
|
| 897 |
|
| 898 |
# Use stream_with_context to ensure context is available during generation
|
|
|
|
| 953 |
for line in response.iter_lines():
|
| 954 |
if line:
|
| 955 |
decoded_line = line.decode("utf-8")
|
| 956 |
+
try:
|
| 957 |
+
data = json.loads(decoded_line)
|
| 958 |
+
segment = extract_segment(decoded_line)
|
| 959 |
+
if segment:
|
| 960 |
+
buffer.write(segment)
|
| 961 |
+
|
| 962 |
+
if data.get("type") == "text":
|
| 963 |
+
content_buffer.write(data["segment"])
|
| 964 |
+
except Exception as e:
|
| 965 |
+
print(f"重试中处理响应出错: {e}")
|
| 966 |
|
| 967 |
response_content = buffer.getvalue()
|
| 968 |
|
|
|
|
| 1105 |
think_state = 2
|
| 1106 |
think_buffer = io.StringIO()
|
| 1107 |
content_buffer = io.StringIO()
|
| 1108 |
+
code_block_active = False
|
| 1109 |
+
|
| 1110 |
content_buffer.write("<think>\n")
|
| 1111 |
|
| 1112 |
for line in response.iter_lines():
|
|
|
|
| 1114 |
decoded_line = line.decode("utf-8")
|
| 1115 |
try:
|
| 1116 |
data = json.loads(decoded_line)
|
| 1117 |
+
# --- 1. Extract segment content ---
|
| 1118 |
+
segment_content = ""
|
| 1119 |
+
event_type = data.get("type")
|
| 1120 |
|
| 1121 |
+
if event_type == "collapsible_component":
|
| 1122 |
+
if data.get("title"):
|
| 1123 |
+
segment_content = f"{data.get('title')}\n"
|
| 1124 |
+
if data.get("segment") and isinstance(data.get("segment"), dict):
|
| 1125 |
+
if data.get("segment").get("segment"):
|
| 1126 |
+
segment_content += data.get("segment").get("segment")
|
| 1127 |
+
elif event_type == "text":
|
| 1128 |
+
segment_content = data.get("segment", "")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1129 |
else:
|
| 1130 |
+
continue
|
| 1131 |
+
|
| 1132 |
+
if not segment_content:
|
| 1133 |
+
continue
|
| 1134 |
+
|
| 1135 |
+
# --- 2. Determine message context ---
|
| 1136 |
+
is_thinking_content = data.get("external", False)
|
| 1137 |
+
current_message_id = data.get("messageId")
|
| 1138 |
+
|
| 1139 |
+
# --- 3. Process based on context ---
|
| 1140 |
+
if is_thinking_content:
|
| 1141 |
+
# --- Handle Thinking Content ---
|
| 1142 |
+
if think_state == 2 and event_type == "collapsible_component": # Start of thinking
|
| 1143 |
+
think_message_id = current_message_id
|
| 1144 |
+
think_buffer.write(segment_content)
|
| 1145 |
+
think_state = 1
|
| 1146 |
+
elif think_state == 1 and think_message_id == current_message_id: # Continuation of thinking
|
| 1147 |
+
think_buffer.write(segment_content)
|
| 1148 |
+
else:
|
| 1149 |
+
# --- Handle Non-Thinking Content ---
|
| 1150 |
+
if think_state == 1:
|
| 1151 |
+
# Thinking just ended
|
| 1152 |
+
content_buffer.write("\n</think>\n")
|
| 1153 |
think_state = 0
|
| 1154 |
think_message_id = None
|
|
|
|
| 1155 |
|
| 1156 |
+
# --- Apply code block processing to segment_content ---
|
| 1157 |
+
parts = re.split('(```)', segment_content)
|
| 1158 |
+
for part in parts:
|
| 1159 |
+
if not part: continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1160 |
|
| 1161 |
+
if part == '```':
|
| 1162 |
+
if not code_block_active:
|
| 1163 |
+
code_block_active = True
|
| 1164 |
+
content_buffer.write('```')
|
| 1165 |
+
else:
|
| 1166 |
+
code_block_active = False
|
| 1167 |
+
content_buffer.write('```')
|
| 1168 |
+
else:
|
| 1169 |
+
# Write content inside or outside code block
|
| 1170 |
+
content_buffer.write(part)
|
| 1171 |
+
# --- End code block processing ---
|
| 1172 |
+
|
| 1173 |
except Exception as e:
|
| 1174 |
print(f"处理响应出错: {e}")
|
| 1175 |
|
| 1176 |
+
# --- Final cleanup ---
|
| 1177 |
if think_state == 1:
|
| 1178 |
content_buffer.write("\n</think>\n")
|
| 1179 |
|
| 1180 |
think_content = think_buffer.getvalue()
|
| 1181 |
response_content = content_buffer.getvalue()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1182 |
else:
|
| 1183 |
+
# --- Non-Thinking Mode ---
|
| 1184 |
buffer = io.StringIO()
|
| 1185 |
+
code_block_active = False
|
| 1186 |
|
| 1187 |
for line in response.iter_lines():
|
| 1188 |
if line:
|
| 1189 |
decoded_line = line.decode("utf-8")
|
| 1190 |
try:
|
| 1191 |
data = json.loads(decoded_line)
|
| 1192 |
+
# --- Extract segment ---
|
| 1193 |
+
segment_content = ""
|
| 1194 |
+
if data.get("type") == "text": # Only process text in non-thinking mode
|
| 1195 |
+
segment_content = data.get("segment", "")
|
| 1196 |
+
else:
|
| 1197 |
+
continue
|
| 1198 |
|
| 1199 |
+
if not segment_content:
|
| 1200 |
+
continue
|
| 1201 |
+
|
| 1202 |
+
# --- Apply code block processing ---
|
| 1203 |
+
parts = re.split('(```)', segment_content)
|
| 1204 |
+
for part in parts:
|
| 1205 |
+
if not part: continue
|
| 1206 |
+
|
| 1207 |
+
if part == '```':
|
| 1208 |
+
if not code_block_active:
|
| 1209 |
+
code_block_active = True
|
| 1210 |
+
buffer.write('```')
|
| 1211 |
+
else:
|
| 1212 |
+
code_block_active = False
|
| 1213 |
+
buffer.write('```')
|
| 1214 |
+
else:
|
| 1215 |
+
buffer.write(part)
|
| 1216 |
+
# --- End code block processing ---
|
| 1217 |
|
|
|
|
|
|
|
| 1218 |
except Exception as e:
|
| 1219 |
print(f"处理响应出错: {e}")
|
| 1220 |
|
| 1221 |
response_content = buffer.getvalue()
|
| 1222 |
|
| 1223 |
+
# ---- Token 计算 ----
|
| 1224 |
+
print("\n----- 计算 Tokens (非流式, think模式) -----")
|
| 1225 |
+
prompt_tokens, calculation_method = num_tokens_from_string(message, model)
|
| 1226 |
+
print(f"输入 token 数: {prompt_tokens} (方法: {calculation_method})")
|
| 1227 |
+
# 计算输出token并更新统计信息
|
| 1228 |
+
completion_tokens, comp_calc_method = num_tokens_from_string(think_content + response_content, model)
|
| 1229 |
+
print(f"输出 token 数: {completion_tokens} (方法: {comp_calc_method})")
|
| 1230 |
+
# 决定最终使用的计算方法
|
| 1231 |
+
final_calculation_method = "精确" if calculation_method == "精确" and comp_calc_method == "精确" else "估算"
|
| 1232 |
+
# ---- Token 计算结束 ----
|
| 1233 |
+
|
| 1234 |
+
# 保存对话历史并获取计算点数
|
| 1235 |
+
_, compute_points_used = save_conversation_history(session, cookies, session_token, conversation_id)
|
| 1236 |
+
|
| 1237 |
+
# 更新统计信息
|
| 1238 |
+
update_model_stats(model, prompt_tokens, completion_tokens, final_calculation_method, compute_points_used)
|
| 1239 |
+
|
| 1240 |
+
return jsonify({
|
| 1241 |
+
"id": f"chatcmpl-{str(uuid.uuid4())}",
|
| 1242 |
+
"object": "chat.completion",
|
| 1243 |
+
"created": int(time.time()),
|
| 1244 |
+
"model": model,
|
| 1245 |
+
"choices": [{
|
| 1246 |
+
"index": 0,
|
| 1247 |
+
"message": {
|
| 1248 |
+
"role": "assistant",
|
| 1249 |
+
"content": response_content # 这里是完整的响应,包括思维链
|
| 1250 |
+
},
|
| 1251 |
+
"finish_reason": "stop"
|
| 1252 |
+
}],
|
| 1253 |
+
"usage": {
|
| 1254 |
+
"prompt_tokens": prompt_tokens,
|
| 1255 |
+
"completion_tokens": completion_tokens,
|
| 1256 |
+
"total_tokens": prompt_tokens + completion_tokens
|
| 1257 |
+
}
|
| 1258 |
+
})
|
| 1259 |
except requests.exceptions.RequestException as e:
|
| 1260 |
error_details = str(e)
|
| 1261 |
if hasattr(e, 'response') and e.response is not None:
|