余思翰 пре 2 недеља
родитељ
комит
ffe640c8c8

+ 0
- 13
llm-back/pom.xml Прегледај датотеку

@@ -68,19 +68,6 @@
68 68
                 <scope>import</scope>
69 69
             </dependency>
70 70
 
71
-            <!-- 覆盖logback的依赖配置-->
72
-            <dependency>
73
-                <groupId>ch.qos.logback</groupId>
74
-                <artifactId>logback-core</artifactId>
75
-                <version>${logback.version}</version>
76
-            </dependency>
77
-
78
-            <dependency>
79
-                <groupId>ch.qos.logback</groupId>
80
-                <artifactId>logback-classic</artifactId>
81
-                <version>${logback.version}</version>
82
-            </dependency>
83
-
84 71
             <!-- 覆盖tomcat的依赖配置-->
85 72
             <dependency>
86 73
                 <groupId>org.apache.tomcat.embed</groupId>

+ 1
- 11
llm-back/ruoyi-agent/pom.xml Прегледај датотеку

@@ -21,22 +21,12 @@
21 21
             <groupId>com.ruoyi</groupId>
22 22
             <artifactId>ruoyi-framework</artifactId>
23 23
         </dependency>
24
-        <dependency>
25
-            <groupId>com.ruoyi</groupId>
26
-            <artifactId>ruoyi-system</artifactId>
27
-        </dependency>
24
+
28 25
         <dependency>
29 26
             <groupId>com.ruoyi</groupId>
30 27
             <artifactId>ruoyi-common</artifactId>
31 28
         </dependency>
32 29
 
33
-        <!-- spring-boot-devtools -->
34
-        <dependency>
35
-            <groupId>org.springframework.boot</groupId>
36
-            <artifactId>spring-boot-devtools</artifactId>
37
-            <optional>true</optional> <!-- 表示依赖不会传递 -->
38
-        </dependency>
39
-
40 30
         <!-- 向量数据库-->
41 31
         <dependency>
42 32
             <groupId>io.milvus</groupId>

+ 0
- 63
llm-back/ruoyi-agent/src/main/java/com/cmc/agent/controller/KnowLedgeController.java Прегледај датотеку

@@ -1,63 +0,0 @@
1
-package com.cmc.agent.controller;
2
-
3
-import com.ruoyi.common.config.RuoYiConfig;
4
-import com.ruoyi.common.core.controller.BaseController;
5
-import com.ruoyi.common.core.domain.AjaxResult;
6
-import com.cmc.agent.service.LangChainMilvusService;
7
-import dev.langchain4j.model.embedding.onnx.bgesmallzhv15.BgeSmallZhV15EmbeddingModel;
8
-import dev.langchain4j.model.embedding.EmbeddingModel;
9
-import org.springframework.web.bind.annotation.*;
10
-import org.springframework.web.multipart.MultipartFile;
11
-
12
-import java.io.File;
13
-import java.io.IOException;
14
-
15
-/**
16
- * cmc知识库Controller
17
- * 
18
- * @author cmc
19
- * @date 2025-04-08
20
- */
21
-@RestController
22
-@RequestMapping("/llm/knowledge")
23
-public class KnowLedgeController extends BaseController
24
-{
25
-    private static final EmbeddingModel embeddingModel = new BgeSmallZhV15EmbeddingModel();
26
-
27
-    /**
28
-     * 新建知识库
29
-     */
30
-    @PostMapping("/create")
31
-    public AjaxResult createKnowLedgeBase(String collectionName)
32
-    {
33
-        LangChainMilvusService langChainMilvusService = new LangChainMilvusService(
34
-                "192.168.28.188",
35
-                19530,
36
-                collectionName,
37
-                embeddingModel);
38
-        langChainMilvusService.createCollection(512);
39
-        return success();
40
-    }
41
-
42
-    /**
43
-     * 插入知识库文件
44
-     */
45
-    @PostMapping("/insert")
46
-    public AjaxResult insertKnowledge(MultipartFile file, String collectionName) throws IOException {
47
-        LangChainMilvusService langChainMilvusService = new LangChainMilvusService(
48
-                "192.168.28.188",
49
-                19530,
50
-                collectionName,
51
-                embeddingModel);
52
-
53
-        File profilePath = new File( RuoYiConfig.getProfile() + "/upload/knowledge");
54
-        if (!profilePath.exists())
55
-            profilePath.mkdirs();
56
-        File transferFile = new File( profilePath + "/" + file.getOriginalFilename());
57
-        if (!transferFile.exists())
58
-            file.transferTo(transferFile);
59
-        langChainMilvusService.insertLangchainEmbeddingDocument(transferFile);
60
-        return success();
61
-    }
62
-
63
-}

