qfrjava
2025-03-26 37f98a71f6c11a6522655de97d1bac54f2e4d960
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
package com.smtaiserver.smtaiserver.control;
 
import java.io.BufferedReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
 
import com.smtaiserver.smtaiserver.core.SMTAIServerApp;
import com.smtaiserver.smtaiserver.core.SMTAIServerRequest;
import com.smtaiserver.smtaiserver.core.SMTCheckChatStreamView;
import com.smtaiserver.smtaiserver.database.SMTDatabase;
import com.smtaiserver.smtaiserver.database.SMTDatabase.DBRecord;
import com.smtaiserver.smtaiserver.database.SMTDatabase.DBRecords;
import com.smtaiserver.smtaiserver.javaai.llm.core.SMTLLMConnect;
import com.smtaiserver.smtaiserver.javaai.qwen.agent.SMTQwenAgent;
import com.smtservlet.util.SMTJsonWriter;
import com.smtservlet.util.SMTStatic;
 
public class SMTKnowledgeControl
{
    public ModelAndView getKnowledgeText(SMTAIServerRequest tranReq) throws Exception 
    {
        String id = tranReq.convParamToString("file_id", true);
        SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
        try
        {
            SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
            DBRecords recs = db.querySQL("SELECT file_text FROM doc_file_list WHERE file_id=?", new Object[] {
                id
            });
            
            if(recs.getRowCount() == 0)
                return tranReq.returnJsonState(false, "file id不存在", null);
            
            jsonWr.addKeyValue("value", recs.getRecord(0).getString(0));
            return tranReq.returnJson(jsonWr);
        }
        finally
        {
            db.close();
        }
    }
    
    public ModelAndView listKnowledgeVector(SMTAIServerRequest tranReq) throws Exception 
    {
        String id = tranReq.convParamToString("file_id", true);
        SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
        try
        {
            SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
            DBRecords recs = db.querySQL("SELECT vector_text FROM doc_file_vector WHERE file_id=? ORDER BY vector_index", new Object[] {
                id
            });
            
            jsonWr.beginArray("values");
            for(DBRecord rec : recs.getRecords())
            {
                jsonWr.addKeyValue(null, rec.getString(0));
            }
            jsonWr.endArray();
            
            return tranReq.returnJson(jsonWr);
        }
        finally
        {
            db.close();
        }
    }
    
    public ModelAndView checkDocvectorValidate(SMTAIServerRequest tranReq) throws Exception 
    {
        String id = tranReq.convParamToString("knowlg_id", true);
        String question = tranReq.convParamToString("question", true);
        
        DBRecords recs;
        SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
        try
        {
            recs = db.querySQL("SELECT * FROM ai_agent_knowlg WHERE knowlg_id=?", new Object[] {
                id
            });
            if(recs.getRowCount() == 0)
                return tranReq.returnJsonState(false, "未发现记录", null);               
        }
        finally
        {
            db.close();
        }
        
        DBRecord rec = recs.getRecord(0);
        SMTQwenAgent agent = (SMTQwenAgent) Class.forName(rec.getString("clz_name")).newInstance();
        agent.initInstance(rec);
        Map<String, SMTQwenAgent> mapId2Agent = new HashMap<>();
        mapId2Agent.put(agent.getAgentId(), agent);
        
        return new ModelAndView(new SMTCheckChatStreamView(tranReq, question, mapId2Agent));
 
    }
    
    public ModelAndView getDocvectorFileList(SMTAIServerRequest tranReq) throws Exception 
    {
        String id = tranReq.convParamToString("knowlg_id", true);
        
        SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
        try
        {
            SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
            DBRecords recs = db.querySQL(
                  " SELECT file_id, file_name, file_type, create_time FROM doc_file_list"
                + " WHERE file_id IN (SELECT knowlg_file_id FROM knowlg_file_list WHERE knowlg_id=?)"
                  , new Object[] {id});
            jsonWr.beginArray("values");
            for(DBRecord rec : recs.getRecords())
            {
                jsonWr.beginMap(null);
                {
                    jsonWr.addKeyValue("id", rec.getString("file_id"));
                    jsonWr.addKeyValue("name", rec.getString("file_name"));
                    jsonWr.addKeyValue("type", rec.getString("file_type"));
                    jsonWr.addKeyValue("time", rec.getString("create_time"));
                }
                jsonWr.endMap();
            }
            jsonWr.endArray();
            
            return tranReq.returnJson(jsonWr);
        }
        finally
        {
            db.close();
        }
    } 
    
