chatApi.ts
42.5 KB
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
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
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
import { defineStore } from "pinia";
import { triggerNewbieTask } from "@/utils/newbieTask";
import {
askQuestion,
streamAnswer,
listChats as apiListChats,
createChat as apiCreateChat,
deleteChat as apiDeleteChat,
listMessages as apiListMessages,
} from "@/api/chat";
// 预处理函数:将方括号包裹的数学公式转换为 $$ 符号格式
function preprocessMathContent(content: string): string {
if (!content) return content;
let processed = content;
// 转义反斜杠的辅助函数:\ 转义为 \\,\\ 转义为 \\\\
// 被保护的分隔符(临时标记)不会被转义,因为临时标记中没有反斜杠
const escapeBackslashes = (str: string): string => {
// 先转义 \\\\ 为临时标记,避免被后续处理影响
let result = str.replace(/\\\\/g, "____DOUBLE_BACKSLASH____");
// 转义单个反斜杠,但跳过被保护的分隔符
// 由于临时标记中不包含反斜杠,所以不会被影响
result = result.replace(/\\/g, "\\\\");
// 恢复双反斜杠
result = result.replace(/____DOUBLE_BACKSLASH____/g, "\\\\\\\\");
return result;
};
// 修复 \left 和 \right 后面缺少分隔符的问题
// \left 和 \right 必须紧跟分隔符,如 \(、\)、[、]、{、}、| 等
const fixLeftRightDelimiters = (formula: string): string => {
let fixed = formula;
// 修复 \left 后面缺少分隔符的情况
// 匹配 \left 后面是空格、换行、或非分隔符字符的情况
// 分隔符包括:\(、\[、\{、|、. 等
fixed = fixed.replace(/\\left(\s+)(?=\S)/gi, (_match, spaces) => {
// \left 后面有空格,且空格后是非空白字符,在空格后添加 \(
return `\\left${spaces}\\(`;
});
// 匹配 \left 后面直接是非分隔符字符(不是 \(、\[、\{、|、.)
fixed = fixed.replace(/\\left(?!\s*[(\[{|.\\])/gi, () => {
// \left 后面没有分隔符,添加 \(
return `\\left\\(`;
});
// 修复 \right 后面缺少分隔符的情况
// 匹配 \right 后面是空格、换行、或非分隔符字符的情况
// 分隔符包括:\)、\]、\}、|、. 等
fixed = fixed.replace(/\\right(\s+)(?=\S)/gi, (_match, spaces) => {
// \right 后面有空格,且空格后是非空白字符,在空格后添加 \)
return `\\right${spaces}\\)`;
});
// 匹配 \right 后面直接是非分隔符字符(不是 \)、\]、\}|、.)
fixed = fixed.replace(/\\right(?!\s*[)\]}|.\\])/gi, () => {
// \right 后面没有分隔符,添加 \)
return `\\right\\)`;
});
return fixed;
};
// 保护包含 \left 的公式内部的 \( 和 \[,以及 \left[ 和 \right] 中的方括号
// 避免被转义和转换为 $
const protectInnerDelimiters = (formula: string): string => {
// 检查是否包含 \left
if (!/\\left/i.test(formula)) {
return formula;
}
// 如果包含 \left,先保护 \left[ 和 \right] 中的方括号(优先级最高)
// 使用临时标记替换,后续会恢复为原始形式(不转义)
let protectedFormula = formula
.replace(/\\left\[/g, "____LEFT_BRACKET_OPEN____")
.replace(/\\right\]/g, "____RIGHT_BRACKET_CLOSE____")
.replace(/\\left\{/g, "____LEFT_BRACE_OPEN____")
.replace(/\\right\}/g, "____RIGHT_BRACE_CLOSE____")
.replace(/\\left\(/g, "____LEFT_PAREN_OPEN____")
.replace(/\\right\)/g, "____RIGHT_PAREN_CLOSE____")
.replace(/\\left\|/g, "____LEFT_PIPE_OPEN____")
.replace(/\\right\|/g, "____RIGHT_PIPE_CLOSE____");
// 然后保护其他内部的 \( 和 \[
protectedFormula = protectedFormula
.replace(/\\\(/g, "____INNER_PAREN_OPEN____")
.replace(/\\\)/g, "____INNER_PAREN_CLOSE____")
.replace(/\\\[/g, "____INNER_BRACKET_OPEN____")
.replace(/\\\]/g, "____INNER_BRACKET_CLOSE____");
return protectedFormula;
};
// 恢复被保护的内部分隔符(恢复为原始形式,不转义)
// 注意:在字符串中,\\( 表示字符串 \((一个反斜杠+左括号)
const restoreInnerDelimiters = (formula: string): string => {
// 先恢复 \left[ 和 \right] 等(优先级最高)
let restored = formula
.replace(/____LEFT_BRACKET_OPEN____/g, "\\left\[")
.replace(/____RIGHT_BRACKET_CLOSE____/g, "\\right\]")
.replace(/____LEFT_BRACE_OPEN____/g, "\\left\{")
.replace(/____RIGHT_BRACE_CLOSE____/g, "\\right\}")
.replace(/____LEFT_PAREN_OPEN____/g, "\\left\(")
.replace(/____RIGHT_PAREN_CLOSE____/g, "\\right\)")
.replace(/____LEFT_PIPE_OPEN____/g, "\\left\|")
.replace(/____RIGHT_PIPE_CLOSE____/g, "\\right\|");
// 然后恢复其他内部分隔符
restored = restored
.replace(/____INNER_PAREN_OPEN____/g, "\\(")
.replace(/____INNER_PAREN_CLOSE____/g, "\\)")
.replace(/____INNER_BRACKET_OPEN____/g, "\\[")
.replace(/____INNER_BRACKET_CLOSE____/g, "\\]");
return restored;
};
// 1. 处理带反斜杠的块级数学公式:\[ ... \] 转换为 $$ ... $$
processed = processed.replace(/\\\[([\s\S]*?)\\\]/g, (_match, formula) => {
// 先修复 \left 和 \right 后面缺少分隔符的问题
let fixedFormula = fixLeftRightDelimiters(formula);
// 如果公式包含 \left,保护内部的 \( 和 \[
const protectedFormula = protectInnerDelimiters(fixedFormula);
// 转义反斜杠(被保护的分隔符不会被转义,因为临时标记中没有反斜杠)
const escapedFormula = escapeBackslashes(protectedFormula);
// 恢复被保护的内部分隔符(恢复为原始形式,不转义)
const restoredFormula = restoreInnerDelimiters(escapedFormula);
return `$$${restoredFormula}$$`;
});
// 2. 处理带反斜杠的行内数学公式:\( ... \) 转换为 $ ... $
processed = processed.replace(/\\\(([\s\S]*?)\\\)/g, (_match, formula) => {
// 先修复 \left 和 \right 后面缺少分隔符的问题
let fixedFormula = fixLeftRightDelimiters(formula);
// 如果公式包含 \left,保护内部的 \( 和 \[
const protectedFormula = protectInnerDelimiters(fixedFormula);
// 转义反斜杠(被保护的分隔符不会被转义,因为临时标记中没有反斜杠)
const escapedFormula = escapeBackslashes(protectedFormula);
// 恢复被保护的内部分隔符(恢复为原始形式,不转义)
const restoredFormula = restoreInnerDelimiters(escapedFormula);
return `$${restoredFormula}$`;
});
// 3. 处理纯方括号包裹的数学公式:[ ... ] 转换为 $$ ... $$(支持多行)
// 只处理包含 LaTeX 命令的方括号内容,保留中间的换行符和空格
processed = processed.replace(/\[[\s\S]*?\]/g, (match) => {
// 先保护 \left[ 和 \right] 中的方括号,避免被误处理
let protectedMatch = match
.replace(/\\left\[/g, "____PROTECT_LEFT_BRACKET____")
.replace(/\\right\]/g, "____PROTECT_RIGHT_BRACKET____");
// 检查保护后的内容是否还包含方括号(即外层的 [ ... ])
const bracketMatch = protectedMatch.match(/^\[([\s\S]*)\]$/);
if (!bracketMatch || !bracketMatch[1]) {
// 如果没有外层方括号,恢复保护并返回原样
return protectedMatch
.replace(/____PROTECT_LEFT_BRACKET____/g, "\\left\[")
.replace(/____PROTECT_RIGHT_BRACKET____/g, "\\right\]");
}
const formula = bracketMatch[1]; // 去掉首尾的方括号
// 恢复被保护的 \left[ 和 \right]
const restoredFormula = formula
.replace(/____PROTECT_LEFT_BRACKET____/g, "\\left\[")
.replace(/____PROTECT_RIGHT_BRACKET____/g, "\\right\]");
// 检查是否包含 LaTeX 命令
if (
/\\(mathbf|begin\{|end\{|frac|times|sqrt|sum|int|alpha|beta|gamma|theta|lambda|mu|sigma|pi|Delta|Omega|left|right)/i.test(
restoredFormula,
)
) {
// 修复百分号:将未转义的 % 转义为 \%(避免被当作 LaTeX 注释)
let fixedFormula = formula.replace(/(?<!\\)%/g, "\\%");
// 直接将 [ 替换为 $$,] 替换为 $$,保留中间所有内容(包括 \n 和空格)
return `$$${fixedFormula}$$`;
}
// 如果不包含 LaTeX 命令,恢复保护并保持原样
return match
.replace(/____PROTECT_LEFT_BRACKET____/g, "\\left\[")
.replace(/____PROTECT_RIGHT_BRACKET____/g, "\\right\]");
});
return processed;
}
// Interfaces for better type safety
interface Session {
sessionId: string | number;
id: string | number;
title: string;
preview: string;
messageCount: number;
lastActivity: string;
createdAt: string;
updatedAt: string;
status: string;
agentId: string | null;
agentName: string;
}
interface Answer {
id: string;
questionId: string;
answerContent: string;
createdAt: string;
status: "thinking" | "typing" | "completed" | "error";
agentId?: string;
agentName?: string;
actions?: any[];
// 百川模型专用字段
thinking?: {
status: "in_progress" | "completed";
content?: string;
steps?: Array<{
kind: "reasoning" | "searching" | "synthesizing";
status: "in_progress" | "completed";
label: string;
}>;
};
grounding?: Array<{
title?: string;
content?: string;
url?: string;
[key: string]: any;
}>;
isComplete?: boolean; // 标记回答是否完成(用于百川模型)
}
interface Message {
questionId: string;
question: string;
questionCreatedAt: string;
chatId?: string | number;
answers: Answer[];
}
interface EventSourceHandle {
close: () => void;
}
interface ChatApiState {
userId: string | null;
sessions: Session[];
currentSession: Session | null;
sessionsLoading: boolean;
sessionsError: string | null;
messages: Message[];
messagesLoading: boolean;
messagesError: string | null;
streamingAnswer: boolean;
streamingError: string | null;
aiThinking: boolean;
typewriterMode: boolean;
eventSources: { [chatId: string | number]: EventSourceHandle };
selectedModel: string; // 选中的模型:doubao 或 baichuan
chatDraft: string; // 聊天框草稿
}
type ChatApiActions = {
setUserId(userId: string | null): void;
setSelectedModel(model: string): void;
setChatDraft(draft: string): void;
fetchSessions(): Promise<void>;
createSession(
title?: string,
): Promise<{ success: boolean; data?: Session; error?: string }>;
deleteSession(
sessionId: string | number,
): Promise<{ success: boolean; error?: string }>;
clearAllSessions(): Promise<{ success: boolean; error?: string }>;
selectSession(payload: {
session: Session;
fetchMessages?: boolean;
}): Promise<void>;
clearCurrentSession(): void;
fetchMessages(chatId: string | number): Promise<void>;
addMessage(message: Message): void;
updateMessageId(payload: { oldId: string; newId: string }): void;
appendAnswerChunk(payload: { questionId: string; chunk: string }): void;
completeAnswer(questionId: string): void;
updateMessageStatus(payload: {
questionId: string;
status: "thinking" | "typing" | "completed" | "error";
content?: string;
}): void;
clearMessages(): void;
setStreamingAnswer(b: boolean): void;
setStreamingError(e: string | null): void;
setAiThinking(b: boolean): void;
setTypewriterMode(b: boolean): void;
addEventSource(payload: {
chatId: string | number;
sub: EventSourceHandle;
}): void;
removeEventSource(chatId: string | number): void;
closeAllEventSources(): void;
clearErrors(): void;
sendMessage(payload: {
sessionId: string | number;
question: string;
context?: any[];
provider?: "baichuan" | "doubao";
}): Promise<{
success: boolean;
data?: { questionId: string };
error?: string;
}>;
startStreamingAnswer(payload: {
chatId: string | number;
questionId: string;
externalQuestionId: string;
provider?: "baichuan" | "doubao";
}): Promise<void>;
handleBaichuanThinking(payload: {
questionId: string;
thinkingData: any;
}): void;
handleBaichuanGrounding(payload: {
questionId: string;
groundingData: any;
}): void;
startTypewriterEffect(_payload: {
questionId: string;
content: string;
}): void;
};
const commonStoreDefinition: {
state: () => ChatApiState;
getters: Record<string, never>;
actions: ChatApiActions & ThisType<ChatApiState & ChatApiActions>;
} = {
state: (): ChatApiState => ({
userId: null,
sessions: [],
currentSession: null,
sessionsLoading: false,
sessionsError: null,
messages: [],
messagesLoading: false,
messagesError: null,
streamingAnswer: false,
streamingError: null,
aiThinking: false,
typewriterMode: false,
eventSources: {},
selectedModel: "doubao", // 默认选择豆包模型
chatDraft: "",
}),
getters: {},
actions: {
setUserId(userId: string | null) {
this.userId = userId;
},
setSelectedModel(model: string) {
this.selectedModel = model;
},
setChatDraft(draft: string) {
this.chatDraft = draft;
},
// Sessions
async fetchSessions() {
try {
this.sessionsLoading = true;
this.sessionsError = null;
const response = await apiListChats({
page: 0,
size: 20,
provider: "external",
});
const data = response.data;
const formatted: Session[] = (Array.isArray(data) ? data : []).map(
(s) => {
// 优先展示问题内容作为标题,如果 title 是默认生成的则使用 question
const isDefaultTitle = !s.title || s.title === "新会话" || s.title === "新对话" || s.title.startsWith("会话 ");
const displayTitle = (isDefaultTitle && s.question) ? s.question : (s.title || s.question || "新会话");
return {
sessionId: s.id,
id: s.id,
title: displayTitle,
preview: "",
messageCount: 0,
lastActivity: s.createdAt,
createdAt: s.createdAt,
updatedAt: s.createdAt,
status: s.deleted ? "DELETED" : "ACTIVE",
agentId: null,
agentName: "LinkMed AI助手",
};
},
);
this.sessions = formatted;
} catch (e: any) {
this.sessionsError = e.message || String(e);
} finally {
this.sessionsLoading = false;
}
},
async createSession(
title: string = "新会话",
): Promise<{ success: boolean; data?: Session; error?: string }> {
try {
const response = await apiCreateChat({ title });
const created = response.data;
const session: Session = {
sessionId: created.id,
id: created.id,
title: created.title || title,
preview: "",
messageCount: 0,
lastActivity: created.createdAt,
createdAt: created.createdAt,
updatedAt: created.createdAt,
status: created.deleted ? "DELETED" : "ACTIVE",
agentId: null,
agentName: "LinkMed AI助手",
};
this.sessions.unshift(session);
return { success: true, data: session };
} catch (e: any) {
console.error("[createSession] 失败:", e);
return { success: false, error: e.message || String(e) };
}
},
async deleteSession(
sessionId: string | number,
): Promise<{ success: boolean; error?: string }> {
try {
await apiDeleteChat(sessionId);
this.sessions = this.sessions.filter(
(s: Session) => (s.sessionId ?? s.id) !== sessionId,
);
if (
this.currentSession &&
(this.currentSession.sessionId ?? this.currentSession.id) ===
sessionId
) {
this.currentSession = null;
this.messages = [];
}
return { success: true };
} catch (e: any) {
console.error("deleteSession failed:", e);
return { success: false, error: e.message || String(e) };
}
},
async clearAllSessions(): Promise<{ success: boolean; error?: string }> {
try {
const sessionIdsToDelete = this.sessions.map(
(s: Session) => s.sessionId ?? s.id,
);
for (const sessionId of sessionIdsToDelete) {
await apiDeleteChat(sessionId);
}
this.sessions = [];
this.currentSession = null;
this.messages = [];
return { success: true };
} catch (e: any) {
console.error("clearAllSessions failed:", e);
return { success: false, error: e.message || String(e) };
}
},
async selectSession(payload: {
session: Session;
fetchMessages?: boolean;
}) {
this.currentSession = payload.session;
if (payload.session && payload.fetchMessages) {
await this.fetchMessages(
payload.session.sessionId ?? payload.session.id,
);
}
},
clearCurrentSession() {
this.currentSession = null;
this.messages = [];
},
// Messages
async fetchMessages(chatId: string | number) {
try {
this.messagesLoading = true;
this.messagesError = null;
// 保存当前正在进行的流式消息(状态为 thinking 或 typing,且 isComplete 为 false)
const streamingMessages = this.messages.filter((msg) => {
// 检查是否有正在进行的回答
return (
msg.answers &&
msg.answers.some(
(answer) =>
(answer.status === "thinking" ||
answer.status === "typing" ||
answer.isComplete === false) &&
answer.status !== "error",
)
);
});
// 创建流式消息的映射,以 questionId 为 key
const streamingMessagesMap = new Map<string, Message>();
streamingMessages.forEach((msg) => {
streamingMessagesMap.set(msg.questionId, msg);
});
const response = await apiListMessages(chatId, { limit: 200 });
const list = response.data;
const serverMessages: Message[] = (list || []).map((turn: any) => {
// 解析 evidence 字段(百川模型返回的引用数据)
let grounding: any[] | undefined;
if (turn.evidence) {
try {
const evidenceData =
typeof turn.evidence === "string"
? JSON.parse(turn.evidence)
: turn.evidence;
if (Array.isArray(evidenceData) && evidenceData.length > 0) {
grounding = evidenceData.map((item: any) => ({
title: item.title || item.title_zh || "未命名引用",
content: item.publication_info || item.author || "",
url: item.url || "",
refNum: item.ref_num,
evidenceClass: item.evidence_class,
author: item.author,
}));
}
} catch (error) {
console.error("[fetchMessages] 解析 evidence 失败:", error);
}
}
return {
questionId: turn.questionId,
question: turn.question,
questionCreatedAt:
turn.questionTime || turn.createdAt || new Date().toISOString(),
answers: turn.answer
? [
{
id: `${turn.questionId}_answer`,
questionId: turn.questionId,
answerContent: preprocessMathContent(turn.answer), // 预处理数学公式
createdAt: turn.answerTime || new Date().toISOString(),
status: "completed" as const,
agentId: "default",
agentName: "AI助手",
grounding: grounding, // 添加 grounding 字段
isComplete: true, // 历史消息都是完成状态
},
]
: [],
};
});
// 合并服务器消息和本地流式消息
const mergedMessages: Message[] = [];
const processedQuestionIds = new Set<string>();
// 先添加流式消息(保留正在进行的消息)
streamingMessages.forEach((streamingMsg) => {
mergedMessages.push(streamingMsg);
processedQuestionIds.add(streamingMsg.questionId);
});
// 然后添加服务器消息(只添加不在流式消息中的,或已完成的消息)
serverMessages.forEach((serverMsg) => {
if (!processedQuestionIds.has(serverMsg.questionId)) {
// 服务器消息不在流式消息中,直接添加
mergedMessages.push(serverMsg);
processedQuestionIds.add(serverMsg.questionId);
} else {
// 服务器消息与流式消息有相同的 questionId
// 检查流式消息是否已完成,如果已完成则用服务器消息替换
const streamingMsg = streamingMessagesMap.get(serverMsg.questionId);
if (streamingMsg) {
const hasIncompleteAnswer = streamingMsg.answers?.some(
(answer) =>
(answer.status === "thinking" ||
answer.status === "typing" ||
answer.isComplete === false) &&
answer.status !== "error",
);
if (!hasIncompleteAnswer) {
// 流式消息已完成,用服务器消息替换(服务器消息可能包含更完整的数据)
const index = mergedMessages.findIndex(
(m) => m.questionId === serverMsg.questionId,
);
if (index !== -1) {
mergedMessages[index] = serverMsg;
}
}
// 如果流式消息未完成,保留流式消息,不替换
}
}
});
// 按时间排序(questionCreatedAt)
mergedMessages.sort((a, b) => {
const timeA = new Date(a.questionCreatedAt).getTime();
const timeB = new Date(b.questionCreatedAt).getTime();
return timeA - timeB;
});
this.messages = mergedMessages.filter((m) => !!m.question);
} catch (e: any) {
this.messagesError = e.message || String(e);
} finally {
this.messagesLoading = false;
}
},
addMessage(message: Message) {
this.messages.push(message);
},
updateMessageId(payload: { oldId: string; newId: string }) {
const msg = this.messages.find(
(x: Message) => x.questionId === payload.oldId,
);
if (msg) {
msg.questionId = payload.newId;
if (msg.answers && msg.answers.length > 0 && msg.answers[0]) {
msg.answers[0].questionId = payload.newId;
}
}
},
appendAnswerChunk(payload: { questionId: string; chunk: string }) {
if (
!payload.chunk ||
payload.chunk === "Question is still being processed" ||
payload.chunk === "UPSTREAM_ERROR: Connection reset"
)
return;
let msg = this.messages.find(
(m: Message) => m.questionId === payload.questionId,
);
if (!msg && this.messages.length)
msg = this.messages[this.messages.length - 1];
if (!msg) return;
if (!msg.answers || !msg.answers.length) {
msg.answers = [
{
id: `answer_${Date.now()}`,
questionId: payload.questionId,
answerContent: payload.chunk, // 不再在追加时进行重度预处理
createdAt: new Date().toISOString(),
status: "typing",
},
];
return;
}
const last = msg.answers[msg.answers.length - 1];
if (last && last.status === "thinking" && payload.chunk.trim()) {
last.status = "typing";
}
if (last) {
// 直接追加原始 chunk
last.answerContent = (last.answerContent || "") + payload.chunk;
}
},
completeAnswer(questionId: string) {
const m = this.messages.find((x: Message) => x.questionId === questionId);
if (m?.answers?.length) {
const lastAnswer = m.answers[m.answers.length - 1];
if (lastAnswer) {
lastAnswer.status = "completed";
lastAnswer.isComplete = true; // 标记回答完成
}
}
},
updateMessageStatus(payload: {
questionId: string;
status: "thinking" | "typing" | "completed" | "error";
content?: string;
}) {
let msg = this.messages.find(
(m: Message) => m.questionId === payload.questionId,
);
if (!msg)
msg = this.messages.find(
(m: Message) => m.answers?.[0]?.status === "thinking",
);
if (!msg && this.messages.length)
msg = this.messages[this.messages.length - 1];
if (msg?.answers?.length && msg.answers[0]) {
const updatedAnswer = {
...msg.answers[0],
status: payload.status,
...(payload.content && {
answerContent: preprocessMathContent(payload.content), // 预处理数学公式
}),
};
const updatedMsg = { ...msg, answers: [updatedAnswer] };
const i = this.messages.findIndex(
(m: Message) => m.questionId === msg!.questionId,
);
if (i !== -1) this.messages.splice(i, 1, updatedMsg);
}
},
clearMessages() {
this.messages = [];
},
// Streaming/Thinking/Typewriter
setStreamingAnswer(b: boolean) {
this.streamingAnswer = b;
},
setStreamingError(e: string | null) {
this.streamingError = e;
},
setAiThinking(b: boolean) {
this.aiThinking = b;
},
setTypewriterMode(b: boolean) {
this.typewriterMode = b;
},
// EventSource management
addEventSource(payload: {
chatId: string | number;
sub: EventSourceHandle;
}) {
this.eventSources = {
...this.eventSources,
[payload.chatId]: payload.sub,
};
},
removeEventSource(chatId: string | number) {
const { [chatId]: removed, ...rest } = this.eventSources;
this.eventSources = rest;
},
closeAllEventSources() {
Object.entries(this.eventSources).forEach(
([chatId, sub]: [string, EventSourceHandle]) => {
try {
sub?.close?.();
} catch {}
this.removeEventSource(chatId);
},
);
this.streamingAnswer = false;
this.aiThinking = false;
},
clearErrors() {
this.sessionsError = null;
this.messagesError = null;
this.streamingError = null;
this.aiThinking = false;
this.typewriterMode = false;
},
async sendMessage(payload: {
sessionId?: string | number; // 设为可选
question: string;
context?: any[];
provider?: "baichuan" | "doubao"; // 显式指定 provider,如果不传则根据 selectedModel 决定
}): Promise<{
success: boolean;
data?: { questionId: string };
error?: string;
}> {
let currentSessionId = payload.sessionId;
// 如果没有提供 sessionId,先创建一个新会话
if (!currentSessionId) {
const title =
payload.question.substring(0, 20) +
(payload.question.length > 20 ? "..." : "");
const createResult = await this.createSession(title);
if (createResult.success && createResult.data) {
currentSessionId = createResult.data.sessionId || createResult.data.id;
// 选择新创建的会话
await this.selectSession({
session: createResult.data,
fetchMessages: false,
});
} else {
return {
success: false,
error: createResult.error || "创建会话失败",
};
}
}
let tempId: string;
const last = this.messages[this.messages.length - 1];
if (
last &&
last.question === payload.question &&
last.answers?.[0]?.status === "thinking"
) {
tempId = last.questionId;
} else {
tempId = `temp_${Date.now()}`;
this.addMessage({
questionId: tempId,
question: payload.question,
questionCreatedAt: new Date().toISOString(),
answers: [
{
id: `answer_${Date.now()}`,
questionId: tempId,
answerContent: "",
createdAt: new Date().toISOString(),
status: "thinking",
isComplete: false, // 初始化为未完成
},
],
});
}
try {
this.messagesLoading = true;
this.messagesError = null;
this.aiThinking = true;
this.streamingError = null;
// 确保 chatId 是有效的数字
const chatId = Number(currentSessionId);
if (isNaN(chatId) || chatId <= 0) {
throw new Error(`无效的会话ID: ${currentSessionId}`);
}
// 确保 fileIds 是数组,并尝试将字符串 ID 转换为数字
const fileIds = Array.isArray(payload.context)
? payload.context
.map((id) => (typeof id === "string" ? parseInt(id, 10) : id))
.filter((id) => typeof id === "number" && !isNaN(id))
: [];
// 根据显式传递的 provider 或选中的模型决定是否传递 provider 参数
const requestPayload: any = {
chatId,
questionContent: payload.question,
fileIds,
};
// 优先使用显式传递的 provider,否则根据 selectedModel 决定
if (payload.provider) {
requestPayload.provider = payload.provider;
} else if (this.selectedModel === "baichuan") {
requestPayload.provider = "baichuan";
}
const response = await askQuestion(requestPayload);
// 如果当前会话标题是默认的(虽然现在创建时已经设置了,但为了保险起见),将其更新为问题的简简短描述
const sessionInList = this.sessions.find(
(s) => (s.sessionId || s.id) === currentSessionId,
);
if (
sessionInList &&
(!sessionInList.title ||
sessionInList.title === "新会话" ||
sessionInList.title === "新对话" ||
sessionInList.title.startsWith("会话 "))
) {
const newTitle =
payload.question.substring(0, 20) +
(payload.question.length > 20 ? "..." : "");
sessionInList.title = newTitle;
if (
this.currentSession &&
(this.currentSession.sessionId || this.currentSession.id) ===
currentSessionId
) {
this.currentSession.title = newTitle;
}
}
// 兼容不同的响应结构:resp?.data?.questionId || resp?.questionId
const qid =
(response.data as any)?.data?.questionId ||
(response.data as any)?.questionId;
const eqid =
(response.data as any)?.data?.externalQuestionId ||
(response.data as any)?.externalQuestionId;
if (!eqid) {
throw new Error("未返回 externalQuestionId");
}
this.updateMessageId({ oldId: tempId, newId: qid });
await this.startStreamingAnswer({
chatId: currentSessionId,
questionId: qid,
externalQuestionId: eqid,
provider: payload.provider, // 传递 provider 参数到流式获取
});
return { success: true, data: { questionId: qid } };
} catch (e: any) {
this.messagesError = e.message || String(e);
this.aiThinking = false;
this.updateMessageStatus({
questionId: tempId,
status: "error",
content: "发送失败",
});
return { success: false, error: e.message || String(e) };
} finally {
this.messagesLoading = false;
}
},
async startStreamingAnswer(payload: {
chatId: string | number;
questionId: string;
externalQuestionId: string;
provider?: "baichuan" | "doubao"; // 显式指定 provider,如果不传则根据 selectedModel 决定
}) {
const prev = this.eventSources[payload.chatId];
if (prev?.close) {
try {
prev.close();
} catch {}
this.removeEventSource(payload.chatId);
}
this.streamingAnswer = true;
this.streamingError = null;
let sub: any = null;
let selectedProvider: any;
if (payload.provider) {
selectedProvider = payload.provider;
} else if (this.selectedModel === "baichuan") {
selectedProvider = "baichuan";
}
// 构建 streamAnswer 的参数,根据 selectedModel 决定是否传递 provider
const streamOptions: any = {
chatId: payload.chatId,
questionId: payload.questionId,
externalQuestionId: payload.externalQuestionId,
onOpen: () => {},
onMessage: (evt: any) => {
// 处理字符串类型的消息(兼容旧格式)
if (typeof evt === "string") {
this.appendAnswerChunk({
questionId: payload.questionId,
chunk: evt,
});
return;
}
// 百川模型专用:处理 thinking 事件
if ((evt as any)?.type === "thinking") {
this.handleBaichuanThinking({
questionId: payload.questionId,
thinkingData: (evt as any).thinking,
});
return;
}
// 百川模型专用:处理 grounding 事件(引用)
if ((evt as any)?.type === "grounding") {
this.handleBaichuanGrounding({
questionId: payload.questionId,
groundingData: (evt as any).grounding,
});
return;
}
// 处理错误类型:将错误消息替换为友好的提示
if ((evt as any)?.type === "error") {
const friendlyErrorMessage = "快问快答系统修复中...";
// 查找对应的消息
const msg = this.messages.find(
(m: Message) => m.questionId === payload.questionId,
);
if (msg) {
if (msg.answers && msg.answers.length > 0) {
const lastAnswer = msg.answers[msg.answers.length - 1];
if (
lastAnswer &&
!lastAnswer.answerContent?.includes(friendlyErrorMessage)
) {
// 设置错误状态
lastAnswer.status = "error";
// 如果回答内容为空或不存在,直接设置;否则追加
if (
!lastAnswer.answerContent ||
lastAnswer.answerContent.trim() === ""
) {
lastAnswer.answerContent =
preprocessMathContent(friendlyErrorMessage);
} else {
// 检查是否已经包含原始错误消息,如果包含则替换
const originalErrorMsg = (evt as any)?.message || "";
if (
originalErrorMsg &&
lastAnswer.answerContent.includes(originalErrorMsg)
) {
// 替换原始错误消息为友好提示
lastAnswer.answerContent = preprocessMathContent(
lastAnswer.answerContent.replace(
originalErrorMsg,
friendlyErrorMessage,
),
);
} else {
lastAnswer.answerContent = preprocessMathContent(
lastAnswer.answerContent +
"\n\n" +
friendlyErrorMessage,
);
}
}
}
} else {
// 如果没有回答,创建一个新的回答来显示错误
msg.answers = [
{
id: `answer_${Date.now()}`,
questionId: payload.questionId,
answerContent: preprocessMathContent(friendlyErrorMessage),
createdAt: new Date().toISOString(),
status: "error",
isComplete: true,
},
];
}
}
return;
}
// 百川模型专用:处理 answer_chunk 事件
if ((evt as any)?.type === "answer_chunk") {
const chunk = (evt as any).chunk ?? "";
const isComplete = (evt as any).isComplete === true;
if (chunk) {
this.appendAnswerChunk({ questionId: payload.questionId, chunk });
}
if (isComplete && selectedProvider === "baichuan") {
this.completeAnswer(payload.questionId);
this.streamingAnswer = false;
this.aiThinking = false;
try {
sub?.close();
} catch {}
}
return;
}
// 兼容豆包模型的 content 类型
if ((evt as any)?.type === "content") {
const chunk = (evt as any).content ?? "";
this.appendAnswerChunk({ questionId: payload.questionId, chunk });
return;
}
// 处理完成事件
if (
(evt as any)?.type === "complete" ||
(evt as any)?.isComplete === true ||
(evt as any)?.close === "stream_complete"
) {
this.completeAnswer(payload.questionId);
this.streamingAnswer = false;
this.aiThinking = false;
try {
sub?.close();
} catch {}
return;
}
// 兼容旧格式的 message 字段
if ((evt as any)?.message) {
const chunk =
typeof (evt as any).message === "string"
? (evt as any).message
: ((evt as any).message.chunk ?? "");
if (chunk)
this.appendAnswerChunk({ questionId: payload.questionId, chunk });
}
},
onError: (err: any) => {
console.error("SSE error:", err);
this.streamingError = "接收回答失败,请重试";
this.streamingAnswer = false;
this.aiThinking = false;
try {
sub?.close();
} catch {}
},
onEnd: () => {
this.completeAnswer(payload.questionId);
this.streamingAnswer = false;
this.aiThinking = false;
// 触发新手任务:快问快答
triggerNewbieTask("quick_qa");
},
};
// 优先使用显式传递的 provider,否则根据 selectedModel 决定
streamOptions.provider = selectedProvider;
sub = streamAnswer(streamOptions);
this.addEventSource({ chatId: payload.chatId, sub });
},
// 百川模型专用:处理思考状态
handleBaichuanThinking(payload: { questionId: string; thinkingData: any }) {
const msg = this.messages.find(
(m: Message) => m.questionId === payload.questionId,
);
if (!msg || !msg.answers || msg.answers.length === 0) return;
const lastAnswer = msg.answers[msg.answers.length - 1];
if (!lastAnswer) return;
// 初始化 thinking 对象(如果不存在)
if (!lastAnswer.thinking) {
lastAnswer.thinking = {
status: "in_progress",
content: "",
steps: [],
};
}
// 更新 thinking 状态
lastAnswer.thinking.status =
payload.thinkingData.status === "completed"
? "completed"
: "in_progress";
// 更新 summary
if (payload.thinkingData.summary) {
lastAnswer.thinking.content = payload.thinkingData.summary;
}
// 更新 steps(累积更新,不覆盖)
if (
payload.thinkingData.steps &&
Array.isArray(payload.thinkingData.steps)
) {
// 合并步骤,避免重复
const existingSteps = lastAnswer.thinking.steps || [];
const newSteps = payload.thinkingData.steps;
// 创建步骤映射,用于去重和更新
const stepsMap = new Map();
// 先添加现有步骤
existingSteps.forEach((step: any) => {
stepsMap.set(step.label, step);
});
// 更新或添加新步骤
newSteps.forEach((step: any) => {
stepsMap.set(step.label, {
kind: step.kind,
status: step.status,
label: step.label,
});
});
// 转换回数组
lastAnswer.thinking.steps = Array.from(stepsMap.values());
}
},
// 百川模型专用:处理引用信息(支持多次流式合并)
handleBaichuanGrounding(payload: {
questionId: string;
groundingData: any;
}) {
const msg = this.messages.find(
(m: Message) => m.questionId === payload.questionId,
);
if (!msg || !msg.answers || msg.answers.length === 0) return;
const lastAnswer = msg.answers[msg.answers.length - 1];
if (!lastAnswer) return;
const incomingEvidence = payload.groundingData?.evidence || [];
if (!Array.isArray(incomingEvidence) || incomingEvidence.length === 0)
return;
// 初始化 grounding
if (!Array.isArray(lastAnswer.grounding)) {
lastAnswer.grounding = [];
}
// 构建现有 evidence 的去重索引
const existingMap = new Map<string, any>();
lastAnswer.grounding.forEach((item: any) => {
const key =
item.refNum != null
? `ref:${item.refNum}`
: item.url
? `url:${item.url}`
: null;
if (key) existingMap.set(key, item);
});
// 合并新到的 evidence(只追加不存在的)
incomingEvidence.forEach((item: any) => {
const key =
item.ref_num != null
? `ref:${item.ref_num}`
: item.url
? `url:${item.url}`
: null;
if (key && existingMap.has(key)) {
return; // 已存在,跳过
}
const normalized = {
title: item.title || item.title_zh || "未命名引用",
content: item.publication_info || item.author || "",
url: item.url || "",
refNum: item.ref_num,
evidenceClass: item.evidence_class,
author: item.author,
};
lastAnswer.grounding!.push(normalized);
if (key) {
existingMap.set(key, normalized);
}
});
},
startTypewriterEffect(_payload: { questionId: string; content: string }) {
// Typewriter effect implementation (optional)
},
},
};
export const useChatApiStore = defineStore("chatApi", commonStoreDefinition);
export const useWorkspaceChatStore = defineStore(
"workspaceChat",
commonStoreDefinition,
);