+ 0
- 45
llm-back/ruoyi-agent/src/main/java/com/cmc/agent/controller/RagController.java Прегледај датотеку

@@ -1,45 +0,0 @@
1
-package com.cmc.agent.controller;
2
-
3
-import com.ruoyi.common.core.controller.BaseController;
4
-import com.ruoyi.common.core.domain.AjaxResult;
5
-import com.cmc.agent.service.LangChainMilvusService;
6
-import dev.langchain4j.model.embedding.EmbeddingModel;
7
-import dev.langchain4j.model.embedding.onnx.bgesmallzhv15.BgeSmallZhV15EmbeddingModel;
8
-import org.springframework.web.bind.annotation.PostMapping;
9
-import org.springframework.web.bind.annotation.RequestMapping;
10
-import org.springframework.web.bind.annotation.RestController;
11
-
12
-import java.io.IOException;
13
-import java.util.List;
14
-
15
-/**
16
- * cmc知识库Controller
17
- * 
18
- * @author cmc
19
- * @date 2025-04-08
20
- */
21
-@RestController
22
-@RequestMapping("/llm/rag")
23
-public class RagController extends BaseController
24
-{
25
-    private static final EmbeddingModel embeddingModel = new BgeSmallZhV15EmbeddingModel();
26
-
27
-    /**
28
-     * 增强检索生成回答
29
-     */
30
-    @PostMapping("/answer")
31
-    public AjaxResult answer(String question, String collectionName) throws IOException {
32
-        LangChainMilvusService langChainMilvusService = new LangChainMilvusService(
33
-                "192.168.28.188",
34
-                19530,
35
-                collectionName,
36
-                embeddingModel);
37
-
38
-        // 1. Milvus检索
39
-        List<String> contexts = langChainMilvusService.retrieveFromMilvus(question, 3);
40
-
41
-        // 2. 调用本地LLM或HTTP服务
42
-        return success(langChainMilvusService.generateAnswerWithRag(question, contexts));
43
-    }
44
-
45
-}

+ 0
- 55
llm-back/ruoyi-agent/src/main/java/com/cmc/agent/controller/SessionController.java Прегледај датотеку

@@ -1,55 +0,0 @@
1
-package com.cmc.agent.controller;
2
-
3
-import com.google.gson.Gson;
4
-import com.ruoyi.common.core.controller.BaseController;
5
-import com.ruoyi.common.core.domain.AjaxResult;
6
-import okhttp3.*;
7
-import org.springframework.web.bind.annotation.PostMapping;
8
-import org.springframework.web.bind.annotation.RequestMapping;
9
-import org.springframework.web.bind.annotation.RestController;
10
-
11
-import java.io.IOException;
12
-import java.util.HashMap;
13
-import java.util.Map;
14
-
15
-/**
16
- * cmc知识库Controller
17
- * 
18
- * @author cmc
19
- * @date 2025-04-08
20
- */
21
-@RestController
22
-@RequestMapping("/llm/session")
23
-public class SessionController extends BaseController
24
-{
25
-    /**
26
-     * 生成回答
27
-     */
28
-    @PostMapping("/answer")
29
-    public AjaxResult answer(String question) throws IOException {
30
-
31
-        // 1. 调用本地LLM或HTTP服务
32
-        return success(generateAnswer(question));
33
-    }
34
-
35
-    // 调用LLM生成回答
36
-    public String generateAnswer(String question) throws IOException {
37
-        Gson gson = new Gson();
38
-        Map<String, String> hashMap = new HashMap<>();
39
-        hashMap.put("prompt", question);
40
-        hashMap.put("max_tokens", "512");
41
-        RequestBody body = RequestBody.create(
42
-                MediaType.parse("application/json"),
43
-                new Gson().toJson(hashMap));
44
-
45
-        Request request = new Request.Builder()
46
-                .url("http://192.168.28.188:8080/generate")
47
-                .post(body)
48
-                .build();
49
-
50
-        try (Response response = new OkHttpClient().newCall(request).execute()) {
51
-            return gson.fromJson(response.body().string(), Map.class).get("generated_text").toString();
52
-        }
53
-    }
54
-
55
-}

