瀏覽代碼

根据rag上下文内容,结合大模型语言回答

lamphua 2 週之前
父節點
當前提交
58f62925ad

+ 0
- 5
llm-back/ruoyi-agent/pom.xml 查看文件

@@ -17,11 +17,6 @@
17 17
 
18 18
     <dependencies>
19 19
 
20
-        <dependency>
21
-            <groupId>com.ruoyi</groupId>
22
-            <artifactId>ruoyi-framework</artifactId>
23
-        </dependency>
24
-
25 20
         <dependency>
26 21
             <groupId>com.ruoyi</groupId>
27 22
             <artifactId>ruoyi-common</artifactId>

+ 23
- 18
llm-back/ruoyi-agent/src/main/java/com/ruoyi/agent/controller/KnowLedgeController.java 查看文件

@@ -24,18 +24,17 @@ import java.util.List;
24 24
 @RequestMapping("/llm/knowledge")
25 25
 public class KnowLedgeController extends BaseController
26 26
 {
27
+    private static final MilvusService milvusService = new MilvusService("192.168.28.188", 19530);
27 28
     private static final EmbeddingModel embeddingModel = new BgeSmallZhV15EmbeddingModel();
28 29
 
29 30
     /**
30 31
      * 新建知识库
31 32
      */
32 33
     @GetMapping("/list")
33
-    public AjaxResult listKnowLedgeBase()
34
+    public AjaxResult listKnowLedgeCollection()
34 35
     {
35
-        MilvusService milvusService = new MilvusService(
36
-                "192.168.28.188",
37
-                19530);
38 36
         List<String> collectionNames = milvusService.getCollectionNames();
37
+        milvusService.close();
39 38
         return success(collectionNames);
40 39
     }
41 40
 
@@ -43,26 +42,30 @@ public class KnowLedgeController extends BaseController
43 42
      * 新建知识库
44 43
      */
45 44
     @PostMapping("/create")
46
-    public AjaxResult createKnowLedgeBase(String collectionName)
45
+    public AjaxResult createKnowLedgeCollection(String collectionName)
47 46
     {
48
-        MilvusService milvusService = new MilvusService(
49
-                "192.168.28.188",
50
-                19530,
51
-                collectionName);
52
-        milvusService.createCollection(512);
47
+        milvusService.createCollection(collectionName, 512);
53 48
         milvusService.close();
54 49
         return success();
55 50
     }
56 51
 
57 52
     /**
58
-     * 新建知识库
53
+     * 修改知识库
54
+     */
55
+    @PostMapping("/modify")
56
+    public AjaxResult modifyKnowLedgeCollection(String collectionName, String newCollectionName)
57
+    {
58
+        milvusService.collectionRename(collectionName, newCollectionName);
59
+        milvusService.close();
60
+        return success();
61
+    }
62
+
63
+    /**
64
+     * 删除知识库集合
59 65
      */
60 66
     @DeleteMapping("/remove")
61
-    public AjaxResult removeKnowLedgeBase(String collectionName)
67
+    public AjaxResult removeKnowLedgeCollection(String collectionName)
62 68
     {
63
-        MilvusService milvusService = new MilvusService(
64
-                "192.168.28.188",
65
-                19530);
66 69
         milvusService.deleteCollectionName(collectionName);
67 70
         milvusService.close();
68 71
         return success();
@@ -72,7 +75,8 @@ public class KnowLedgeController extends BaseController
72 75
      * 插入知识库文件
73 76
      */
74 77
     @PostMapping("/insert")
75
-    public AjaxResult insertKnowledge(MultipartFile file, String collectionName) throws IOException {
78
+    public AjaxResult insertKnowledgeDocument(MultipartFile file, String collectionName) throws IOException
79
+    {
76 80
         LangChainMilvusService langChainMilvusService = new LangChainMilvusService(
77 81
                 "192.168.28.188",
78 82
                 19530,
@@ -82,9 +86,10 @@ public class KnowLedgeController extends BaseController
82 86
         File profilePath = new File( RuoYiConfig.getProfile() + "/upload/knowledge");
83 87
         if (!profilePath.exists())
84 88
             profilePath.mkdirs();
85
-        File transferFile = new File( profilePath + "/" + file.getOriginalFilename());
86
-        if (!transferFile.exists())
89
+        File transferFile = new File( profilePath + File.separator + file.getOriginalFilename());
90
+        if (!transferFile.exists()) {
87 91
             file.transferTo(transferFile);
92
+        }
88 93
         langChainMilvusService.insertLangchainEmbeddingDocument(transferFile);
89 94
         langChainMilvusService.close();
90 95
         return success();

+ 1
- 1
llm-back/ruoyi-agent/src/main/java/com/ruoyi/agent/controller/RagController.java 查看文件

@@ -36,7 +36,7 @@ public class RagController extends BaseController
36 36
                 embeddingModel);
37 37
 
38 38
         // 1. Milvus检索
39
-        List<String> contexts = langChainMilvusService.retrieveFromMilvus(question, 3);
39
+        List<String> contexts = langChainMilvusService.retrieveFromMilvus(question, 1);
40 40
 
41 41
         // 2. 调用本地LLM或HTTP服务
42 42
         return success(langChainMilvusService.generateAnswerWithRag(question, contexts));

+ 1
- 1
llm-back/ruoyi-agent/src/main/java/com/ruoyi/agent/controller/SessionController.java 查看文件

@@ -37,7 +37,7 @@ public class SessionController extends BaseController
37 37
         HttpUrl url = HttpUrl.parse("http://192.168.28.188:8000/generate")
38 38
                 .newBuilder()
39 39
                 .addQueryParameter("prompt", question)
40
-                .addQueryParameter("max_token", String.valueOf(512))
40
+                .addQueryParameter("max_token", String.valueOf(1024))
41 41
                 .build();
42 42
 
43 43
         Request request = new Request.Builder()

+ 28
- 7
llm-back/ruoyi-agent/src/main/java/com/ruoyi/agent/service/LangChainMilvusService.java 查看文件

@@ -11,7 +11,10 @@ import io.milvus.client.MilvusServiceClient;
11 11
 import io.milvus.grpc.MutationResult;
12 12
 import io.milvus.grpc.SearchResults;
13 13
 import io.milvus.param.ConnectParam;
14
+import io.milvus.param.MetricType;
14 15
 import io.milvus.param.R;
16
+import io.milvus.param.RpcStatus;
17
+import io.milvus.param.collection.LoadCollectionParam;
15 18
 import io.milvus.param.dml.InsertParam;
16 19
 import io.milvus.param.dml.SearchParam;
17 20
 import io.milvus.response.SearchResultsWrapper;
@@ -41,7 +44,7 @@ public class LangChainMilvusService {
41 44
                         .withPort(port)
42 45
                         .build()
43 46
         );
44
-        this.LLM_SERVICE_URL = "http://" + host + ":8000/generate";
47
+        this.LLM_SERVICE_URL = "http://" + host + ":8080/generate";
45 48
         this.collectionName = collectionName;
46 49
         this.embeddingModel = embeddingModel;
47 50
     }
@@ -50,10 +53,11 @@ public class LangChainMilvusService {
50 53
         // 加载文档
51 54
         InputStream fileInputStream = new FileInputStream(file);
52 55
         Document document = new ApachePdfBoxDocumentParser().parse(fileInputStream);
53
-        DocumentByParagraphSplitter splitter = new DocumentByParagraphSplitter(150,10);;
56
+        DocumentByParagraphSplitter splitter = new DocumentByParagraphSplitter(1024,0);;
54 57
         List<TextSegment> segments = splitter.split(document);
55 58
 
56 59
         // 提取文本和生成嵌入
60
+        List<String> fileNames = new ArrayList<>();
57 61
         List<String> texts = new ArrayList<>();
58 62
         List<List<Float>> embeddings = new ArrayList<>();
59 63
 
@@ -61,15 +65,16 @@ public class LangChainMilvusService {
61 65
             String text = segment.text();
62 66
             if (text.trim().isEmpty())
63 67
                 continue;
68
+            fileNames.add(file.getName());
64 69
             texts.add(text);
65 70
             embeddings.add(embeddingModel.embed(text).content().vectorAsList());
66 71
         }
67 72
 
68 73
         // 准备插入数据
69 74
         List<InsertParam.Field> fields = new ArrayList<>();
70
-        fields.add(new InsertParam.Field("file_name", Arrays.asList(file.getName())));
71
-        fields.add(new InsertParam.Field("content", Arrays.asList(texts)));
72
-        fields.add(new InsertParam.Field("embedding", Arrays.asList(embeddings)));
75
+        fields.add(new InsertParam.Field("file_name", fileNames));
76
+        fields.add(new InsertParam.Field("content", texts));
77
+        fields.add(new InsertParam.Field("embedding", embeddings));
73 78
 
74 79
         InsertParam insertParam = InsertParam.newBuilder()
75 80
                 .withCollectionName(collectionName)
@@ -86,13 +91,29 @@ public class LangChainMilvusService {
86 91
 
87 92
     // 从Milvus检索相关文档
88 93
     public List<String> retrieveFromMilvus(String query, int topK) throws IOException {
89
-        List<Float> queryVector = embeddingModel.embed(query).content().vectorAsList();
94
+        List<List<Float>> queryVector = Arrays.asList(embeddingModel.embed(query).content().vectorAsList());
90 95
 
96
+        //  加载集合
97
+        LoadCollectionParam loadParam = LoadCollectionParam.newBuilder()
98
+                .withCollectionName(collectionName)
99
+                .build();
100
+
101
+        R<RpcStatus> loadResponse = milvusClient.loadCollection(loadParam);
102
+        if (loadResponse.getStatus() != R.Status.Success.getCode()) {
103
+            System.err.println("Failed to load collection: " + loadResponse.getMessage());
104
+            milvusClient.close();
105
+            return null;
106
+        }
107
+
108
+        // 构建SearchParam
91 109
         SearchParam searchParam = SearchParam.newBuilder()
92 110
                 .withCollectionName(collectionName)
93 111
                 .withVectors(queryVector)
94 112
                 .withTopK(topK)
95 113
                 .withOutFields(Arrays.asList("content"))
114
+                .withVectorFieldName("embedding")
115
+                .withMetricType(MetricType.COSINE)
116
+                .withParams("{\"nprobe\": 1}")
96 117
                 .build();
97 118
 
98 119
         R<SearchResults> response = milvusClient.search(searchParam);
@@ -110,7 +131,7 @@ public class LangChainMilvusService {
110 131
         HttpUrl url = HttpUrl.parse(LLM_SERVICE_URL)
111 132
                 .newBuilder()
112 133
                 .addQueryParameter("prompt", prompt)
113
-                .addQueryParameter("max_token", String.valueOf(512))
134
+                .addQueryParameter("max_token", String.valueOf(1024))
114 135
                 .build();
115 136
 
116 137
         Request request = new Request.Builder()

+ 16
- 57
llm-back/ruoyi-agent/src/main/java/com/ruoyi/agent/service/MilvusService.java 查看文件

@@ -1,47 +1,20 @@
1 1
 package com.ruoyi.agent.service;
2 2
 
3
-import com.alibaba.fastjson2.JSONObject;
4
-import dev.langchain4j.data.document.Document;
5
-import dev.langchain4j.data.document.parser.apache.pdfbox.ApachePdfBoxDocumentParser;
6
-import dev.langchain4j.data.document.splitter.DocumentByParagraphSplitter;
7
-import dev.langchain4j.data.segment.TextSegment;
8
-import dev.langchain4j.model.embedding.EmbeddingModel;
9 3
 import io.milvus.client.MilvusServiceClient;
10 4
 import io.milvus.grpc.DataType;
11
-import io.milvus.grpc.MutationResult;
12
-import io.milvus.grpc.SearchResults;
13 5
 import io.milvus.param.ConnectParam;
14 6
 import io.milvus.param.IndexType;
15 7
 import io.milvus.param.MetricType;
16
-import io.milvus.param.R;
17 8
 import io.milvus.param.collection.CreateCollectionParam;
18 9
 import io.milvus.param.collection.DropCollectionParam;
19 10
 import io.milvus.param.collection.FieldType;
20
-import io.milvus.param.dml.InsertParam;
21
-import io.milvus.param.dml.SearchParam;
11
+import io.milvus.param.collection.RenameCollectionParam;
22 12
 import io.milvus.param.highlevel.collection.ListCollectionsParam;
23 13
 import io.milvus.param.index.CreateIndexParam;
24
-import io.milvus.response.SearchResultsWrapper;
25
-import okhttp3.HttpUrl;
26
-import okhttp3.OkHttpClient;
27
-import okhttp3.Request;
28
-import okhttp3.Response;
29
-
30
-import java.io.File;
31
-import java.io.FileInputStream;
32
-import java.io.IOException;
33
-import java.io.InputStream;
34
-import java.util.ArrayList;
35
-import java.util.Arrays;
36 14
 import java.util.List;
37
-import java.util.concurrent.TimeUnit;
38
-import java.util.stream.Collectors;
39 15
 
40 16
 public class MilvusService {
41
-    private String LLM_SERVICE_URL;
42 17
     private MilvusServiceClient milvusClient;
43
-    private String collectionName;
44
-    private EmbeddingModel embeddingModel;
45 18
 
46 19
     /**
47 20
      *  连接milvus知识库
@@ -55,37 +28,10 @@ public class MilvusService {
55 28
         );
56 29
     }
57 30
 
58
-    /**
59
-     * 连接milvus知识库指定collection
60
-     */
61
-    public MilvusService(String host, int port, String collectionName) {
62
-        this.milvusClient = new MilvusServiceClient(
63
-                ConnectParam.newBuilder()
64
-                        .withHost(host)
65
-                        .withPort(port)
66
-                        .build()
67
-        );
68
-        this.collectionName = collectionName;
69
-    }
70
-
71
-    /**
72
-     * 连接milvus知识库指定collection,加入langchain自带emdding
73
-     */
74
-    public MilvusService(String host, int port, String collectionName, EmbeddingModel embeddingModel) {
75
-        this.milvusClient = new MilvusServiceClient(
76
-                ConnectParam.newBuilder()
77
-                        .withHost(host)
78
-                        .withPort(port)
79
-                        .build()
80
-        );
81
-        this.collectionName = collectionName;
82
-        this.embeddingModel = embeddingModel;
83
-    }
84
-
85 31
     /**
86 32
      * 新建知识库Collection(含Schema、Field、Index)
87 33
      */
88
-    public void createCollection(int dimension) {
34
+    public void createCollection(String collectionName, int dimension) {
89 35
         FieldType idField = FieldType.newBuilder()
90 36
                 .withName("id")
91 37
                 .withDataType(DataType.Int64)
@@ -141,11 +87,24 @@ public class MilvusService {
141 87
         return milvusClient.listCollections(param).getData().collectionNames;
142 88
     }
143 89
 
90
+    /**
91
+     * 修改知识库Collection
92
+     */
93
+    public void collectionRename(String collectionName, String newCollectionName) {
94
+        RenameCollectionParam renameCollectionReq = RenameCollectionParam.newBuilder()
95
+                .withOldCollectionName(collectionName)
96
+                .withNewCollectionName(newCollectionName)
97
+                .build();
98
+
99
+        milvusClient.renameCollection(renameCollectionReq);
100
+    }
101
+
144 102
     /**
145 103
      * 删除知识库Collection
146 104
      */
147 105
     public void deleteCollectionName(String collectionName) {
148
-        DropCollectionParam param = DropCollectionParam.newBuilder().withCollectionName(collectionName).build();
106
+        DropCollectionParam param = DropCollectionParam.newBuilder()
107
+                .withCollectionName(collectionName).build();
149 108
         milvusClient.dropCollection(param);
150 109
     }
151 110
 

Loading…
取消
儲存