|
@@ -0,0 +1,208 @@
|
|
1
|
+package com.ruoyi.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
|
+}
|