+ 0
- 208
llm-back/ruoyi-agent/src/main/java/com/cmc/agent/service/LangChainMilvusService.java Прегледај датотеку

@@ -1,208 +0,0 @@
1
-package com.cmc.agent.service;
2
-
3
-import com.google.gson.Gson;
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
-
10
-import io.milvus.client.MilvusServiceClient;
11
-import io.milvus.grpc.DataType;
12
-import io.milvus.grpc.MutationResult;
13
-import io.milvus.grpc.SearchResults;
14
-import io.milvus.param.ConnectParam;
15
-import io.milvus.param.IndexType;
16
-import io.milvus.param.MetricType;
17
-import io.milvus.param.R;
18
-import io.milvus.param.collection.CreateCollectionParam;
19
-import io.milvus.param.collection.FieldType;
20
-import io.milvus.param.dml.InsertParam;
21
-import io.milvus.param.dml.SearchParam;
22
-import io.milvus.param.index.CreateIndexParam;
23
-import io.milvus.response.SearchResultsWrapper;
24
-import okhttp3.*;
25
-
26
-import java.io.File;
27
-import java.io.FileInputStream;
28
-import java.io.IOException;
29
-import java.io.InputStream;
30
-import java.util.*;
31
-import java.util.stream.Collectors;
32
-
33
-public class LangChainMilvusService {
34
-    private String LLM_SERVICE_URL;
35
-    private MilvusServiceClient milvusClient;
36
-    private String collectionName;
37
-    private EmbeddingModel embeddingModel;
38
-
39
-    /**
40
-     * 连接milvus知识库,加入langchain自带emdding
41
-     */
42
-    public LangChainMilvusService(String host, int port, String collectionName, EmbeddingModel embeddingModel) {
43
-        this.milvusClient = new MilvusServiceClient(
44
-                ConnectParam.newBuilder()
45
-                        .withHost(host)
46
-                        .withPort(port)
47
-                        .build()
48
-        );
49
-        this.LLM_SERVICE_URL = "http://" + host + ":8000/generate";
50
-        this.collectionName = collectionName;
51
-        this.embeddingModel = embeddingModel;
52
-    }
53
-
54
-    /**
55
-     * 不使用向量数据库
56
-     */
57
-    public LangChainMilvusService(String host, int port) {
58
-        this.milvusClient = new MilvusServiceClient(
59
-                ConnectParam.newBuilder()
60
-                        .withHost(host)
61
-                        .withPort(port)
62
-                        .build()
63
-        );
64
-        this.LLM_SERVICE_URL = "http://" + host + ":8000/generate";
65
-    }
66
-
67
-    /**
68
-     * 新建知识库Collection(含Schema、Field、Index)
69
-     */
70
-    public void createCollection(int dimension) {
71
-        FieldType idField = FieldType.newBuilder()
72
-                .withName("id")
73
-                .withDataType(DataType.Int64)
74
-                .withPrimaryKey(true)
75
-                .withAutoID(true)
76
-                .build();
77
-
78
-        FieldType fileNameField = FieldType.newBuilder()
79
-                .withName("file_name")
80
-                .withDataType(DataType.VarChar)
81
-                .withMaxLength(256)
82
-                .build();
83
-
84
-        FieldType contentField = FieldType.newBuilder()
85
-                .withName("content")
86
-                .withDataType(DataType.VarChar)
87
-                .withMaxLength(65535)
88
-                .build();
89
-
90
-        FieldType vectorField = FieldType.newBuilder()
91
-                .withName("embedding")
92
-                .withDataType(DataType.Float16Vector)
93
-                .withDimension(dimension)
94
-                .build();
95
-
96
-        CreateCollectionParam createCollectionParam = CreateCollectionParam.newBuilder()
97
-                .withCollectionName(collectionName)
98
-                .addFieldType(idField)
99
-                .addFieldType(fileNameField)
100
-                .addFieldType(contentField)
101
-                .addFieldType(vectorField)
102
-                .build();
103
-
104
-        milvusClient.createCollection(createCollectionParam);
105
-
106
-        // 创建索引
107
-        CreateIndexParam createIndexParam = CreateIndexParam.newBuilder()
108
-                .withCollectionName(collectionName)
109
-                .withFieldName("embedding")
110
-                .withIndexType(IndexType.IVF_FLAT)
111
-                .withMetricType(MetricType.COSINE)
112
-                .withExtraParam("{\"nlist\": 64}")
113
-                .build();
114
-
115
-        milvusClient.createIndex(createIndexParam);
116
-    }
117
-
118
-    public void insertLangchainEmbeddingDocument(File file) throws IOException {
119
-        // 加载文档
120
-        InputStream fileInputStream = new FileInputStream(file);
121
-        Document document = new ApachePdfBoxDocumentParser().parse(fileInputStream);
122
-        DocumentByParagraphSplitter splitter = new DocumentByParagraphSplitter(150,10);;
123
-        List<TextSegment> segments = splitter.split(document);
124
-
125
-        // 提取文本和生成嵌入
126
-        List<String> texts = new ArrayList<>();
127
-        List<List<Float>> embeddings = new ArrayList<>();
128
-
129
-        for (TextSegment segment : segments) {
130
-            String text = segment.text();
131
-            if (text.trim().isEmpty())
132
-                continue;
133
-            texts.add(text);
134
-            embeddings.add(embeddingModel.embed(text).content().vectorAsList());
135
-        }
136
-
137
-        // 准备插入数据
138
-        List<InsertParam.Field> fields = new ArrayList<>();
139
-        fields.add(new InsertParam.Field("file_name", Arrays.asList(file.getName())));
140
-        fields.add(new InsertParam.Field("content", Arrays.asList(texts)));
141
-        fields.add(new InsertParam.Field("embedding", Arrays.asList(embeddings)));
142
-
143
-        InsertParam insertParam = InsertParam.newBuilder()
144
-                .withCollectionName(collectionName)
145
-                .withFields(fields)
146
-                .build();
147
-
148
-        // 执行插入
149
-        R<MutationResult> insertResult = milvusClient.insert(insertParam);
150
-
151
-        if (insertResult.getStatus() != R.Status.Success.getCode()) {
152
-            throw new RuntimeException("Failed to insert document: " + insertResult.getMessage());
153
-        }
154
-    }
155
-
156
-    // 从Milvus检索相关文档
157
-    public List<String> retrieveFromMilvus(String query, int topK) throws IOException {
158
-        List<Float> queryVector = embeddingModel.embed(query).content().vectorAsList();
159
-
160
-        SearchParam searchParam = SearchParam.newBuilder()
161
-                .withCollectionName(collectionName)
162
-                .withVectors(queryVector)
163
-                .withTopK(topK)
164
-                .withOutFields(Arrays.asList("content"))
165
-                .build();
166
-
167
-        R<SearchResults> response = milvusClient.search(searchParam);
168
-        SearchResultsWrapper wrapper = new SearchResultsWrapper(response.getData().getResults());
169
-
170
-        return wrapper.getRowRecords(0).stream()
171
-                .map(record -> (String) record.get("content"))
172
-                .collect(Collectors.toList());
173
-    }
174
-
175
-    // 调用LLM+RAG生成回答
176
-    public String generateAnswerWithRag(String question, List<String> contexts) throws IOException {
177
-        String prompt = buildPrompt(question, contexts);
178
-        Gson gson = new Gson();
179
-        Map<String, String> hashMap = new HashMap<>();
180
-        hashMap.put("prompt", prompt);
181
-        hashMap.put("max_tokens", "512");
182
-        RequestBody body = RequestBody.create(
183
-                MediaType.parse("application/json"),
184
-                new Gson().toJson(hashMap));
185
-
186
-        Request request = new Request.Builder()
187
-                .url(LLM_SERVICE_URL)
188
-                .post(body)
189
-                .build();
190
-
191
-        try (Response response = new OkHttpClient().newCall(request).execute()) {
192
-            return gson.fromJson(response.body().string(), Map.class).get("generated_text").toString();
193
-        }
194
-    }
195
-
196
-    private String buildPrompt(String question, List<String> contexts) {
197
-        StringBuilder sb = new StringBuilder();
198
-        sb.append("根据以下上下文回答问题:\n\n");
199
-        for (int i = 0; i < contexts.size(); i++) {
200
-            sb.append("上下文").append(i+1).append(": ").append(contexts.get(i)).append("\n\n");
201
-        }
202
-        sb.append("问题: ").append(question).append("\n回答: ");
203
-        return sb.toString();
204
-    }
205
-    public void close() {
206
-        milvusClient.close();
207
-    }
208
-}