    public ModelAndView deleteDocvectorFile(SMTAIServerRequest tranReq) throws Exception 
    {
        String id = tranReq.convParamToString("knowlg_id", true);
        String fileId = tranReq.convParamToString("file_id", true);
        
        SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
        try
        {
            db.executeSQL("DELETE FROM knowlg_file_list WHERE knowlg_id=? AND knowlg_file_id=?", new Object[] {
                id,
                fileId
            });
            
            return tranReq.returnJsonState(true, null, null);
        }
        finally
        {
            db.close();
        }
    } 
    
    public ModelAndView addDocvectorFile(SMTAIServerRequest tranReq) throws Exception 
    {
        String id = tranReq.convParamToString("knowlg_id", true);
        String fileId = tranReq.convParamToString("file_id", true);
        
        SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
        try
        {
            db.executeSQL("DELETE FROM knowlg_file_list WHERE knowlg_id=? AND knowlg_file_id=?", new Object[] {
                id,
                fileId
            });
            
            db.executeSQL("INSERT INTO knowlg_file_list(knowlg_id, knowlg_file_id)VALUES(?,?)", new Object[] {
                id,
                fileId
            });
            
            return tranReq.returnJsonState(true, null, null);
        }
        finally
        {
            db.close();
        }
    } 
    
    public ModelAndView publishDocvectorName(SMTAIServerRequest tranReq) throws Exception 
    {
        String id = tranReq.convParamToString("knowlg_id", true);
        String publish = tranReq.convParamToString("publish", true);
        
        SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
        try
        {
            DBRecords recs = db.querySQL("SELECT is_publish FROM ai_agent_knowlg WHERE knowlg_id=?", new Object[] {
                id
            });
            if(recs.getRowCount() == 0)
                return tranReq.returnJsonState(false, "未发现知识库id", null);
            
            db.executeSQL("UPDATE ai_agent_knowlg SET is_publish=? WHERE knowlg_id=?", new Object[] {
                publish,
                id
            });
            
            if(!publish.equals(recs.getRecord(0).getString(0)))
                SMTAIServerApp.getApp().clearQwenAgentManager();
            
            return tranReq.returnJsonState(true, null, null);
        }
        finally
        {
            db.close();
        }
    }         
    
    public ModelAndView updateDocvectorGroup(SMTAIServerRequest tranReq) throws Exception 
    {
        String id = tranReq.convParamToString("knowlg_id", true);
        String groupId = tranReq.convParamToString("group_id", true);
        
        SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
        try
        {
            db.executeSQL("UPDATE ai_agent_knowlg SET knowlg_title=? WHERE knowlg_id=?", new Object[] {
                groupId,
                id
            });
            
            return tranReq.returnJsonState(true, null, null);
        }
        finally
        {
            db.close();
        }
    }
    
    public ModelAndView updateDocvectorName(SMTAIServerRequest tranReq) throws Exception 
    {
        String id = tranReq.convParamToString("knowlg_id", true);
        String title = tranReq.convParamToString("title", true);
        String prompt = tranReq.convParamToString("prompt", true);
        int scope = tranReq.convParamToInteger("scope", true);
        
        SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
        try
        {
            db.executeSQL("UPDATE ai_agent_knowlg SET knowlg_title=?, knowlg_prompt=?, vector_scope=? WHERE knowlg_id=?", new Object[] {
                title,
                prompt,
                scope,
                id
            });
            
            return tranReq.returnJsonState(true, null, null);
        }
        finally
        {
            db.close();
        }
    }             
            
