-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomponentLKE.go
More file actions
463 lines (408 loc) · 13.7 KB
/
componentLKE.go
File metadata and controls
463 lines (408 loc) · 13.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
// Copyright (c) 2025 minRAG Authors.
//
// This file is part of minRAG.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses>.
// 腾讯云大模型知识引擎LKE https://cloud.tencent.com/product/lke ,适配Embedding和Reranker模型
// 使用OpenAI SDK 接入方式: https://console.cloud.tencent.com/lkeap
package main
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
)
//POST https://lkeap.tencentcloudapi.com/
//Authorization: TC3-HMAC-SHA256 Credential=AKID********************************/2019-02-25/lkeap/tc3_request, SignedHeaders=content-type;host;x-tc-action, Signature=10b1a37a7301a02ca19a647ad722d5e43b4b3cff309d421d85b46093f6ab6c4f
/**
Content-Type: application/json; charset=utf-8
Host: lkeap.tencentcloudapi.com
X-TC-Action: GetEmbedding
X-TC-Version: 2024-05-22
X-TC-Timestamp: 1551113065
X-TC-Region: ap-guangzhou
{"Limit": 1, "Filters": [{"Values": ["\u672a\u547d\u540d"], "Name": "instance-name"}]}
*/
// https://cloud.tencent.com/document/product/1772/115368
// LKEDocumentEmbedder LKE向量化文档字符串.https://cloud.tencent.com/document/product/1772/115343
type LKEDocumentEmbedder struct {
Host string `json:"Host,omitempty"` // lkeap.tencentcloudapi.com
Action string `json:"Action,omitempty"` // GetEmbedding
Region string `json:"Region,omitempty"` // ap-guangzhou
Version string `json:"Version,omitempty"` // 2024-05-22
Algorithm string `json:"Algorithm,omitempty"` // TC3-HMAC-SHA256
Service string `json:"Service,omitempty"`
SecretId string `json:"SecretId,omitempty"`
SecretKey string `json:"SecretKey,omitempty"`
Timestamp int `json:"-"`
Model string `json:"model,omitempty"` // lke-text-embedding-v2
DefaultHeaders map[string]string `json:"defaultHeaders,omitempty"`
Timeout int `json:"timeout,omitempty"`
MaxRetries int `json:"maxRetries,omitempty"`
client *http.Client `json:"-"`
}
func (component *LKEDocumentEmbedder) Initialization(ctx context.Context, input map[string]any) error {
if component.Host == "" {
component.Host = "lkeap.tencentcloudapi.com"
}
if component.Action == "" {
component.Action = "GetEmbedding"
}
if component.Region == "" {
component.Region = "ap-guangzhou"
}
if component.Version == "" {
component.Version = "2024-05-22"
}
if component.Model == "" {
component.Model = "lke-text-embedding-v2"
}
if component.Algorithm == "" {
component.Algorithm = "TC3-HMAC-SHA256"
}
if component.Service == "" {
component.Service = "lkeap"
}
if component.DefaultHeaders == nil {
component.DefaultHeaders = make(map[string]string, 0)
}
if component.Timeout == 0 {
component.Timeout = 180
}
component.client = &http.Client{
Timeout: time.Second * time.Duration(component.Timeout),
}
if component.SecretId == "" {
component.SecretId = config.AIBaseURL
}
if component.SecretKey == "" {
component.SecretKey = config.AIAPIkey
}
return nil
}
func (component *LKEDocumentEmbedder) Run(ctx context.Context, input map[string]any) error {
if input["documentChunks"] == nil {
return errors.New(funcT("input['documentChunks'] cannot be empty"))
}
documentChunks := input["documentChunks"].([]DocumentChunk)
vecDocumentChunks := make([]VecDocumentChunk, 0)
for i := 0; i < len(documentChunks); i++ {
documentChunk := documentChunks[i]
bodyMap := make(map[string]any, 0)
bodyMap["Inputs"] = []string{documentChunk.Markdown}
bodyMap["Model"] = component.Model
bodyByte, err := httpPostLKEBody(component.client, component.SecretId, component.SecretKey, component.Host, component.Algorithm, component.Service, component.Version, component.Action, component.Region, bodyMap)
if err != nil {
input[errorKey] = err
return err
}
rs := struct {
Response struct {
Data []struct {
Embedding []float64 `json:"Embedding,omitempty"`
} `json:"Data,omitempty"`
} `json:"Response,omitempty"`
}{}
err = json.Unmarshal(bodyByte, &rs)
if err != nil {
input[errorKey] = err
return err
}
if len(rs.Response.Data) < 1 {
err := errors.New("httpPostLKEBody data is empty")
input[errorKey] = err
return err
}
embedding, err := vecSerializeFloat64(rs.Response.Data[0].Embedding)
if err != nil {
input[errorKey] = err
return err
}
documentChunks[i].Embedding = embedding
vecdc := VecDocumentChunk{}
vecdc.Id = documentChunks[i].Id
vecdc.DocumentID = documentChunks[i].DocumentID
vecdc.KnowledgeBaseID = documentChunks[i].KnowledgeBaseID
vecdc.SortNo = documentChunks[i].SortNo
vecdc.Status = 2
vecdc.Embedding = embedding
vecDocumentChunks = append(vecDocumentChunks, vecdc)
}
input["documentChunks"] = documentChunks
input["vecDocumentChunks"] = vecDocumentChunks
return nil
}
// LKETextEmbedder LKE向量化字符串文本
type LKETextEmbedder struct {
Host string `json:"Host,omitempty"` // lkeap.tencentcloudapi.com
Action string `json:"Action,omitempty"` // GetEmbedding
Region string `json:"Region,omitempty"` // ap-guangzhou
Version string `json:"Version,omitempty"` // 2024-05-22
Algorithm string `json:"Algorithm,omitempty"` // TC3-HMAC-SHA256
Service string `json:"Service,omitempty"`
SecretId string `json:"SecretId,omitempty"`
SecretKey string `json:"SecretKey,omitempty"`
Timestamp int `json:"-"`
OpenAIChatGenerator
}
func (component *LKETextEmbedder) Initialization(ctx context.Context, input map[string]any) error {
if component.Host == "" {
component.Host = "lkeap.tencentcloudapi.com"
}
if component.Action == "" {
component.Action = "GetEmbedding"
}
if component.Region == "" {
component.Region = "ap-guangzhou"
}
if component.Version == "" {
component.Version = "2024-05-22"
}
if component.Model == "" {
component.Model = "lke-text-embedding-v2"
}
if component.Algorithm == "" {
component.Algorithm = "TC3-HMAC-SHA256"
}
if component.Service == "" {
component.Service = "lkeap"
}
if component.SecretId == "" {
component.SecretId = config.AIBaseURL
}
if component.SecretKey == "" {
component.SecretKey = config.AIAPIkey
}
if component.BaseURL == "" {
component.BaseURL = config.AIBaseURL + "/embeddings"
}
component.OpenAIChatGenerator.Initialization(ctx, input)
return nil
}
func (component *LKETextEmbedder) Run(ctx context.Context, input map[string]any) error {
if input["query"] == nil {
return errors.New(funcT("input['query'] cannot be empty"))
}
query := input["query"].(string)
bodyMap := make(map[string]any, 0)
bodyMap["Inputs"] = []string{query}
bodyMap["Model"] = component.Model
bodyByte, err := httpPostLKEBody(component.client, component.SecretId, component.SecretKey, component.Host, component.Algorithm, component.Service, component.Version, component.Action, component.Region, bodyMap)
if err != nil {
input[errorKey] = err
return err
}
rs := struct {
Response struct {
Data []struct {
Embedding []float64 `json:"Embedding,omitempty"`
} `json:"Data,omitempty"`
} `json:"Response,omitempty"`
}{}
err = json.Unmarshal(bodyByte, &rs)
if err != nil {
input[errorKey] = err
return err
}
if len(rs.Response.Data) < 1 {
err := errors.New("httpPostLKEBody data is empty")
input[errorKey] = err
return err
}
input["embedding"] = rs.Response.Data[0].Embedding
return nil
}
// LKEDocumentChunkReranker LKE对DocumentChunks进行重新排序. https://cloud.tencent.com/document/product/1772/115339
type LKEDocumentChunkReranker struct {
DocumentChunkReranker
Host string `json:"Host,omitempty"` // lkeap.tencentcloudapi.com
Action string `json:"Action,omitempty"` // RunRerank
Region string `json:"Region,omitempty"` // ap-beijing, ap-guangzhou
Version string `json:"Version,omitempty"` // 2024-05-22
Algorithm string `json:"Algorithm,omitempty"` // TC3-HMAC-SHA256
Service string `json:"Service,omitempty"`
SecretId string `json:"SecretId,omitempty"`
SecretKey string `json:"SecretKey,omitempty"`
Timestamp int `json:"-"`
}
func (component *LKEDocumentChunkReranker) Initialization(ctx context.Context, input map[string]any) error {
if component.Host == "" {
component.Host = "lkeap.tencentcloudapi.com"
}
if component.Action == "" {
component.Action = "RunRerank"
}
if component.Region == "" {
component.Region = "ap-guangzhou"
}
if component.Version == "" {
component.Version = "2024-05-22"
}
if component.Model == "" {
component.Model = "lke-reranker-base"
}
if component.Algorithm == "" {
component.Algorithm = "TC3-HMAC-SHA256"
}
if component.Service == "" {
component.Service = "lkeap"
}
component.DocumentChunkReranker.Initialization(ctx, input)
return nil
}
func (component *LKEDocumentChunkReranker) Run(ctx context.Context, input map[string]any) error {
query, topN, score, documentChunks, documents, err := component.checkRerankParameter(ctx, input)
if err != nil {
input[errorKey] = err
return err
}
if documentChunks == nil {
return nil
}
bodyMap := map[string]any{
"Query": query,
"Docs": documents,
"Model": component.Model,
}
bodyByte, err := httpPostLKEBody(component.client, component.SecretId, component.SecretKey, component.Host, component.Algorithm, component.Service, component.Version, component.Action, component.Region, bodyMap)
if err != nil {
input[errorKey] = err
return err
}
rs := struct {
Response struct {
ScoreList []float32 `json:"ScoreList,omitempty"`
} `json:"Response,omitempty"`
}{}
err = json.Unmarshal(bodyByte, &rs)
if err != nil {
input[errorKey] = err
return err
}
if len(rs.Response.ScoreList) != len(documentChunks) {
err := errors.New("httpPostLKEBody ScoreList is error")
input[errorKey] = err
return err
}
for i := 0; i < len(documentChunks); i++ {
documentChunks[i].Score = rs.Response.ScoreList[i]
}
documentChunks = sortDocumentChunksScore(documentChunks, topN, score)
input["documentChunks"] = documentChunks
return nil
}
// https://github.com/TencentCloud/signature-process-demo/blob/main/signature-v3/golang/demo.go
func httpPostLKEBody(client *http.Client, secretId, secretKey, host, algorithm, service, version, action, region string, bodyMap map[string]any) ([]byte, error) {
// 需要设置环境变量 TENCENTCLOUD_SECRET_ID,值为示例的 AKIDz8krbsJ5yKBZQpn74WFkmLPx3*******
var timestamp int64 = time.Now().Unix()
// step 1: build canonical request string
httpRequestMethod := "POST"
canonicalURI := "/"
canonicalQueryString := ""
canonicalHeaders := fmt.Sprintf("content-type:%s\nhost:%s\nx-tc-action:%s\n",
"application/json; charset=utf-8", host, strings.ToLower(action))
signedHeaders := "content-type;host;x-tc-action"
// 序列化请求体
payloadBytes, err := json.Marshal(bodyMap)
// hash 请求体
hashedRequestPayload := sha256hex(string(payloadBytes))
canonicalRequest := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s",
httpRequestMethod,
canonicalURI,
canonicalQueryString,
canonicalHeaders,
signedHeaders,
hashedRequestPayload)
//fmt.Println(canonicalRequest)
// step 2: build string to sign
date := time.Unix(timestamp, 0).UTC().Format("2006-01-02")
credentialScope := fmt.Sprintf("%s/%s/tc3_request", date, service)
hashedCanonicalRequest := sha256hex(canonicalRequest)
string2sign := fmt.Sprintf("%s\n%d\n%s\n%s",
algorithm,
timestamp,
credentialScope,
hashedCanonicalRequest)
//fmt.Println(string2sign)
// step 3: sign string
secretDate := hmacsha256(date, "TC3"+secretKey)
secretService := hmacsha256(service, secretDate)
secretSigning := hmacsha256("tc3_request", secretService)
signature := hex.EncodeToString([]byte(hmacsha256(string2sign, secretSigning)))
//fmt.Println(signature)
// step 4: build authorization
authorization := fmt.Sprintf("%s Credential=%s/%s, SignedHeaders=%s, Signature=%s",
algorithm,
secretId,
credentialScope,
signedHeaders,
signature)
//fmt.Println(authorization)
if err != nil {
return nil, err
}
// 创建HTTP请求
req, err := http.NewRequest(httpRequestMethod, "https://"+host, bytes.NewBuffer(payloadBytes))
if err != nil {
return nil, err
}
// 设置请求头
req.Header.Set("Authorization", authorization)
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Host", host)
req.Header.Set("X-TC-Action", action)
req.Header.Set("X-TC-Timestamp", fmt.Sprintf("%d", timestamp))
req.Header.Set("X-TC-Version", version)
req.Header.Set("X-TC-Region", region)
/*
curl := fmt.Sprintf(`curl -X POST https://%s\
-H "Authorization: %s"\
-H "Content-Type: application/json; charset=utf-8"\
-H "Host: %s"
-H "X-TC-Action: %s"\
-H "X-TC-Timestamp: %d"\
-H "X-TC-Version: %s"\
-H "X-TC-Region: %s"\
-d '%s'`, host, authorization, host, action, timestamp, version, region, payload)
fmt.Println(curl)
*/
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
bodyByte, err := io.ReadAll(resp.Body)
// 检查状态码
if resp.StatusCode != http.StatusOK {
return nil, errors.New(string(bodyByte))
}
return bodyByte, err
}
func sha256hex(s string) string {
b := sha256.Sum256([]byte(s))
return hex.EncodeToString(b[:])
}
func hmacsha256(s, key string) string {
hashed := hmac.New(sha256.New, []byte(key))
hashed.Write([]byte(s))
return string(hashed.Sum(nil))
}