+ 35
- 5
llm-back/ruoyi-agent/src/main/java/com/ruoyi/agent/controller/KnowLedgeController.java Прегледај датотеку

@@ -1,9 +1,10 @@
1 1
 package com.ruoyi.agent.controller;
2 2
 
3
+import com.ruoyi.agent.service.LangChainMilvusService;
3 4
 import com.ruoyi.common.config.RuoYiConfig;
4 5
 import com.ruoyi.common.core.controller.BaseController;
5 6
 import com.ruoyi.common.core.domain.AjaxResult;
6
-import com.ruoyi.agent.service.LangChainMilvusService;
7
+import com.ruoyi.agent.service.MilvusService;
7 8
 import dev.langchain4j.model.embedding.onnx.bgesmallzhv15.BgeSmallZhV15EmbeddingModel;
8 9
 import dev.langchain4j.model.embedding.EmbeddingModel;
9 10
 import org.springframework.web.bind.annotation.*;
@@ -11,6 +12,7 @@ import org.springframework.web.multipart.MultipartFile;
11 12
 
12 13
 import java.io.File;
13 14
 import java.io.IOException;
15
+import java.util.List;
14 16
 
15 17
 /**
16 18
  * cmc知识库Controller
@@ -24,18 +26,45 @@ public class KnowLedgeController extends BaseController
24 26
 {
25 27
     private static final EmbeddingModel embeddingModel = new BgeSmallZhV15EmbeddingModel();
26 28
 
29
+    /**
30
+     * 新建知识库
31
+     */
32
+    @GetMapping("/list")
33
+    public AjaxResult listKnowLedgeBase()
34
+    {
35
+        MilvusService milvusService = new MilvusService(
36
+                "192.168.28.188",
37
+                19530);
38
+        List<String> collectionNames = milvusService.getCollectionNames();
39
+        return success(collectionNames);
40
+    }
41
+
27 42
     /**
28 43
      * 新建知识库
29 44
      */