    public ModelAndView deleteDocvectorName(SMTAIServerRequest tranReq) throws Exception 
    {
        String id = tranReq.convParamToString("knowlg_id", true);
        
        SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
        try
        {
            db.executeSQL("BEGIN", null);
            try
            {
                db.executeSQL("DELETE FROM ai_agent_knowlg WHERE knowlg_id=?", new Object[] {id});
                db.executeSQL("DELETE FROM knowlg_file_list WHERE knowlg_id=?", new Object[] {id});
                db.executeSQL("COMMIT", null);
                return tranReq.returnJsonState(true, null, null);
            }
            catch(Exception ex)
            {
                db.rollbackDB(ex);
                return null;
            }
        }
        finally
        {
            db.close();
        }
    }           
    
    public ModelAndView addDocvectorName(SMTAIServerRequest tranReq) throws Exception 
    {
        String title = tranReq.convParamToString("title", true);
        String prompt = tranReq.convParamToString("prompt", true);
        String groupId = tranReq.convParamToString("group_id", true);
        int scope = tranReq.convParamToInteger("scope", true);
        
        SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
        try
        {
            SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
            String id = "agent_" + SMTStatic.newUUID();
            db.executeSQL(
                "INSERT INTO ai_agent_knowlg(knowlg_id, knowlg_title, knowlg_prompt, is_publish, create_time, create_user,vector_scope, agent_group)VALUES(?,?,?,?,?,?,?,?)"
                , new Object[] {
                    id,
                    title,
                    prompt,
                    "N",
                    new Date(),
                    tranReq.getLoginUserId(),
                    scope,
                    groupId
                });
            
            jsonWr.addKeyValue("knowlg_id", id);
            return tranReq.returnJson(jsonWr);
        }
        finally
        {
            db.close();
        }
    }
        
    
    public ModelAndView getDocvectorList(SMTAIServerRequest tranReq) throws Exception 
    {
        SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
        try
        {
            SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
            
            DBRecords recs = db.querySQL(
                  " SELECT A.knowlg_id, A.knowlg_title, A.knowlg_prompt, A.is_publish, A.create_time, B.user_name, A.vector_scope, A.agent_group"
                + " FROM ai_agent_knowlg A LEFT JOIN sys_user_info B ON A.create_user=B.user_id"
                , null);
            
            jsonWr.beginArray("values");
            for(DBRecord rec : recs.getRecords())
            {
                jsonWr.beginMap(null);
                {
                    jsonWr.addKeyValue("id", rec.getString("knowlg_id"));
                    jsonWr.addKeyValue("title", rec.getString("knowlg_title"));
                    jsonWr.addKeyValue("prompt", rec.getString("knowlg_prompt"));
                    jsonWr.addKeyValue("publish", rec.getString("is_publish"));
                    jsonWr.addKeyValue("create_time", rec.getString("create_time"));
                    jsonWr.addKeyValue("user_name", rec.getString("user_name"));
                    jsonWr.addKeyValue("scope", rec.getString("vector_scope"));
                    jsonWr.addKeyValue("group_id", rec.getString("agent_group"));
                }
                jsonWr.endMap();
            }
            
            jsonWr.endArray();
            
            return tranReq.returnJson(jsonWr);
        }
        finally
        {
            db.close();
        }
    }
    
    public ModelAndView listKnowledgeFile(SMTAIServerRequest tranReq) throws Exception 
    {
        String groupId = tranReq.convParamToString("group_id", true);
        
        SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
        try
        {
            SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
            DBRecords recs = db.querySQL("SELECT file_id, file_name, file_type, create_time, length(file_text) as file_size FROM doc_file_list WHERE file_group=?", new Object[] {groupId});
            jsonWr.beginArray("values");
            for(DBRecord rec : recs.getRecords())
            {
                jsonWr.beginMap(null);
                {
                    jsonWr.addKeyValue("id", rec.getString("file_id"));
                    jsonWr.addKeyValue("name", rec.getString("file_name"));
                    jsonWr.addKeyValue("type", rec.getString("file_type"));
                    jsonWr.addKeyValue("time", rec.getString("create_time"));
                    jsonWr.addKeyValue("size", rec.getInteger("file_size"));
                }
                jsonWr.endMap();
            }
            jsonWr.endArray();
            
            return tranReq.returnJson(jsonWr);
        }
        finally
        {
            db.close();
        }        
    }
    
