XlyErpService.java
56.7 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
package com.xly.service;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.xly.agent.ChatiAgent;
import com.xly.agent.DynamicTableNl2SqlAiAgent;
import com.xly.agent.ErpAiAgent;
import com.xly.agent.SceneSelectorAiAgent;
import com.xly.config.OperableChatMemoryProvider;
import com.xly.constant.CommonConstant;
import com.xly.constant.ReturnTypeCode;
import com.xly.entity.*;
import com.xly.exception.sqlexception.SqlGenerateException;
import com.xly.exception.sqlexception.SqlValidateException;
import com.xly.milvus.service.AiGlobalAgentQuestionSqlEmitterService;
import com.xly.milvus.service.MilvusService;
import com.xly.runner.AppStartupRunner;
import com.xly.thread.AiSqlErrorHistoryThread;
import com.xly.thread.AiUserAgentQuestionThread;
import com.xly.thread.MultiThreadPoolServer;
import com.xly.tool.DynamicToolProvider;
import com.xly.util.*;
import dev.langchain4j.agent.tool.ToolExecutionRequest;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageType;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.ollama.OllamaChatModel;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.MemoryId;
import dev.langchain4j.service.V;
import io.milvus.v2.common.DataType;
import io.milvus.v2.service.collection.request.CreateCollectionReq;
import jnr.ffi.annotations.In;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.IdGenerator;
import reactor.core.publisher.Flux;
import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@Service
@RequiredArgsConstructor
@Slf4j
public class XlyErpService {
//中文对话模型
private final OllamaChatModel chatModel;
private final ChatLanguageModel chatiModel;
private final SceneSelectorAiAgent sceneSelectorAiAgent;
private final UserSceneSessionService userSceneSessionService;
private final DynamicToolProvider dynamicToolProvider;
private final OperableChatMemoryProvider operableChatMemoryProvider;
private final DynamicExeDbService dynamicExeDbService;
private final RedisService redisService;
private final AiGlobalAgentQuestionSqlEmitterService aiGlobalAgentQuestionSqlEmitterService;
private final MilvusService milvusService;
//执行动态语句 执行异常的情况下 最多执行次数
private final Integer maxRetries = 5;
//没有找到对应方法重走一次补偿次数
public final static Integer maxTollRetries = 1;
@Value("${langchain4j.ollama.base-url}")
private String sqlModelUrl;
@Value("${langchain4j.ollama.sql-model-name}")
private String sqlModelName;
/**
* @Author 钱豹
* @Date 19:18 2026/1/27
* @Param [userInput, userId, sUserType]
* @return reactor.core.publisher.Flux<AiResponseDTO>
* @Description 问答(流式返回)
**/
public Flux<AiResponseDTO> erpUserInputStream(String userInput,
String userId,
String sUserName,
String sBrandsId,
String sSubsidiaryId,
String sUserType,
String authorization) {
String sceneName = StrUtil.EMPTY;
String methodName = StrUtil.EMPTY;
UserSceneSession session=null;
try {
// 0. 预处理用户输入:去空格、转小写(方便匹配)
String input= InputPreprocessor.preprocessWithCommons(userInput);
// 1. 初始化用户场景会话(权限内场景)
session = userSceneSessionService.getUserSceneSession(userId,sUserName,sBrandsId,sSubsidiaryId,sUserType,authorization);
session.setAuthorization(authorization);
session.setSFunPrompts(null);
sceneName = ObjectUtil.isNotEmpty(session.getCurrentScene())?session.getCurrentScene().getSSceneName():StrUtil.EMPTY;
methodName = ObjectUtil.isNotEmpty(session.getCurrentTool())?session.getCurrentTool().getSMethodName():StrUtil.EMPTY;
// 2. 特殊指令:重置场景(无论是否已选,都可重置)
if (input.contains("重置") || input.contains("重新选择")) {
//清除记忆缓存
reSet(userId ,sUserName, sBrandsId ,sSubsidiaryId,sUserType,authorization,session);
return Flux.just(AiResponseDTO.builder()
.aiText(resetUserScene(session.getUserId(), session))
.sSceneName(sceneName)
.sMethodName(methodName)
.sReturnType(ReturnTypeCode.HTML.getCode())
.build());
}
//聊天只能体
if (session.getCurrentScene() != null
&& Objects.equals(session.getCurrentScene().getSSceneNo(), "ChatZone"))
{
return getChatiAgentStream(input, session);
}
// 3. 未选场景:先展示场景选择界面,处理用户序号选择
if (!session.isSceneSelected() && ValiDataUtil.me().isPureNumber(input)){
// 3.1 尝试处理场景选择(输入序号则匹配,否则展示选择提示)
AiResponseDTO aiResponseDTO = handleSceneSelect(userId, input, session);
return Flux.just(aiResponseDTO);
}
// 4. 构建Agent,执行业务交互,如果返回为null,说明大模型没有判段出场景,必判断出后才能继续
ErpAiAgent aiAgent = createErpAiAgent(userId, input, session);
// 没有选择到场景,进闲聊模式
if (aiAgent == null){
return getChatiAgentStream (input,session);
}
String sResponMessage = StrUtil.EMPTY;
//用户输入添加方法(如果没有方法,动态SQL方法不需要)
if(!(ObjectUtil.isNotEmpty(session.getCurrentTool())
&& ObjectUtil.isNotEmpty(session.getCurrentTool().getSInputTabelName())
&& ObjectUtil.isNotEmpty(session.getCurrentTool().getSStructureMemo()))
){
sResponMessage = aiAgent.chat(userId, input);
}
if(ObjectUtil.isNotEmpty(session.getCurrentTool())
&& !ObjectUtil.isNotEmpty(session.getCurrentTool().getSInputTabelName())
){
input = session.getCurrentTool().getSMethodName()+","+input;
}
//动态方法或返回需要提示的信息
if(ObjectUtil.isNotEmpty(session.getSFunPrompts())){
return Flux.just(AiResponseDTO.builder()
.aiText(session.getSFunPrompts())
.sSceneName(sceneName)
.sMethodName(methodName)
.sReturnType(ReturnTypeCode.HTML.getCode())
.build());
}
// 1.找到方法并且本方法带表结构描述时,需要调用 自然语言转SQL智能体
if((ObjectUtil.isNotEmpty(session.getCurrentTool())
&& ObjectUtil.isNotEmpty(session.getCurrentTool().getSInputTabelName())
&& ObjectUtil.isNotEmpty(session.getCurrentTool().getSStructureMemo()))
){
//查询缓存是否存在取缓存 直接走
Map<String,Object> cachMap = getDynamicTableCach(session,userInput);
Boolean isAggregation;
Boolean bHasCach;
String sCleanSql = StrUtil.EMPTY;
if(ObjectUtil.isEmpty(cachMap)){
//查询是否走向量库 还是数据库查询
isAggregation = aiAgent.routeQuery(session.getUserId(), input);
session.setDbCach("D");
bHasCach = false;
}else{
isAggregation = "MYSQL".equals(cachMap.get("cachType"));
session.setDbCach("H");
bHasCach = true;
sCleanSql = ObjectUtil.isNotEmpty(cachMap.get("sSqlContent"))?cachMap.get("sSqlContent").toString() : StrUtil.EMPTY;
}
if(!isAggregation){
//获取常量库内容
session.setDbType("X");
sResponMessage = getMilvus(session, input, aiAgent,bHasCach);
}else {
session.setDbType("G");
sResponMessage = getDynamicTableSql(session, input, userId, userInput,0,StrUtil.EMPTY,StrUtil.EMPTY,"0",StrUtil.EMPTY, aiAgent,sCleanSql);
}
return Flux.just(AiResponseDTO.builder()
.aiText(sResponMessage)
.sSceneName(sceneName)
.sMethodName(methodName)
.sReturnType(ReturnTypeCode.HTML.getCode())
.build());
} else if (ObjectUtil.isNotEmpty(session.getCurrentTool())) {
//2.处理工具参数采集结束后业务逻辑处理
//调用方法,参数缺失部分提示,就直接使用方法返回的
sResponMessage = dynamicToolProvider.doDynamicTool(session.getCurrentTool(),session);
return Flux.just(AiResponseDTO.builder()
.aiText(sResponMessage)
.sSceneName(sceneName)
.sMethodName(methodName)
.sReturnType(ReturnTypeCode.HTML.getCode())
.build());
}else if(session.getCurrentScene()== null ){
return Flux.just(AiResponseDTO.builder()
.aiText("当前场景:没有选择 退回当前场景 请输入 "+ CommonConstant.RESET + sResponMessage)
.sSceneName(sceneName)
.sMethodName(methodName)
.sReturnType(ReturnTypeCode.HTML.getCode())
.build());
}else{
return getChatiAgentStream (input, session);
}
} catch (Exception e) {
e.printStackTrace();
return Flux.just(AiResponseDTO.builder()
.aiText("系统异常:" + e.getMessage() + ",请稍后重试!")
.sSceneName(sceneName)
.sMethodName(methodName)
.sReturnType(ReturnTypeCode.HTML.getCode())
.build());
}finally {
//5.执行工具方法后,清除记忆
if(session !=null && session.getBCleanMemory()){
doCleanUserMemory(session,userId);
}
}
}
/****
* @Author 钱豹
* @Date 8:54 2026/4/7
* @Param [userInput, userId, sUserName, sBrandsId, sSubsidiaryId, sUserType, authorization]
* @return com.xly.entity.AiResponseDTO
* @Description 换一换
**/
public AiResponseDTO change(String userId ,
String sUserName ,
String sBrandsId ,
String sSubsidiaryId,
String sUserType,
String authorization,
Integer iPage) {
// 1. 初始化用户场景会话(权限内场景)
UserSceneSession session = userSceneSessionService.getUserSceneSession(userId,sUserName,sBrandsId,sSubsidiaryId,sUserType,authorization);
return getChange(session, iPage);
}
/***
* @Author 钱豹
* @Date 19:18 2026/1/27
* @Param [userInput, userId, sUserType]
* @return java.lang.String
* @Description 问答
**/
public AiResponseDTO erpUserInput(String userInput,
String userId ,
String sUserName ,
String sBrandsId ,
String sSubsidiaryId,
String sUserType,
String authorization) {
String sceneName = StrUtil.EMPTY;
String methodName = StrUtil.EMPTY;
UserSceneSession session=null;
try {
// 0. 预处理用户输入:去空格、转小写(方便匹配)
String input= InputPreprocessor.preprocessWithCommons(userInput);
// 1. 初始化用户场景会话(权限内场景)
session = userSceneSessionService.getUserSceneSession(userId,sUserName,sBrandsId,sSubsidiaryId,sUserType,authorization);
session.setAuthorization(authorization);
session.setSFunPrompts(null);
session.setDbCach(StrUtil.EMPTY);
session.setDbType(StrUtil.EMPTY);
sceneName = ObjectUtil.isNotEmpty(session.getCurrentScene())?session.getCurrentScene().getSSceneName():StrUtil.EMPTY;
// 2. 特殊指令:重置场景(无论是否已选,都可重置)
if (input.contains("重置") || input.contains("重新选择")) {
//清除记忆缓存
reSet(userId ,sUserName, sBrandsId ,sSubsidiaryId,sUserType,authorization,session);
return AiResponseDTO.builder().aiText(resetUserScene(session.getUserId(),session)).build();
}
//聊天只能体
if (session.getCurrentScene() != null
&& Objects.equals(session.getCurrentScene().getSSceneNo(), "ChatZone"))
{
return getChatiAgent(input, session);
}
// 3. 未选场景:先展示场景选择界面,处理用户序号选择
if (!session.isSceneSelected() && ValiDataUtil.me().isPureNumber(input)){
// 3.1 尝试处理场景选择(输入序号则匹配,否则展示选择提示)
return handleSceneSelect(userId, input, session,1);
}
// 4. 构建Agent,执行业务交互,如果返回为null,说明大模型没有判段出场景,必判断出后才能继续
ErpAiAgent aiAgent = createErpAiAgent(userId, input, session);
// 没有选择到场景,进闲聊模式
if (aiAgent == null){
return getChatiAgent (input,session);
}
String sResponMessage = StrUtil.EMPTY;
//用户输入添加方法(如果没有方法,动态SQL方法不需要)
if(!(ObjectUtil.isNotEmpty(session.getCurrentTool())
&& ObjectUtil.isNotEmpty(session.getCurrentTool().getSInputTabelName())
&& ObjectUtil.isNotEmpty(session.getCurrentTool().getSStructureMemo()))
){
sResponMessage = aiAgent.chat(userId, input);
}
methodName = ObjectUtil.isNotEmpty(session.getCurrentTool())?session.getCurrentTool().getSMethodName():StrUtil.EMPTY;
if(ObjectUtil.isNotEmpty(session.getCurrentTool())
&& !ObjectUtil.isNotEmpty(session.getCurrentTool().getSInputTabelName())
){
input = session.getCurrentTool().getSMethodName()+","+input;
}
//动态方法或返回需要提示的信息
if(ObjectUtil.isNotEmpty(session.getSFunPrompts())){
return AiResponseDTO.builder().sSceneName(sceneName).sMethodName(methodName).aiText(session.getSFunPrompts()).sReturnType(ReturnTypeCode.HTML.getCode()).build();
}
// 1.找到方法并且本方法带表结构描述时,需要调用 自然语言转SQL智能体
if((ObjectUtil.isNotEmpty(session.getCurrentTool())
&& ObjectUtil.isNotEmpty(session.getCurrentTool().getSInputTabelName())
&& ObjectUtil.isNotEmpty(session.getCurrentTool().getSStructureMemo()))
){
//查询缓存是否存在取缓存 直接走
Map<String,Object> cachMap = getDynamicTableCach(session,userInput);
Boolean isAggregation;
Boolean bHasCach;
String sCleanSql = StrUtil.EMPTY;
if(ObjectUtil.isEmpty(cachMap)){
//查询是否走向量库 还是数据库查询
// isAggregation = aiAgent.routeQuery(session.getUserId(), input);
session.setDbCach("D");
bHasCach = false;
}else{
isAggregation = "MYSQL".equals(cachMap.get("cachType"));
session.setDbCach("H");
bHasCach = true;
sCleanSql = ObjectUtil.isNotEmpty(cachMap.get("sSqlContent"))?cachMap.get("sSqlContent").toString() : StrUtil.EMPTY;
}
// if(!isAggregation){
// //获取常量库内容
// session.setDbType("X");
// sResponMessage = getMilvus(session, input, aiAgent,bHasCach);
// }else {
session.setDbType("G");
sResponMessage = getDynamicTableSql(session, input, userId, userInput,0,StrUtil.EMPTY,StrUtil.EMPTY,"0",StrUtil.EMPTY, aiAgent,sCleanSql);
// }
return AiResponseDTO.builder().sSceneName(sceneName).sMethodName(methodName).aiText(sResponMessage).sReturnType(ReturnTypeCode.HTML.getCode()).dbType(session.getDbType()).dbCach(session.getDbCach()).build();
} else if (ObjectUtil.isNotEmpty(session.getCurrentTool())) {
//2.处理工具参数采集结束后业务逻辑处理
//调用方法,参数缺失部分提示,就直接使用方法返回的
sResponMessage = dynamicToolProvider.doDynamicTool(session.getCurrentTool(),session);
return AiResponseDTO.builder().sSceneName(sceneName).sMethodName(methodName).aiText(sResponMessage).dbType(session.getDbType()).dbCach(session.getDbCach()).sReturnType(ReturnTypeCode.HTML.getCode()).build();
}else if(session.getCurrentScene()== null ){
return AiResponseDTO.builder().sSceneName(sceneName).sMethodName(methodName).aiText("当前场景:没有选择 退回当前场景 请输入 "+ CommonConstant.RESET + sResponMessage).dbType(session.getDbType()).dbCach(session.getDbCach()).sReturnType(ReturnTypeCode.HTML.getCode()).build();
}else{
return getChatiAgent (input, session);
}
} catch (Exception e) {
e.printStackTrace();
return AiResponseDTO.builder().sSceneName(sceneName).sMethodName(methodName).aiText("系统异常:" + e.getMessage() + ",请稍后重试!").dbType(session.getDbType()).dbCach(session.getDbCach()).sReturnType(ReturnTypeCode.HTML.getCode()).build();
}finally {
//5.执行工具方法后,清除记忆
if(session !=null && session.getBCleanMemory()){
doCleanUserMemory(session,userId);
}
}
}
/***
* @Author 钱豹
* @Date 22:47 2026/3/16
* @Param [userId, sUserName, sBrandsId, sSubsidiaryId, sUserType, authorization]
* @return void
* @Description 回首页
**/
public void reSet( String userId ,
String sUserName ,
String sBrandsId ,
String sSubsidiaryId,
String sUserType,
String authorization, UserSceneSession session) {
userSceneSessionService.cleanUserSession(userId);
session.setCurrentScene(null);
session.setSceneSelected(false);
session.setBCleanMemory(false);
session.setCurrentRowData(null);
UserSceneSessionService.USER_SCENE_SESSION_CACHE.put(userId, session);
// 清空Agent缓存
UserSceneSessionService.ERP_AGENT_CACHE.remove(userId);
UserSceneSessionService.CHAT_AGENT_CACHE.remove(userId);
cleanMemory(userId, sUserName, sBrandsId, sSubsidiaryId, sUserType, authorization);
}
public AiResponseDTO cleanMemory( String userId ,
String sUserName ,
String sBrandsId ,
String sSubsidiaryId,
String sUserType,
String authorization) {
UserSceneSession session = userSceneSessionService.getUserSceneSession(userId,sUserName,sBrandsId,sSubsidiaryId,sUserType,authorization);
operableChatMemoryProvider.clearSpecifiedMemory(userId);
session.setCurrentTool(null);
session.setArgs(null);
session.setSUserQuestionList(new ArrayList<>());
UserSceneSessionService.ERP_AGENT_CACHE.remove(userId);
UserSceneSessionService.CHAT_AGENT_CACHE.remove(userId);
session.setBCleanMemory(false);
String sceneName = ObjectUtil.isNotEmpty(session.getCurrentScene())?session.getCurrentScene().getSSceneName():StrUtil.EMPTY;
return AiResponseDTO.builder().sSceneName(sceneName).sMethodName(StrUtil.EMPTY).aiText(StrUtil.EMPTY).systemText("清除记忆成功!").sReturnType(ReturnTypeCode.HTML.getCode()).build();
}
/***
* @Author 钱豹
* @Date 10:16 2026/3/25
* @Param [session, input, userId, userInput, attempt, errorSql, errorMessage, iErroCount, historySqlList, aiAgent]
* @return java.lang.String
* @Description 查询向量库
**/
private String getMilvus(UserSceneSession session,String userInput,ErpAiAgent aiAgent,Boolean bCach){
String resultExplain = "信息模糊,请提供更具体的问题或指令";
try{
addSessionUserQuestionList(session, userInput);
String sVectorfiled = session.getCurrentTool().getSVectorfiled();
String sInputTabelName = session.getCurrentTool().getSInputTabelName();
String sVectorfiledAll = session.getCurrentTool().getSVectorfiledAll();
String sVectorfiledShow = session.getCurrentTool().getSVectorfiledShow();
String sVectorjson = session.getCurrentTool().getSVectorjson();
String sceneName = session.getCurrentTool().getSceneName();
String sMethodName = session.getCurrentTool().getSMethodName();
Map<String,Object> rMap = milvusService.getMilvusFiled(sVectorfiled,sVectorfiledAll,sVectorfiledShow,sVectorjson);
String sMilvusFiled = rMap.get("sMilvusFiled").toString();
String sMilvusFiledXl = rMap.get("sMilvusFiledXl").toString();
String sMilvusFiledDescription = rMap.get("sMilvusFiledDescription").toString();
String sMilvusFiledDescriptionXl = rMap.get("sMilvusFiledDescriptionXl").toString();
String sMilvusFiledDescriptionAll = rMap.get("sMilvusFiledDescriptionAll").toString();
List<String> filedsShow = (List<String>) rMap.get("filedsShow");
List<Map<String, String>> title = (List<Map<String, String>>) rMap.get("title");
String milvusFilter = StrUtil.EMPTY;
String vectorValue = StrUtil.EMPTY;
Boolean bMethodName = false;
if(!bCach){
long sDateNow = System.currentTimeMillis() / 1000;
String milvusFilterOld = aiAgent.getMilvusFilter(session.getUserId(),userInput, sMilvusFiled, sMilvusFiledDescription,sMilvusFiledXl, sMilvusFiledDescriptionXl,sDateNow,sMethodName);
log.info("查询向量库条件{}",milvusFilterOld);
if(ObjectUtil.isNotEmpty(milvusFilterOld) && JSONUtil.isTypeJSON(milvusFilterOld)){
Map<String,Object> filterMap = JSONUtil.parseObj(milvusFilterOld);
if(ObjectUtil.isNotEmpty(filterMap.get("filterExpression"))){
milvusFilterOld = filterMap.get("filterExpression").toString();
}
if(ObjectUtil.isNotEmpty(filterMap.get("vectorValue"))){
vectorValue = filterMap.get("vectorValue").toString();
}
if(ObjectUtil.isNotEmpty(filterMap.get("sMethodName"))){
bMethodName = BooleanUtil.toBoolean(filterMap.get("sMethodName").toString());
}
}
Boolean milvusFilterCheck = milvusService.isStringFilterValid(milvusFilterOld,sInputTabelName);
milvusFilter = milvusFilterCheck?milvusFilterOld : null;
if(!bMethodName && ObjectUtil.isEmpty(vectorValue) && ObjectUtil.isEmpty(milvusFilter)){
return resultExplain;
}
}
Integer pageSize = 100;
if(ObjectUtil.isEmpty(milvusFilter)){
pageSize = 10;
}
// 待条件全查 不带 10条
List<Map<String,Object>> data = milvusService.getDataToCollection(sInputTabelName, milvusFilter,userInput,pageSize,filedsShow, vectorValue,sceneName);
//存储到历史问题库(带where条件了就不存)并且没有记录过缓存
if(!bCach && ObjectUtil.isEmpty(milvusFilter)){
//执行操作记录表
try{
List<ChatMessage> chatMessage = operableChatMemoryProvider.getCurrentChatMessages(session.getUserId());
//插入向量库
doAiUserAgentQuestion(session,userInput,milvusFilter,"MILVUS",chatMessage);
}catch (Exception e){
log.error("插入向量库异常",e);
}
}
//采用表格形式显示明细、...详情、...记录、...列表、...清单
if( retrunMarkdownType(userInput) ){
resultExplain = buildMarkdownTableWithStream(data, title);
}else{
resultExplain = aiAgent.explainMilvusResult(session.getUserId(),userInput,sMilvusFiledDescriptionAll,JSONObject.toJSONString(data));
}
return resultExplain;
}catch (Exception e){
e.printStackTrace();
}
return resultExplain;
}
/***
* @Author 钱豹
* @Date 19:48 2026/3/28
* @Param [userInput]
* @return java.lang.Boolean
* @Description 是否返回Markdown类型
**/
private Boolean retrunMarkdownType(String userInput){
return userInput.contains("明细")
// || userInput.contains("详情")
// || userInput.contains("记录")
|| userInput.contains("列表")
|| userInput.contains("清单");
}
/***
* @Author 钱豹
* @Date 13:19 2026/3/25
* @Param [data, title]
* @return java.lang.String
* @Description 数据转成MarkdownTable
**/
public String buildMarkdownTableWithStream(List<Map<String, Object>> data, List<Map<String, String>> title) {
if (data == null || data.isEmpty()) {
return "暂无数据";
}
// 动态构建表头
StringBuilder headerBuilder = new StringBuilder("|");
StringBuilder separatorBuilder = new StringBuilder("|");
for (Map<String, String> column : title) {
String displayName = column.get("sTitle"); // 中文显示名称
headerBuilder.append(" ").append(displayName).append(" |");
separatorBuilder.append("------|");
}
String header = headerBuilder.toString() + "\n" + separatorBuilder.toString() + "\n";
// 构建数据行
String rows = IntStream.range(0, data.size())
.mapToObj(i -> {
Map<String, Object> item = data.get(i);
StringBuilder rowBuilder = new StringBuilder("|");
for (Map<String, String> column : title) {
String fieldName = column.get("sName");
Object value = item.getOrDefault(fieldName, "");
rowBuilder.append(" ").append(value).append(" |");
}
return rowBuilder.toString();
})
.collect(Collectors.joining("\n"));
return header + rows;
}
/***
* @Author 钱豹
* @Date 18:38 2026/2/5
* @Param [session, input, userId, userInput]
* @return java.lang.String
* @Description 获取执行动态SQL
**/
private String getDynamicTableSql(UserSceneSession session,String input,String userId,String userInput,Integer attempt,String errorSql,String errorMessage,String iErroCount,String historySqlList,ErpAiAgent aiAgent,String cleanSql){
String resultExplain = "信息模糊,请提供更具体的问题或指令";
try{
while (attempt < maxRetries) {
try{
attempt = attempt+1;
if(attempt==1){
addSessionUserQuestionList(session, userInput);
}
return getDynamicTableSqlExec(session, input, userId, userInput,errorSql,errorMessage,iErroCount,historySqlList, aiAgent, cleanSql);
}catch (SqlValidateException e){
return "本场景没有识别到您的意图<br/> 如果切换场景,点[回首页],如果在本场景下,转换意图,点[清除记忆]";
}catch (Exception e){
String erroMsg = e.getMessage();
String errorSqlOld = StrUtil.EMPTY;
if(erroMsg.contains(EnhancedErrorGuidance.splitString) && erroMsg.split(EnhancedErrorGuidance.splitString).length>1){
errorSqlOld = erroMsg.split(EnhancedErrorGuidance.splitString)[1];
errorSqlOld = StrUtil.replace(errorSqlOld,";","");
if(StrUtil.isNotEmpty(historySqlList)){
historySqlList = historySqlList+"/"+errorSqlOld;
}else{
historySqlList = errorSqlOld;
}
}
String errorMessageOld = erroMsg.split(EnhancedErrorGuidance.splitString)[0];
if (attempt == maxRetries) {
return resultExplain +"<br/>查询的SQL语句:"+historySqlList;
} else {
return getDynamicTableSql( session, input, userId, userInput, attempt,errorSqlOld,errorMessageOld,attempt.toString(),historySqlList, aiAgent,cleanSql);
}
}
}
}catch (Exception e){
}
// finally {
// doCleanUserMemory(session,userId);
// }
return resultExplain;
}
private void addSessionUserQuestionList(UserSceneSession session,String userInput){
List<String> userQuestionList = session.getSUserQuestionList();
if(ObjectUtil.isEmpty(userQuestionList)){
userQuestionList = new ArrayList<>();
}
String sQuestion = StrUtil.replace(userInput," ",StrUtil.EMPTY);
sQuestion = StrUtil.replace(sQuestion,"\t",StrUtil.EMPTY);
sQuestion = StrUtil.replace(sQuestion,"\n",StrUtil.EMPTY);
sQuestion = sQuestion.toLowerCase();
userQuestionList.add(sQuestion);
session.setSUserQuestionList(userQuestionList);
}
/***
* @Author 钱豹
* @Date 19:59 2026/3/4
* @Param [session, sUserId]
* @return void
* @Description 删除用户记忆 方法
**/
private void doCleanUserMemory(UserSceneSession session,String userId){
operableChatMemoryProvider.clearSpecifiedMemory(userId);
session.setCurrentTool(null);
session.setSUserQuestionList(new ArrayList<>());
session.setArgs(new HashMap<>());
// session.setSceneSelected(false);
UserSceneSessionService.ERP_AGENT_CACHE.remove(userId);
UserSceneSessionService.CHAT_AGENT_CACHE.remove(userId);
session.setBCleanMemory(false);
}
/***
* @Author 钱豹
* @Date 19:49 2026/3/4
* @Param [session, input, userId, userInput]
* @return java.lang.String
* @Description 执行动态sSql
**/
private String getDynamicTableSqlExec(UserSceneSession session,String input,String userId,String userInput,String errorSql,String errorMessage,String iErroCount,String historySqlList,ErpAiAgent aiAgent,String cleanSql){
// 1. 构建自然语言转SQLAgent,
List<Map<String, Object>> sqlResult;
String rawSql;
String tableStruct = session.getCurrentTool().getSStructureMemo();
String sError_mes;
Boolean doAddSql = false;
List<ChatMessage> chatMessage = new ArrayList<>();
try{
//如果之前已查询直接返回
if(ObjectUtil.isEmpty(cleanSql)){
DynamicTableNl2SqlAiAgent aiDynamicTableNl2SqlAiAgent = createDynamicTableNl2SqlAiAgent(userId, input, session);
chatMessage = operableChatMemoryProvider.getCurrentChatMessages(session.getUserId());
String tableNames = session.getCurrentTool().getSInputTabelName();
// "订单表:viw_salsalesorder,客户信息表:elecustomer,结算方式表:sispayment,产品表(无单价,无金额,无数量):viw_product_sort,销售人员表:viw_sissalesman_depart";
String sDataNow = DateUtil.now();
//DateFormatUtils.format(new Date(), "yyyy年MM月dd日HH时mm分ss秒");
// String sDataNow = DateUtil.format(new Date(), DatePattern.CHINESE_DATE_TIME_FORMAT);
if(ObjectUtil.isEmpty(errorSql) && ObjectUtil.isEmpty(errorMessage)){
rawSql = aiDynamicTableNl2SqlAiAgent.generateMysqlSql(userId,tableNames,tableStruct,sDataNow,userInput);
}else{
rawSql = aiDynamicTableNl2SqlAiAgent.regenerateSqlWithError(userId, tableNames,tableStruct,sDataNow,userInput,errorSql,errorMessage,iErroCount,historySqlList);
}
log.info("rawSql:"+rawSql);
if (rawSql == null || rawSql.trim().isEmpty()) {
throw new SqlValidateException("SQL EMPTY");
}
// 2. 清理SQL多余符号 + 生产级强校验(核心安全保障,不可省略)
cleanSql = SqlValidateUtil.cleanSqlSymbol(rawSql);
SqlValidateUtil.validateMysqlSql(cleanSql);
doAddSql = true;
}
// List<ChatMessage> chatMessage2 = operableChatMemoryProvider.getCurrentChatMessages(session.getUserId());
try{
sqlResult = dynamicExeDbService.findSql(new HashMap<>(),cleanSql);
}catch (Exception e){
throw new SqlGenerateException(e.getMessage()+" OLDSQL "+cleanSql);
}
}catch (SqlValidateException e){
//删除记录
// operableChatMemoryProvider.deleteUserLasterMessageBySize(userId,3);
sError_mes = e.getMessage();
doAiSqlErrorHistoryThread(session, StrUtil.EMPTY, cleanSql, sError_mes,input);
throw e;
}catch (SqlGenerateException e){
// operableChatMemoryProvider.deleteUserLasterMessageBySize(userId,3);
sError_mes = e.getMessage();
doAiSqlErrorHistoryThread(session, StrUtil.EMPTY, cleanSql, sError_mes,input);
throw e;
}
//如果查询不到数据走向量库
if(ObjectUtil.isEmpty(sqlResult)){
session.setDbType("X");
//数据集为空的也记录到历史问题中
doAiSqlErrorHistoryThread(session, StrUtil.EMPTY,cleanSql, "结果为空",input);
return getMilvus(session, input, aiAgent,false);
}
// 5. 调用AI服务生成自然语言解释(传入表结构,让解释更贴合业务)
String resultJson = JSON.toJSONString(sqlResult);
//执行正确去修改对应正确的SQl
if(Integer.valueOf(iErroCount)>0){
doAiSqlErrorHistoryThread(session, cleanSql, StrUtil.EMPTY, "执行正确去修改对应正确的SQl",input);
}
//插入常用操作 不包含where 条件
if(doAddSql){
//执行操作记录表
doAiUserAgentQuestion(session,input,cleanSql,"MYSQL",chatMessage);
}
//采用表格形式显示明细、...详情、...记录、...列表、...清单
String resultExplain = StrUtil.EMPTY;
// if(retrunMarkdownType(userInput) ){
// List<Map<String, String>> titles = getMarkdownTableTitleWithSql(sqlResult);
// resultExplain = buildMarkdownTableWithStream(sqlResult, titles);
// }else {
resultExplain = aiAgent.explainSqlResult(
userId,
userInput,
cleanSql,
tableStruct,
resultJson);
// }
return resultExplain;
}
/***
* @Author 钱豹
* @Date 19:55 2026/3/28
* @Param [sqlResult]
* @return java.util.List<java.util.Map<java.lang.String,java.lang.String>>
* @Description 动态SQL 返回Markdown 形式抬头
**/
private List<Map<String, String>> getMarkdownTableTitleWithSql(List<Map<String, Object>> sqlResult){
if(ObjectUtil.isEmpty(sqlResult)){
return new ArrayList<>();
}
Map<String, Object> one = sqlResult.get(0);
List<Map<String, String>> titleData = new ArrayList<>();
one.forEach((k,v)->{
Map<String, String> title = new HashMap<>();
title.put("sTitle",k);
title.put("sName",k);
titleData.add(title);
});
return titleData;
}
/***
* @Author 钱豹
* @Date 17:04 2026/3/19
* @Param [session]
* @return java.lang.String
* @Description 获取动态SQL(历史中查询)
**/
private Map<String,Object> getDynamicTableCach(UserSceneSession session,String input){
try{
String searchText = session.getCurrentScene().getSId()+"_"+session.getCurrentTool().getSId()+"_"+input;
//根据问题查询向量库
Map<String,Object> serMap = aiGlobalAgentQuestionSqlEmitterService.queryAiGlobalAgentQuestionSqlEmitter(searchText, "ai_global_agent_question_sql");
return serMap;
}catch (Exception e){
log.error("取是否走缓存异常");
}
return null;
}
/***
* @Author 钱豹
* @Date 16:57 2026/3/14
* @Param
* @return
* @Description 记录动态SQL日志(多线程)
**/
public void doAiSqlErrorHistoryThread(UserSceneSession session,
String sSqlContent,
String sError_sql,
String sError_mes,
String sQuestion
){
MultiThreadPoolServer mts = MultiThreadPoolServer.getInstance();
AiSqlErrorHistoryThread at = new AiSqlErrorHistoryThread(session, sSqlContent, sError_sql, sError_mes,sQuestion);
mts.service(at);
}
/***
* @Author 钱豹
* @Date 16:57 2026/3/14
* @Param
* @return
* @Description 记录动态SQL日志(多线程)
**/
public void doAiUserAgentQuestion(UserSceneSession session,
String sQuestion,
String sSqlContent,
String cachType,
List<ChatMessage> chatMessage
){
MultiThreadPoolServer mts = MultiThreadPoolServer.getInstance();
AiUserAgentQuestionThread at = new AiUserAgentQuestionThread(session,sQuestion,sSqlContent,cachType,chatMessage);
mts.service(at);
}
/***
* @Author 钱豹
* @Date 11:22 2026/1/31
* @Param
* @return
* @Description 动态参数补齐处理
**/
private String dotoolExecutionRequests(AiMessage aiMessage){
String textTs = aiMessage.text();
if(aiMessage.hasToolExecutionRequests()){
List<ToolExecutionRequest> toolExecutionRequests = aiMessage.toolExecutionRequests();
toolExecutionRequests.forEach(toolRequests->{
String arguments = toolRequests.arguments();
log.info(arguments);
});
}
return textTs;
}
/***
* 存入全部场景
* @Author 钱豹
* @Date 19:06 2026/1/26
* @Param [sUserId, sUserType]
* @return java.lang.String
* 页面刷新/首次进入时调用:初始化用户场景会话,直接返回场景选择引导词
* 前端页面加载完成后,无需用户输入,直接调用该方法即可显示引导词
* @param sUserId 用户ID(前端传入,如user-001) sUserType 角色状态
* @return 场景选择引导词(即原buildSceneSelectHint生成的文案)
*/
public AiResponseDTO initSceneGuide(String systemText,String sUserId,String sUserName,String sBrandsId,String sSubsidiaryId,String sUserType,String authorization) {
try {
UserSceneSession userSceneSession = userSceneSessionService.getUserSceneSession( sUserId,sUserName,sBrandsId,sSubsidiaryId,sUserType,authorization);
systemText = userSceneSession.buildSceneSelectHint();
} catch (Exception e) {
systemText = "<p style='color:red;'>抱歉,你暂无任何业务场景的访问权限,请联系管理员开通!</p>";
}
return AiResponseDTO.builder().aiText(StrUtil.EMPTY).systemText(systemText) .build();
}
// ====================== 动态构建Agent(支持选定场景/未选场景) ======================
private DynamicTableNl2SqlAiAgent createDynamicTableNl2SqlAiAgent(String userId, String userInput, UserSceneSession session) {
// 4. 获取/创建用DynamicTableNl2SqlAiAgent
DynamicTableNl2SqlAiAgent aiAgent = UserSceneSessionService.ERP_DynamicTableNl2SqlAiAgent_CACHE.get(userId);
if(ObjectUtil.isEmpty(aiAgent)){
OllamaChatModel ol = OllamaChatModel.builder()
.baseUrl(sqlModelUrl)
.modelName(sqlModelName) // 使用SQL模型名称
.temperature(0.0)
.topP(0.95)
.numPredict(4096) // 代码生成需要更长
.timeout(Duration.ofSeconds(120))
.maxRetries(3)
// .repeatPenalty(1.1) // 减少重复
.build();
aiAgent = AiServices.builder(DynamicTableNl2SqlAiAgent.class)
.chatLanguageModel(ol)
.chatMemoryProvider(operableChatMemoryProvider)
.toolProvider(dynamicToolProvider)
.build();
UserSceneSessionService.ERP_DynamicTableNl2SqlAiAgent_CACHE.put(userId, aiAgent);
}
return aiAgent;
}
// ====================== 动态构建Agent(支持选定场景/未选场景) ======================
private ErpAiAgent createErpAiAgent(String userId, String userInput, UserSceneSession session) {
// 1. 已选场景:强制绑定该场景工具
if (session.isSceneSelected() && session.getCurrentScene() != null) {
dynamicToolProvider.sSceneIdMap.put(userId,session.getCurrentScene().getSId());
} else {
// 2. 未选场景:大模型根据输入返加相应的场景
SceneDto sceneDto = parseSceneByLlm(userId, userInput, session);
if (sceneDto != null) {
session.setCurrentScene(sceneDto);
session.setSceneSelected(true);
UserSceneSessionService.USER_SCENE_SESSION_CACHE.put(userId, session);
dynamicToolProvider.sSceneIdMap.put(userId,session.getCurrentScene().getSId());
}else {return null;}
}
// 4. 获取/创建用Agent
ErpAiAgent aiAgent = UserSceneSessionService.ERP_AGENT_CACHE.get(userId);
if(ObjectUtil.isEmpty(aiAgent)){
aiAgent = AiServices.builder(ErpAiAgent.class)
.chatLanguageModel(chatModel)
.chatMemoryProvider(operableChatMemoryProvider)
.toolProvider(dynamicToolProvider)
// .toolChoice(ChatCompletionToolChoice.ofRequired()) // 👈 必须调用一个工具
.build();
UserSceneSessionService.ERP_AGENT_CACHE.put(userId, aiAgent);
// 初始化AiService 以防止热加载太慢 找不到相应的方法
try{
aiAgent.chat(userId, "initAiService");
}catch (Exception e){
e.printStackTrace();
}
log.info("用户{}Agent构建完成,已选场景:{},场景ID{}", userId, session.isSceneSelected() ? session.getCurrentScene().getSSceneName() : "未选(全场景匹配)", dynamicToolProvider.sSceneIdMap.get(userId));
}
return aiAgent;
}
/**
* 大模型意图解析核心方法(获取场景)
* @param userId 用户ID
* @param userInput 用户输入
* @param session 用户会话
* @return 匹配的BusinessScene,null表示解析失败
*/
private SceneDto parseSceneByLlm(String userId, String userInput, UserSceneSession session) {
try {
List<ToolMeta> metasAll = session.getAuthTool();
// toolMetaMapper.findAll();
// 1. 构建大模型意图解析请求
String authScenesDesc =session.buildAuthScenesForLlm(metasAll);
// 2. 调用大模型解析意图,LangChain4j自动将大模型输出映射为SceneIntentParseResp
// {{authScenesDesc}}
SceneIntentParseResp parseResp = sceneSelectorAiAgent.parseSceneIntent(userInput,authScenesDesc);
// authScenesDesc
// 3. 解析结果处理
if (parseResp == null || parseResp.getSceneCode() == null || "NO_MATCH".equals(parseResp.getSceneCode())) {
log.warn("用户{}大模型未匹配到任何场景,输入:{}", userId, userInput);
return null;
}
// 4. 将场景编码转换为BusinessScene枚举
String sSceneNo = parseResp.getScene();
return AppStartupRunner.getAiAgentByCode(sSceneNo);
} catch (Exception e) {
log.error("用户{}大模型意图解析失败,输入:{}", userId, userInput, e);
return null;
}
}
/***
* @Author 钱豹
* @Date 19:28 2026/1/26
* @Param [userId, session]
* @return java.lang.String
* @Description 重置用户场景选择:恢复为未选状态,清空当前场景,重新展示选择界面
**/
private String resetUserScene(String userId, UserSceneSession session) {
session.setSceneSelected(false);
session.setBCleanMemory(false);
session.setCurrentTool(null);
session.setSUserQuestionList(new ArrayList<>());
session.setCurrentScene(null);
session.setCurrentRowData(null);
UserSceneSessionService.USER_SCENE_SESSION_CACHE.put(userId, session);
// 清空Agent缓存
UserSceneSessionService.ERP_AGENT_CACHE.remove(userId);
UserSceneSessionService.CHAT_AGENT_CACHE.remove(userId);
return "场景选择已重置!请重新选择业务场景:\n" + session.buildSceneSelectHint();
}
/**
* 处理用户场景选择:输入序号→匹配场景→更新会话状态
*/
private AiResponseDTO handleSceneSelect(String userId, String userInput, UserSceneSession session,Integer page) {
// 1. 尝试根据序号匹配场景
boolean selectSuccess = session.selectSceneByInput(userInput);
String sceneName = StrUtil.EMPTY;
String methodName = StrUtil.EMPTY;
if (selectSuccess) {
// 2. 选择成功:更新缓存,返回成功提示
UserSceneSessionService.USER_SCENE_SESSION_CACHE.put(userId, session);
// 清空该用户原有Agent缓存(重新构建绑定新场景的Agent)
UserSceneSessionService.ERP_AGENT_CACHE.remove(userId);
//清除记忆缓存
operableChatMemoryProvider.clearSpecifiedMemory(userId);
return getChange( session, page);
} else {
// 3. 选择失败:重新展示场景选择提示
return AiResponseDTO.builder().sSceneName(sceneName).sMethodName(methodName).aiText(session.buildSceneSelectHint()).build();
}
}
/***
* @Author 钱豹
* @Date 9:00 2026/4/7
* @Param [session, page]
* @return com.xly.entity.AiResponseDTO
* @Description 用户输入数字换一换
**/
private AiResponseDTO getChange(UserSceneSession session,Integer page){
StringBuffer aiText = new StringBuffer().append(" <div style='line-height:1.8;width:100%;'>")
.append("<div style=\"color: #333;\">")
.append("智能体选择成功! 现在可以问她相关问题(如" + String.join("、", session.getCurrentScene().getSSceneContext()) + ")")
.append("</div>");
//插入用户常用问题
aiText.append(getSelectAgent(session,page));
String sceneName = ObjectUtil.isNotEmpty(session.getCurrentScene())?session.getCurrentScene().getSSceneName():StrUtil.EMPTY;
String methodName = ObjectUtil.isNotEmpty(session.getCurrentTool())?session.getCurrentTool().getSControlName():StrUtil.EMPTY;
return AiResponseDTO.builder().sSceneName(sceneName).sMethodName(methodName).aiText(aiText.toString()).sSceneName(session.getCurrentScene().getSSceneName()).build();
}
/***
* @Author 钱豹
* @Date 11:45 2026/3/13
* @Param []
* @return java.lang.String
* @Description 选择智能体成功后获取高频问题列表
**/
private String getSelectAgent(UserSceneSession session,Integer page){
List<ToolMeta> toolMetaAll = session.getAuthTool();
String sSceneId = session.getCurrentScene().getSId();
String sToolId = session.getCurrentTool().getSId();
toolMetaAll = toolMetaAll.stream().filter(to-> to.getSSceneId().equals(session.getCurrentScene().getSId())).collect(Collectors.toUnmodifiableList());
StringBuffer sb = new StringBuffer();
//获取用户最近五次问题
List<Map<String,Object>> data = getAiUserAgentQuestion(session.getUserId(),sSceneId, sToolId, page,3);
Integer iPageCount = 0;
if(page==1){
iPageCount =getAiUserAgentQuestionCount(session.getUserId(), sSceneId, sToolId);
}
List<ToolMeta> showListAll = new ArrayList<>();
if(ObjectUtil.isNotEmpty(data)){
data.forEach(one->{
ToolMeta tm = new ToolMeta();
tm.setSMethodName(one.get("sUserInput").toString());
});
}
showListAll.addAll(toolMetaAll);
showListAll.forEach(one->{
sb.append("<div style=\"color: #4096ff; margin-top: 5px;display:flex;align-items:center;font-size:12px;\" data-action=\"reset\" data-text=\"")
.append(one.getSMethodName()).append("\" onclick=\"reset(").append(one.getSMethodName()).append("\">")
.append("<span style=\"display:inline-block; width:5px; height:5px; background-color:#ccc; border-radius:50%; margin-right:5px;\"></span>")
.append(one.getSMethodName())
.append(" </div>");
});
sb.append("</div>");
sb.append(" <div style=\"color: #4096ff; margin-top: 5px;width:100%;text-align:right;margin-right:10px;font-size:12px;\" data-action=\"resetTag\" data-text=\"").append(sSceneId).append(",").append(sToolId).append(",").append(page+1).append(",").append(iPageCount).append("\" onclick=\"reset(换一换)\">");
sb.append(" 换一换").append("</div>");
return sb.toString();
}
/***
* @Author 钱豹
* @Date 10:02 2026/4/7
* @Param [sLoginId, sSceneId, sMethodId, iPageNum, iPageSize]
* @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
* @Description 换一换获取最近数据
**/
private List<Map<String,Object>> getAiUserAgentQuestion(String sLoginId, String sSceneId, String sMethodId, Integer iPageNum,Integer iPageSize){
StringBuffer sb = new StringBuffer().append("SELECT sId,iUpdate,sUserInput FROM ai_user_agent_question ")
.append("WHERE sLoginId = #{sLoginId} ")
.append("AND sSceneId = #{sSceneId} ")
.append("AND sMethodId = #{sMethodId} ")
.append("AND IFNULL(sUserInput,'') <> '' ")
.append("ORDER BY iUpdate DESC,tUpdateDate DESC ")
.append("LIMIT #{iPageNum},#{iPageSize} ");
Map<String,Object> serMap = new HashMap<>();
serMap.put("sLoginId",sLoginId);
serMap.put("sSceneId",sSceneId);
serMap.put("sMethodId",sMethodId);
serMap.put("iPageNum",iPageNum);
serMap.put("iPageSize",iPageSize);
return dynamicExeDbService.findSql(serMap,sb.toString());
}
private Integer getAiUserAgentQuestionCount(String sLoginId, String sSceneId, String sMethodId){
StringBuffer sb = new StringBuffer().append("SELECT COUNT(1) AS iCount FROM ai_user_agent_question ")
.append("WHERE sLoginId = #{sLoginId} ")
.append("AND sSceneId = #{sSceneId} ")
.append("AND sMethodId = #{sMethodId} ")
.append("AND IFNULL(sUserInput,'') <> '' ");
Map<String,Object> serMap = new HashMap<>();
serMap.put("sLoginId",sLoginId);
serMap.put("sSceneId",sSceneId);
serMap.put("sMethodId",sMethodId);
List<Map<String,Object>> data = dynamicExeDbService.findSql(serMap,sb.toString());
if(ObjectUtil.isNotEmpty(data)){
return (Integer) data.get(0).get("iCount");
}
return 0;
}
/**
* @Author 钱豹
* @Date 13:32 2026/2/6
* @Param [input, session]
* @return reactor.core.publisher.Flux<AiResponseDTO>
* @Description 获取智普通智能体(流式返回)
**/
private Flux<AiResponseDTO> getChatiAgentStream(String input, UserSceneSession session) {
String sceneName = ObjectUtil.isNotEmpty(session.getCurrentScene())
? session.getCurrentScene().getSSceneName() : StrUtil.EMPTY;
String methodName = ObjectUtil.isNotEmpty(session.getCurrentTool())
? session.getCurrentTool().getSMethodName() : "随便聊聊";
// 从缓存获取或创建ChatiAgent
ChatiAgent chatiAgent = UserSceneSessionService.CHAT_AGENT_CACHE.get(session.getUserId());
if (ObjectUtil.isEmpty(chatiAgent)) {
chatiAgent = AiServices.builder(ChatiAgent.class)
.chatLanguageModel(chatiModel)
.chatMemoryProvider(operableChatMemoryProvider)
.build();
UserSceneSessionService.CHAT_AGENT_CACHE.put(session.getUserId(), chatiAgent);
}
// 调用流式聊天方法
return chatiAgent.chatStream(session.getUserId(), input)
.map(chunk -> AiResponseDTO.builder()
.sSceneName(sceneName)
.sMethodName(methodName)
.aiText(chunk)
.systemText(StrUtil.EMPTY)
.sReturnType(ReturnTypeCode.STREAM.getCode())
.build());
}
/***
* @Author 钱豹
* @Date 13:32 2026/2/6
* @Param [input, session]
* @return java.lang.String
* @Description 获取智普通智能体
**/
private AiResponseDTO getChatiAgent (String input,UserSceneSession session){
String sceneName = ObjectUtil.isNotEmpty(session.getCurrentScene())?session.getCurrentScene().getSSceneName():StrUtil.EMPTY;
String methodName = ObjectUtil.isNotEmpty(session.getCurrentTool())?session.getCurrentTool().getSMethodName():"随便聊聊";
ChatiAgent chatiAgent = UserSceneSessionService.CHAT_AGENT_CACHE.get(session.getUserId());
if(ObjectUtil.isEmpty(chatiAgent)){
chatiAgent = AiServices.builder(ChatiAgent.class)
.chatLanguageModel(chatiModel)
.chatMemoryProvider(operableChatMemoryProvider)
.build();
UserSceneSessionService.CHAT_AGENT_CACHE.put(session.getUserId(), chatiAgent); }
String sChatMessage = chatiAgent.chat(session.getUserId(), input);
return AiResponseDTO.builder().sSceneName(sceneName).sMethodName(methodName).aiText(sChatMessage).systemText(StrUtil.EMPTY).sReturnType(ReturnTypeCode.HTML.getCode()).build();
}
}