30 45
     @PostMapping("/create")
31 46
     public AjaxResult createKnowLedgeBase(String collectionName)
32 47
     {
33
-        LangChainMilvusService langChainMilvusService = new LangChainMilvusService(
48
+        MilvusService milvusService = new MilvusService(
34 49
                 "192.168.28.188",
35 50
                 19530,
36
-                collectionName,
37
-                embeddingModel);
38
-        langChainMilvusService.createCollection(512);
51
+                collectionName);
52
+        milvusService.createCollection(512);
53
+        milvusService.close();
54
+        return success();
55
+    }
56
+
57
+    /**
58
+     * 新建知识库
59
+     */
60
+    @DeleteMapping("/remove")
61
+    public AjaxResult removeKnowLedgeBase(String collectionName)
62
+    {
63
+        MilvusService milvusService = new MilvusService(
64
+                "192.168.28.188",
65
+                19530);
66
+        milvusService.deleteCollectionName(collectionName);
67
+        milvusService.close();
39 68
         return success();
40 69
     }
41 70
 
@@ -57,6 +86,7 @@ public class KnowLedgeController extends BaseController
57 86
         if (!transferFile.exists())
58 87
             file.transferTo(transferFile);
59 88
         langChainMilvusService.insertLangchainEmbeddingDocument(transferFile);
89
+        langChainMilvusService.close();
60 90
         return success();
61 91
     }
62 92
 

+ 2
- 2
llm-back/ruoyi-agent/src/main/java/com/ruoyi/agent/controller/RagController.java Прегледај датотеку

@@ -5,7 +5,7 @@ import com.ruoyi.common.core.domain.AjaxResult;
5 5
 import com.ruoyi.agent.service.LangChainMilvusService;
6 6
 import dev.langchain4j.model.embedding.EmbeddingModel;
7 7
 import dev.langchain4j.model.embedding.onnx.bgesmallzhv15.BgeSmallZhV15EmbeddingModel;