    public ModelAndView deleteKnowledgeFile(SMTAIServerRequest tranReq) throws Exception 
    {
        String fileId = tranReq.convParamToString("file_id", true);
        SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
        try
        {
            db.executeSQL("BEGIN", null);
            try
            {
                db.executeSQL("DELETE FROM doc_file_list WHERE file_id=?", new Object[] {fileId});
                db.executeSQL("DELETE FROM doc_file_vector WHERE file_id=?", new Object[] {fileId}); 
                db.executeSQL("DELETE FROM knowlg_file_list WHERE knowlg_file_id=?", new Object[] {fileId}); 
                db.executeSQL("COMMIT", null);
            }
            catch(Exception ex)
            {
                db.rollbackDB(ex);
            }
            
            return tranReq.returnJsonState(true, null, null);
        }
        finally
        {
            db.close();
        }        
    }
    
    public ModelAndView addKnowledgeFile(SMTAIServerRequest tranReq, @RequestParam(value = "file", required = false) MultipartFile file) throws Exception 
    {
        String fileName = file.getOriginalFilename();
        String groupId = tranReq.convParamToString("group_id", true);
        String fileText = SMTStatic.readTextStream(file.getInputStream());
 
        
        String fileType;
        List<String> listBlock = null;
        if(fileName.endsWith(".md"))
        {
            fileType = "markdown";
            listBlock = splitMarkdownToVectorBlock(fileText);
        }
        else
        {
            return tranReq.returnJsonState(false, "文件格式不支持", null);
        }
        
        List<String> listVector = new ArrayList<>();
        SMTLLMConnect llm = SMTAIServerApp.getApp().allocLLMConnect(null);
        try
        {
            for(String text : listBlock)
            {
                listVector.add(llm.getVector(text));
            }
        }
        finally
        {
            llm.close();
        }
        
        
        SMTDatabase db = SMTAIServerApp.getApp().allocDatabase();
        try
        {
            db.executeSQL("BEGIN", null);
            try
            {
                String fileId = SMTStatic.newUUID();
                db.executeSQL("INSERT INTO doc_file_list(file_id, file_name, file_type, create_time, file_text, file_group)VALUES(?,?,?,?,?,?)", new Object[] {
                    fileId,
                    fileName,
                    fileType,
                    new Date(),
                    fileText,
                    groupId
                });
                
                for(int i = 0; i < listBlock.size(); i ++)
                {
                    db.executeSQL("INSERT INTO doc_file_vector(file_id, vector_index, vector_text, vector_value)VALUES(?,?,?,?::vector)", new Object[] {
                        fileId,
                        i,
                        listBlock.get(i),
                        "[" + listVector.get(i) + "]"
                    });
                }
                
                db.executeSQL("COMMIT", null);
                
                SMTJsonWriter jsonWr = tranReq.newReturnJsonWriter(true, null, null);
                jsonWr.addKeyValue("file_id", fileId);
                return tranReq.returnJson(jsonWr);
            }
            catch(Exception ex)
            {
                db.rollbackDB(ex);
                return null;
            }
        }
        finally
        {
            db.close();
        }
 
    }
    
    private List<String> splitMarkdownToVectorBlock(String fileText) throws Exception
    {
        List<String> blocks = new ArrayList<>();
        String currentBlock = "";
 
        BufferedReader reader = new BufferedReader(new StringReader(fileText));
        try
        {
            String line;
            while ((line = reader.readLine())!= null) {
                // 忽略空行
                if (line.matches("\\s*?\\n")) {
                    continue;
                }
 
                // 当遇到标题或者是新的段落时,结束当前块
                if (line.matches("#+.+") || line.matches("\\s*?\\n\\s*?\\n")) {
                    if (!currentBlock.isEmpty()) {
                        blocks.add(currentBlock);
                        currentBlock = "";
                    }
                }
 
                // 添加行到当前块
                currentBlock += line + "\n";
            }
 
            // 添加最后一个块
            if (!currentBlock.isEmpty()) {
                blocks.add(currentBlock);
            }
        } 
        finally
        {
            reader.close();
        }
 
        return blocks;
    }
}