8
-import org.springframework.web.bind.annotation.PostMapping;
8
+import org.springframework.web.bind.annotation.GetMapping;
9 9
 import org.springframework.web.bind.annotation.RequestMapping;
10 10
 import org.springframework.web.bind.annotation.RestController;
11 11
 
@@ -27,7 +27,7 @@ public class RagController extends BaseController
27 27
     /**
28 28
      * 增强检索生成回答
29 29
      */
30
-    @PostMapping("/answer")
30
+    @GetMapping("/answer")
31 31
     public AjaxResult answer(String question, String collectionName) throws IOException {
32 32
         LangChainMilvusService langChainMilvusService = new LangChainMilvusService(
33 33
                 "192.168.28.188",

+ 2
- 1
llm-back/ruoyi-agent/src/main/java/com/ruoyi/agent/controller/SessionController.java Прегледај датотеку

@@ -34,9 +34,10 @@ public class SessionController extends BaseController
34 34
     // 调用LLM生成回答
35 35
     public String generateAnswer(String question) throws IOException {
36 36
         // 构建带动态参数的URL
37
-        HttpUrl url = HttpUrl.parse("http://192.168.28.188:8080/generate")
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 41
                 .build();
41 42
 
42 43
         Request request = new Request.Builder()

+ 19
- 83
llm-back/ruoyi-agent/src/main/java/com/ruoyi/agent/service/LangChainMilvusService.java Прегледај датотеку

@@ -1,6 +1,6 @@
1 1
 package com.ruoyi.agent.service;
2 2
 
3
-import com.google.gson.Gson;
3
+import com.alibaba.fastjson2.JSONObject;
4 4
 import dev.langchain4j.data.document.Document;
5 5
 import dev.langchain4j.data.document.parser.apache.pdfbox.ApachePdfBoxDocumentParser;
6 6
 import dev.langchain4j.data.document.splitter.DocumentByParagraphSplitter;
@@ -8,18 +8,12 @@ import dev.langchain4j.data.segment.TextSegment;
8 8
 import dev.langchain4j.model.embedding.EmbeddingModel;
9 9
 
10 10
 import io.milvus.client.MilvusServiceClient;
11
-import io.milvus.grpc.DataType;
12 11
 import io.milvus.grpc.MutationResult;
13 12
 import io.milvus.grpc.SearchResults;
14 13
 import io.milvus.param.ConnectParam;
15
-import io.milvus.param.IndexType;
16
-import io.milvus.param.MetricType;
17 14
 import io.milvus.param.R;
18
-import io.milvus.param.collection.CreateCollectionParam;
19
-import io.milvus.param.collection.FieldType;
20 15
 import io.milvus.param.dml.InsertParam;
21 16
 import io.milvus.param.dml.SearchParam;
22
-import io.milvus.param.index.CreateIndexParam;
23 17
 import io.milvus.response.SearchResultsWrapper;
24 18
 import okhttp3.*;
25 19
 
@@ -28,6 +22,7 @@ import java.io.FileInputStream;
28 22
 import java.io.IOException;
29 23
 import java.io.InputStream;
30 24
 import java.util.*;
25
+import java.util.concurrent.TimeUnit;
31 26
 import java.util.stream.Collectors;
32 27
 
33 28
 public class LangChainMilvusService {
@@ -37,7 +32,7 @@ public class LangChainMilvusService {
37 32
     private EmbeddingModel embeddingModel;
38 33
 
39 34
     /**
40
-     * 连接milvus知识库,加入langchain自带emdding
35
+     * 连接milvus知识库指定collection,加入langchain自带emdding
41 36
      */
42 37
     public LangChainMilvusService(String host, int port, String collectionName, EmbeddingModel embeddingModel) {
43 38
         this.milvusClient = new MilvusServiceClient(
@@ -51,70 +46,6 @@ public class LangChainMilvusService {
51 46
         this.embeddingModel = embeddingModel;
52 47
     }
53 48
 
54
-    /**
55
-     * 不使用向量数据库
56
-     */
57
-    public LangChainMilvusService(String host, int port) {
58
-        this.milvusClient = new MilvusServiceClient(
59
-                ConnectParam.newBuilder()
60
-                        .withHost(host)
61
-                        .withPort(port)
62
-                        .build()
63
-        );
64
-        this.LLM_SERVICE_URL = "http://" + host + ":8000/generate";
65
-    }
66
-
67
-    /**
68
-     * 新建知识库Collection(含Schema、Field、Index)
69
-     */
70
-    public void createCollection(int dimension) {
71
-        FieldType idField = FieldType.newBuilder()
72
-                .withName("id")
73
-                .withDataType(DataType.Int64)
74
-                .withPrimaryKey(true)
75
-                .withAutoID(true)
76
-                .build();
77
-
78
-        FieldType fileNameField = FieldType.newBuilder()
79
-                .withName("file_name")
80
-                .withDataType(DataType.VarChar)
81
-                .withMaxLength(256)
82
-                .build();
83
-
84
-        FieldType contentField = FieldType.newBuilder()
85
-                .withName("content")
86
-                .withDataType(DataType.VarChar)
87
-                .withMaxLength(65535)
88
-                .build();
89
-
90
-        FieldType vectorField = FieldType.newBuilder()
91
-                .withName("embedding")
92
-                .withDataType(DataType.Float16Vector)
93
-                .withDimension(dimension)
94
-                .build();
95
-
96
-        CreateCollectionParam createCollectionParam = CreateCollectionParam.newBuilder()
97
-                .withCollectionName(collectionName)
98
-                .addFieldType(idField)
99
-                .addFieldType(fileNameField)
100
-                .addFieldType(contentField)
101
-                .addFieldType(vectorField)
102
-                .build();
103
-
104
-        milvusClient.createCollection(createCollectionParam);
105
-
106
-        // 创建索引
107
-        CreateIndexParam createIndexParam = CreateIndexParam.newBuilder()
108
-                .withCollectionName(collectionName)
109
-                .withFieldName("embedding")
110
-                .withIndexType(IndexType.IVF_FLAT)
111
-                .withMetricType(MetricType.COSINE)
112
-                .withExtraParam("{\"nlist\": 64}")
113
-                .build();
114
-
115
-        milvusClient.createIndex(createIndexParam);
116
-    }
117
-
118 49
     public void insertLangchainEmbeddingDocument(File file) throws IOException {
119 50
         // 加载文档
120 51
         InputStream fileInputStream = new FileInputStream(file);
@@ -175,21 +106,25 @@ public class LangChainMilvusService {
175 106
     // 调用LLM+RAG生成回答
176 107
     public String generateAnswerWithRag(String question, List<String> contexts) throws IOException {
177 108
         String prompt = buildPrompt(question, contexts);
178
-        Gson gson = new Gson();
179
-        Map<String, String> hashMap = new HashMap<>();
180
-        hashMap.put("prompt", prompt);
181
-        hashMap.put("max_tokens", "512");
182
-        RequestBody body = RequestBody.create(
183
-                MediaType.parse("application/json"),
184
-                new Gson().toJson(hashMap));
109
+        // 构建带动态参数的URL
110
+        HttpUrl url = HttpUrl.parse(LLM_SERVICE_URL)
111
+                .newBuilder()
112
+                .addQueryParameter("prompt", prompt)
113
+                .addQueryParameter("max_token", String.valueOf(512))
114
+                .build();
185 115
 
186 116
         Request request = new Request.Builder()
187
-                .url(LLM_SERVICE_URL)
188
-                .post(body)
117
+                .url(url)
118
+                .build();
119
+
120
+        OkHttpClient client = new OkHttpClient.Builder()
121
+                .readTimeout(60, TimeUnit.SECONDS)      // 读取响应超时
189 122
                 .build();
190 123
 
191
-        try (Response response = new OkHttpClient().newCall(request).execute()) {
192
-            return gson.fromJson(response.body().string(), Map.class).get("generated_text").toString();
124
+        try (Response response = client.newCall(request).execute()) {
125
+            String responseBody = response.body().string();
126
+            String responseResult = JSONObject.parseObject(responseBody).getString("generated_text");
127
+            return responseResult;
193 128
         }
194 129
     }
195 130
 
@@ -202,6 +137,7 @@ public class LangChainMilvusService {
202 137
         sb.append("问题: ").append(question).append("\n回答: ");
203 138
         return sb.toString();
204 139
     }
140
+
205 141
     public void close() {
206 142
         milvusClient.close();
207 143
     }

+ 155
- 0
llm-back/ruoyi-agent/src/main/java/com/ruoyi/agent/service/MilvusService.java Прегледај датотеку

@@ -0,0 +1,155 @@
1
+package com.ruoyi.agent.service;
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
+import io.milvus.client.MilvusServiceClient;
10
+import io.milvus.grpc.DataType;
11
+import io.milvus.grpc.MutationResult;
12
+import io.milvus.grpc.SearchResults;
13
+import io.milvus.param.ConnectParam;
14
+import io.milvus.param.IndexType;
15
+import io.milvus.param.MetricType;
16
+import io.milvus.param.R;
17
+import io.milvus.param.collection.CreateCollectionParam;
18
+import io.milvus.param.collection.DropCollectionParam;
19
+import io.milvus.param.collection.FieldType;
20
+import io.milvus.param.dml.InsertParam;
21
+import io.milvus.param.dml.SearchParam;
22
+import io.milvus.param.highlevel.collection.ListCollectionsParam;
23
+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
+import java.util.List;
37
+import java.util.concurrent.TimeUnit;
38
+import java.util.stream.Collectors;
39
+
40
+public class MilvusService {
41
+    private String LLM_SERVICE_URL;
42
+    private MilvusServiceClient milvusClient;
43
+    private String collectionName;
44
+    private EmbeddingModel embeddingModel;
45
+
46
+    /**
47
+     *  连接milvus知识库
48
+     */
49
+    public MilvusService(String host, int port) {
50
+        this.milvusClient = new MilvusServiceClient(
51
+                ConnectParam.newBuilder()
52
+                        .withHost(host)
53
+                        .withPort(port)
54
+                        .build()
55
+        );
56
+    }
57
+
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
+    /**
86
+     * 新建知识库Collection(含Schema、Field、Index)
87
+     */
88
+    public void createCollection(int dimension) {
89
+        FieldType idField = FieldType.newBuilder()
90
+                .withName("id")
91
+                .withDataType(DataType.Int64)
92
+                .withPrimaryKey(true)
93
+                .withAutoID(true)
94
+                .build();
95
+
96
+        FieldType fileNameField = FieldType.newBuilder()
97
+                .withName("file_name")
98
+                .withDataType(DataType.VarChar)
99
+                .withMaxLength(256)
100
+                .build();
101
+
102
+        FieldType contentField = FieldType.newBuilder()
103
+                .withName("content")
104
+                .withDataType(DataType.VarChar)
105
+                .withMaxLength(65535)
106
+                .build();
107
+
108
+        FieldType vectorField = FieldType.newBuilder()
109
+                .withName("embedding")
110
+                .withDataType(DataType.FloatVector)
111
+                .withDimension(dimension)
112
+                .build();
113
+
114
+        CreateCollectionParam createCollectionParam = CreateCollectionParam.newBuilder()
115
+                .withCollectionName(collectionName)
116
+                .addFieldType(idField)
117
+                .addFieldType(fileNameField)
118
+                .addFieldType(contentField)
119
+                .addFieldType(vectorField)
120
+                .build();
121
+
122
+        milvusClient.createCollection(createCollectionParam);
123
+
124
+        // 创建索引
125
+        CreateIndexParam createIndexParam = CreateIndexParam.newBuilder()
126
+                .withCollectionName(collectionName)
127
+                .withFieldName("embedding")
128
+                .withIndexType(IndexType.IVF_FLAT)
129
+                .withMetricType(MetricType.COSINE)
130
+                .withExtraParam("{\"nlist\": 64}")
131
+                .build();
132
+
133
+        milvusClient.createIndex(createIndexParam);
134
+    }
135
+
136
+    /**
137
+     * 查询知识库Collection
138
+     */
139
+    public List<String> getCollectionNames() {
140
+        ListCollectionsParam param = ListCollectionsParam.newBuilder().build();
141
+        return milvusClient.listCollections(param).getData().collectionNames;
142
+    }
143
+
144
+    /**
145
+     * 删除知识库Collection
146
+     */
147
+    public void deleteCollectionName(String collectionName) {
148
+        DropCollectionParam param = DropCollectionParam.newBuilder().withCollectionName(collectionName).build();
149
+        milvusClient.dropCollection(param);
150
+    }
151
+
152
+    public void close() {
153
+        milvusClient.close();
154
+    }
155
+}

Loading…
Откажи
Сачувај