-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomponentOpenAI.go
1606 lines (1470 loc) · 46.8 KB
/
componentOpenAI.go
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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>.
package main
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"reflect"
"sort"
"strconv"
"strings"
"text/template"
"time"
"gitee.com/chunanyong/zorm"
"github.com/chromedp/chromedp"
"github.com/cloudwego/hertz/pkg/app"
"golang.org/x/net/html"
)
const (
errorKey string = "__error__"
nextComponentKey string = "__next__"
endKey string = "__end__"
ifEmptyStop string = "__ifEmptyStop__"
)
// TODO 缺少 function call 的实现和测试
// componentTypeMap 组件类型对照,key是类型名称,value是组件实例
var componentTypeMap = map[string]IComponent{
"Pipeline": &Pipeline{},
"ChatMessageLogStore": &ChatMessageLogStore{},
"OpenAIChatGenerator": &OpenAIChatGenerator{},
"OpenAIChatMemory": &OpenAIChatMemory{},
"PromptBuilder": &PromptBuilder{},
"DocumentChunkReranker": &DocumentChunkReranker{},
"BaiLianDocumentChunkReranker": &BaiLianDocumentChunkReranker{},
"GiteeDocumentChunkReranker": &GiteeDocumentChunkReranker{},
"LKEDocumentChunkReranker": &LKEDocumentChunkReranker{},
"FtsKeywordRetriever": &FtsKeywordRetriever{},
"VecEmbeddingRetriever": &VecEmbeddingRetriever{},
"OpenAITextEmbedder": &OpenAITextEmbedder{},
"LKETextEmbedder": &LKETextEmbedder{},
"SQLiteVecDocumentStore": &SQLiteVecDocumentStore{},
"OpenAIDocumentEmbedder": &OpenAIDocumentEmbedder{},
"LKEDocumentEmbedder": &LKEDocumentEmbedder{},
"DocumentSplitter": &DocumentSplitter{},
"HtmlCleaner": &HtmlCleaner{},
"WebScraper": &WebScraper{},
"MarkdownConverter": &MarkdownConverter{},
"TikaConverter": &TikaConverter{},
}
// componentMap 组件的Map,从数据查询拼装参数
var componentMap = make(map[string]IComponent, 0)
// IComponent 组件的接口
type IComponent interface {
// Initialization 初始化方法
Initialization(ctx context.Context, input map[string]interface{}) error
// Run 执行方法
Run(ctx context.Context, input map[string]interface{}) error
}
func init() {
initComponentMap()
}
// initComponentMap 初始化componentMap
func initComponentMap() {
componentMap = make(map[string]IComponent, 0)
// indexPipeline 比较特殊,默认禁用,为了不让Agent绑定上
finder := zorm.NewSelectFinder(tableComponentName).Append("WHERE status=1 or id=?", "indexPipeline")
cs := make([]Component, 0)
ctx := context.Background()
zorm.Query(ctx, finder, &cs, nil)
for i := 0; i < len(cs); i++ {
c := cs[i]
componentType, has := componentTypeMap[c.ComponentType]
if componentType == nil || (!has) {
continue
}
// 使用反射动态创建一个结构体的指针实例
cType := reflect.TypeOf(componentType).Elem()
cPtr := reflect.New(cType)
// 将反射对象转换为接口类型
component := cPtr.Interface().(IComponent)
if c.Parameter == "" {
err := component.Initialization(ctx, nil)
if err != nil {
FuncLogError(ctx, err)
continue
}
componentMap[c.Id] = component
continue
}
err := json.Unmarshal([]byte(c.Parameter), component)
if err != nil {
FuncLogError(ctx, err)
continue
}
err = component.Initialization(ctx, nil)
if err != nil {
FuncLogError(ctx, err)
continue
}
componentMap[c.Id] = component
}
}
// Pipeline 流水线也是组件
type Pipeline struct {
Start string `json:"start,omitempty"`
Process map[string]string `json:"process,omitempty"`
}
func (component *Pipeline) Initialization(ctx context.Context, input map[string]interface{}) error {
return nil
}
func (component *Pipeline) Run(ctx context.Context, input map[string]interface{}) error {
return component.runProcess(ctx, input, component.Start)
}
func (component *Pipeline) runProcess(ctx context.Context, input map[string]interface{}, componentName string) error {
pipelineComponent, has := componentMap[componentName]
if !has {
return fmt.Errorf(funcT("The %s component of the pipeline does not exist"), componentName)
}
err := pipelineComponent.Run(ctx, input)
if err != nil {
input[errorKey] = err
return err
}
err, has = input[errorKey].(error)
if has {
return err
}
_, has = input[endKey]
if has {
return nil
}
nextComponentName := component.Process[componentName]
nextComponentObj, has := input[nextComponentKey]
if has && nextComponentObj.(string) != "" {
nextComponentName = nextComponentObj.(string)
}
if nextComponentName != "" {
return component.runProcess(ctx, input, nextComponentName)
}
return nil
}
// TikaConverter 使用tika服务解析文档内容
type TikaConverter struct {
FilePath string `json:"filePath,omitempty"`
TiKaURL string `json:"tikaURL,omitempty"`
DefaultHeaders map[string]string `json:"defaultHeaders,omitempty"`
Timeout int `json:"timeout,omitempty"`
MaxRetries int `json:"maxRetries,omitempty"`
client *http.Client `json:"-"`
}
func (component *TikaConverter) Initialization(ctx context.Context, input map[string]interface{}) error {
if component.Timeout == 0 {
component.Timeout = 180
}
component.client = &http.Client{
Timeout: time.Second * time.Duration(component.Timeout),
}
if component.TiKaURL == "" {
component.TiKaURL = "http://localhost:9998/tika"
}
if component.DefaultHeaders == nil {
component.DefaultHeaders = make(map[string]string, 0)
}
accept := component.DefaultHeaders["Accept"]
contentType := component.DefaultHeaders["Content-Type"]
//获取文本内容,没有html等其他标签
if accept == "" {
component.DefaultHeaders["Accept"] = "text/plain"
}
//上传文件的默认类型
if contentType == "" {
component.DefaultHeaders["Content-Type"] = "application/octet-stream"
}
//使用tesseract OCR组件处理PDF里的图片
//component.DefaultHeaders["X-Tika-PDFextractInlineImages"] = "true"
//OCR的字体
//component.DefaultHeaders["X-Tika-OCRLanguage"] = "chi_sim"
return nil
}
func (component *TikaConverter) Run(ctx context.Context, input map[string]interface{}) error {
document, has := input["document"].(*Document)
if document == nil || (!has) {
err := errors.New(funcT("The document of TikaConverter cannot be empty"))
input[errorKey] = err
return err
}
filePath := component.FilePath
if filePath == "" {
filePath = document.FilePath
} else {
document.FilePath = filePath
}
if filePath == "" && document.Markdown == "" {
err := errors.New(funcT("The filePath of TikaConverter cannot be empty"))
input[errorKey] = err
return err
}
if document.Markdown == "" {
markdownByte, err := httpUploadFile(component.client, "PUT", component.TiKaURL, datadir+filePath, component.DefaultHeaders)
if err != nil {
input[errorKey] = err
return err
}
document.Markdown = string(markdownByte)
document.FileSize = len(markdownByte)
}
document.Status = 2
input["document"] = document
return nil
}
// MarkdownConverter markdown文件读取
type MarkdownConverter struct {
FilePath string `json:"filePath,omitempty"`
}
func (component *MarkdownConverter) Initialization(ctx context.Context, input map[string]interface{}) error {
return nil
}
func (component *MarkdownConverter) Run(ctx context.Context, input map[string]interface{}) error {
document, has := input["document"].(*Document)
if document == nil || (!has) {
err := errors.New(funcT("The document of MarkdownConverter cannot be empty"))
input[errorKey] = err
return err
}
filePath := component.FilePath
if filePath == "" {
filePath = document.FilePath
} else {
document.FilePath = filePath
}
if filePath == "" && document.Markdown == "" {
err := errors.New(funcT("The filePath of MarkdownConverter cannot be empty"))
input[errorKey] = err
return err
}
if document.Markdown == "" {
markdownByte, err := os.ReadFile(datadir + filePath)
if err != nil {
input[errorKey] = err
return err
}
document.Markdown = string(markdownByte)
document.FileSize = len(markdownByte)
}
document.Status = 2
input["document"] = document
return nil
}
// WebScraper 网络爬虫
type WebScraper struct {
UserAgent string `json:"userAgent,omitempty"`
WebURL string `json:"webURL,omitempty"`
//抓取的深度,默认1,也就是当前页面
Depth int `json:"depth,omitempty"`
// 需要抓取的 querySelector
QuerySelector []string `json:"querySelector,omitempty"`
KnowledgeBaseID string `json:"knowledgeBaseID,omitempty"`
Timeout int `json:"timeout,omitempty"`
chromedpOptions []chromedp.ExecAllocatorOption
}
func (component *WebScraper) Initialization(ctx context.Context, input map[string]interface{}) error {
if component.Timeout == 0 {
component.Timeout = 60
}
if component.Depth == 0 {
component.Depth = 1
}
if component.UserAgent == "" {
component.UserAgent = "Mozilla/5.0 (Windows NT 11.0; Win64; x64)"
}
qs := make([]string, 0)
for i := 0; i < len(component.QuerySelector); i++ {
if component.QuerySelector[i] == "" {
continue
}
qs = append(qs, component.QuerySelector[i])
}
component.QuerySelector = qs
if len(component.QuerySelector) < 1 {
component.QuerySelector = []string{"html"}
}
component.chromedpOptions = []chromedp.ExecAllocatorOption{
chromedp.Flag("headless", true), // debug使用 false
chromedp.UserAgent(component.UserAgent),
chromedp.Flag("blink-settings", "imagesEnabled=false"),
chromedp.Flag("ignore-certificate-errors", true), // 忽略SSL证书错误[1](@ref)
chromedp.Flag("disable-web-security", true), // 禁用同源策略限制[1](@ref)
chromedp.Flag("disable-hang-monitor", true), // 禁用页面无响应检测[1](@ref)
}
//初始化参数,先传一个空的数据
component.chromedpOptions = append(chromedp.DefaultExecAllocatorOptions[:], component.chromedpOptions...)
return nil
}
func (component *WebScraper) Run(ctx context.Context, input map[string]interface{}) error {
document, has := input["document"].(*Document)
if document == nil || (!has) {
err := errors.New(funcT("The document of WebScraper cannot be empty"))
input[errorKey] = err
return err
}
_, err := component.FetchPage(ctx, document, input)
if err != nil {
input[errorKey] = err
return err
}
return nil
}
// FetchPage 抓取网页,方便后期扩展为递归
func (component *WebScraper) FetchPage(ctx context.Context, document *Document, input map[string]interface{}) ([]string, error) {
webURL, has := input["webScraper_webURL"].(string)
if webURL == "" || (!has) {
webURL = component.WebURL
}
if webURL == "" {
err := errors.New(funcT("The webScraper_webURL of WebScraper cannot be empty"))
input[errorKey] = err
return nil, err
}
allocCtx, cancel := chromedp.NewExecAllocator(ctx, component.chromedpOptions...)
defer cancel()
chromeCtx, cancel := chromedp.NewContext(allocCtx)
defer cancel()
// 执行一个空task, 用提前创建Chrome实例
//chromedp.Run(chromeCtx, make([]chromedp.Action, 0, 1)...)
//创建一个上下文,超时时间为60s
chromeCtx, cancel = context.WithTimeout(chromeCtx, time.Duration(component.Timeout)*time.Second)
defer cancel()
title := ""
qsLen := len(component.QuerySelector)
hcs := make([]string, qsLen)
hrefs := make([][]string, qsLen)
// 双重等待机制
bodyReady := chromedp.WaitReady("body", chromedp.ByQuery) // 等待body标签存在
sleepReady := chromedp.Sleep(2 * time.Second) // 容错性等待
// 自定义处理逻辑,忽略页面错误
actionFunc := chromedp.ActionFunc(func(ctx context.Context) error {
for i := 0; i < qsLen; i++ {
//获取网页的内容,chromedp.AtLeast(0)立即执行,不要等待
err := chromedp.OuterHTML(component.QuerySelector[i], &hcs[i], chromedp.ByQuery, chromedp.AtLeast(0)).Do(ctx)
if err != nil {
continue
}
// 获取页面的超链接
if component.Depth > 1 {
chromedp.Evaluate(fmt.Sprintf("Array.from(document.querySelector('%s').querySelectorAll('a')).map(a => a.href)", component.QuerySelector[i]), &hrefs[i]).Do(ctx)
}
}
return nil
})
// 获取网页的title,放到最后再执行
titleAction := chromedp.Title(&title)
//执行动作
err := chromedp.Run(chromeCtx, chromedp.Navigate(webURL), bodyReady, sleepReady, actionFunc, titleAction)
if err != nil {
return nil, err
}
document.Markdown = strings.Join(hcs, ".")
document.Name = title
herf := make([]string, 0)
if component.Depth > 0 {
for i := 0; i < len(hrefs); i++ {
herf = append(herf, hrefs[i]...)
}
}
return herf, nil
}
// HtmlCleaner 清理html标签
type HtmlCleaner struct {
}
func (component *HtmlCleaner) Initialization(ctx context.Context, input map[string]interface{}) error {
return nil
}
func (component *HtmlCleaner) Run(ctx context.Context, input map[string]interface{}) error {
document, has := input["document"].(*Document)
if document == nil || (!has) {
err := errors.New(funcT("The document of DocumentSplitter cannot be empty"))
input[errorKey] = err
return err
}
doc, err := html.Parse(bytes.NewReader([]byte(document.Markdown)))
if err != nil {
return err
}
var buf strings.Builder
var inScript, inStyle bool // 新增状态标记[1,3](@ref)
var extract func(*html.Node)
extract = func(n *html.Node) {
// 新增标签检测逻辑[6,7](@ref)
switch n.Type {
case html.ElementNode:
switch n.Data {
case "script":
inScript = true
case "style":
inStyle = true
}
case html.TextNode:
if !inScript && !inStyle { // 仅收集非脚本/样式内容[2,4](@ref)
buf.WriteString(strings.TrimSpace(n.Data) + " ")
}
}
// 递归处理子节点(跳过脚本/样式内容)[8](@ref)
if !inScript && !inStyle {
for c := n.FirstChild; c != nil; c = c.NextSibling {
extract(c)
}
}
// 重置标签状态[9](@ref)
if n.Type == html.ElementNode {
switch n.Data {
case "script":
inScript = false
case "style":
inStyle = false
}
}
}
extract(doc)
document.Markdown = html.UnescapeString(buf.String())
return nil
}
// DocumentSplitter 文档拆分
type DocumentSplitter struct {
SplitBy []string `json:"splitBy,omitempty"`
SplitLength int `json:"splitLength,omitempty"`
SplitOverlap int `json:"splitOverlap,omitempty"`
}
func (component *DocumentSplitter) Initialization(ctx context.Context, input map[string]interface{}) error {
return nil
}
func (component *DocumentSplitter) Run(ctx context.Context, input map[string]interface{}) error {
document, has := input["document"].(*Document)
if document == nil || (!has) {
err := errors.New(funcT("The document of DocumentSplitter cannot be empty"))
input[errorKey] = err
return err
}
if len(component.SplitBy) < 1 {
component.SplitBy = []string{"\f", "\n\n", "\n", "。", "!", ".", ";", ",", ",", " "}
}
if component.SplitLength == 0 {
component.SplitLength = 500
}
// 递归分割
chunks := component.recursiveSplit(document.Markdown, 0)
if len(chunks) < 1 {
return nil
}
// 合并3次短内容
for j := 0; j < 3; j++ {
chunks = component.mergeChunks(chunks)
}
// @TODO 处理文本重叠,感觉没有必要了,还会破坏文本的连续性
documentChunks := make([]DocumentChunk, 0)
for i := 0; i < len(chunks); i++ {
chunk := chunks[i]
documentChunk := DocumentChunk{}
documentChunk.Id = FuncGenerateStringID()
documentChunk.DocumentID = document.Id
documentChunk.KnowledgeBaseID = document.KnowledgeBaseID
documentChunk.Markdown = chunk
documentChunk.CreateTime = document.CreateTime
documentChunk.UpdateTime = document.UpdateTime
documentChunk.SortNo = i
documentChunk.Status = document.Status
documentChunks = append(documentChunks, documentChunk)
}
input["documentChunks"] = documentChunks
return nil
}
// OpenAIDocumentEmbedder 向量化文档字符串
type OpenAIDocumentEmbedder struct {
APIKey string `json:"api_key,omitempty"`
Model string `json:"model,omitempty"`
BaseURL string `json:"base_url,omitempty"`
DefaultHeaders map[string]string `json:"defaultHeaders,omitempty"`
Timeout int `json:"timeout,omitempty"`
MaxRetries int `json:"maxRetries,omitempty"`
client *http.Client `json:"-"`
}
func (component *OpenAIDocumentEmbedder) Initialization(ctx context.Context, input map[string]interface{}) error {
if component.Timeout == 0 {
component.Timeout = 180
}
component.client = &http.Client{
Timeout: time.Second * time.Duration(component.Timeout),
}
if component.BaseURL == "" {
component.BaseURL = config.AIBaseURL
}
if component.APIKey == "" {
component.APIKey = config.AIAPIkey
}
if component.DefaultHeaders == nil {
component.DefaultHeaders = make(map[string]string, 0)
}
return nil
}
func (component *OpenAIDocumentEmbedder) Run(ctx context.Context, input map[string]interface{}) error {
documentChunks, has := input["documentChunks"].([]DocumentChunk)
if !has {
return errors.New(funcT("input['documentChunks'] cannot be empty"))
}
vecDocumentChunks := make([]VecDocumentChunk, 0)
for i := 0; i < len(documentChunks); i++ {
bodyMap := make(map[string]interface{}, 0)
bodyMap["input"] = []string{documentChunks[i].Markdown}
bodyMap["model"] = component.Model
bodyMap["encoding_format"] = "float"
bodyByte, err := httpPostJsonBody(component.client, component.APIKey, component.BaseURL+"/embeddings", component.DefaultHeaders, bodyMap)
if err != nil {
input[errorKey] = err
return err
}
rs := struct {
Data []struct {
Embedding []float64 `json:"embedding,omitempty"`
} `json:"data,omitempty"`
}{}
err = json.Unmarshal(bodyByte, &rs)
if err != nil {
input[errorKey] = err
return err
}
if len(rs.Data) < 1 {
err := errors.New("httpPostJsonBody data is empty")
input[errorKey] = err
return err
}
embedding, err := vecSerializeFloat64(rs.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
}
// SQLiteVecDocumentStore 更新文档和向量
type SQLiteVecDocumentStore struct {
}
func (component *SQLiteVecDocumentStore) Initialization(ctx context.Context, input map[string]interface{}) error {
return nil
}
func (component *SQLiteVecDocumentStore) Run(ctx context.Context, input map[string]interface{}) error {
document, has := input["document"].(*Document)
if !has {
err := errors.New(funcT("The document of SQLiteVecDocumentStore cannot be empty"))
input[errorKey] = err
return err
}
documentChunks := input["documentChunks"].([]DocumentChunk)
vecDocumentChunks := input["vecDocumentChunks"].([]VecDocumentChunk)
_, err := zorm.Transaction(ctx, func(ctx context.Context) (interface{}, error) {
//先删除,重新插入
zorm.Delete(ctx, document)
document.Status = 1
zorm.Insert(ctx, document)
// 删除关联的数据,重新插入
finderDeleteChunk := zorm.NewDeleteFinder(tableDocumentChunkName).Append("WHERE documentID=?", document.Id)
count, err := zorm.UpdateFinder(ctx, finderDeleteChunk)
if err != nil {
return count, err
}
finderDeleteVec := zorm.NewDeleteFinder(tableVecDocumentChunkName).Append("WHERE documentID=?", document.Id)
count, err = zorm.UpdateFinder(ctx, finderDeleteVec)
if err != nil {
return count, err
}
dcs := make([]zorm.IEntityStruct, 0)
vecdcs := make([]zorm.IEntityStruct, 0)
for i := 0; i < len(documentChunks); i++ {
documentChunks[i].Status = 1
dcs = append(dcs, &documentChunks[i])
if len(vecDocumentChunks) < 1 {
continue
}
vecDocumentChunks[i].Status = 1
vecdcs = append(vecdcs, &vecDocumentChunks[i])
}
if len(dcs) > 0 {
count, err = zorm.InsertSlice(ctx, dcs)
if err != nil {
return count, err
}
}
if len(vecdcs) > 0 {
count, err = zorm.InsertSlice(ctx, vecdcs)
if err != nil {
return count, err
}
}
return nil, nil
})
if err != nil {
input[errorKey] = err
}
return err
}
// OpenAITextEmbedder 向量化字符串文本
type OpenAITextEmbedder struct {
APIKey string `json:"api_key,omitempty"`
Model string `json:"model,omitempty"`
BaseURL string `json:"base_url,omitempty"`
DefaultHeaders map[string]string `json:"defaultHeaders,omitempty"`
Timeout int `json:"timeout,omitempty"`
MaxRetries int `json:"maxRetries,omitempty"`
client *http.Client `json:"-"`
}
func (component *OpenAITextEmbedder) Initialization(ctx context.Context, input map[string]interface{}) error {
if component.Timeout == 0 {
component.Timeout = 180
}
component.client = &http.Client{
Timeout: time.Second * time.Duration(component.Timeout),
}
if component.BaseURL == "" {
component.BaseURL = config.AIBaseURL
}
if component.APIKey == "" {
component.APIKey = config.AIAPIkey
}
if component.DefaultHeaders == nil {
component.DefaultHeaders = make(map[string]string, 0)
}
return nil
}
func (component *OpenAITextEmbedder) Run(ctx context.Context, input map[string]interface{}) error {
query, has := input["query"].(string)
if !has {
return errors.New(funcT("input['query'] cannot be empty"))
}
bodyMap := make(map[string]interface{}, 0)
bodyMap["input"] = []string{query}
bodyMap["model"] = component.Model
bodyMap["encoding_format"] = "float"
bodyByte, err := httpPostJsonBody(component.client, component.APIKey, component.BaseURL+"/embeddings", component.DefaultHeaders, bodyMap)
if err != nil {
input[errorKey] = err
return err
}
rs := struct {
Data []struct {
Embedding []float64 `json:"embedding,omitempty"`
} `json:"data,omitempty"`
}{}
err = json.Unmarshal(bodyByte, &rs)
if err != nil {
input[errorKey] = err
return err
}
if len(rs.Data) < 1 {
err := errors.New("httpPostJsonBody data is empty")
input[errorKey] = err
return err
}
input["embedding"] = rs.Data[0].Embedding
return nil
}
// VecEmbeddingRetriever 使用SQLite-Vec向量检索相似数据
type VecEmbeddingRetriever struct {
// DocumentID 文档ID
DocumentID string `json:"documentID,omitempty"`
// KnowledgeBaseID 知识库ID
KnowledgeBaseID string `json:"knowledgeBaseID,omitempty"`
// Embedding 需要查询的向量化数组
Embedding []float64 `json:"embedding,omitempty"`
// TopN 检索多少条
TopN int `json:"top_n,omitempty"`
// Score 向量表的score匹配分数
Score float32 `json:"score,omitempty"`
}
func (component *VecEmbeddingRetriever) Initialization(ctx context.Context, input map[string]interface{}) error {
return nil
}
func (component *VecEmbeddingRetriever) Run(ctx context.Context, input map[string]interface{}) error {
documentID := ""
knowledgeBaseID := ""
topN := 0
var score float32 = 0.0
var embedding []float64 = nil
eId, has := input["embedding"]
if has {
embedding = eId.([]float64)
}
if embedding == nil {
embedding = component.Embedding
}
if embedding == nil {
err := errors.New(funcT("The embedding of VecEmbeddingRetriever cannot be empty"))
input[errorKey] = err
return err
}
dId, has := input["documentID"]
if has {
documentID = dId.(string)
}
if documentID == "" {
documentID = component.DocumentID
}
kId, has := input["knowledgeBaseID"]
if has {
knowledgeBaseID = kId.(string)
}
if knowledgeBaseID == "" {
knowledgeBaseID = component.KnowledgeBaseID
}
tId, has := input["topN"]
if has {
topN = tId.(int)
}
if topN == 0 {
topN = component.TopN
}
if topN == 0 {
topN = 5
}
disId, has := input["score"]
if has {
score = disId.(float32)
}
if score <= 0 {
score = component.Score
}
query, err := vecSerializeFloat64(embedding)
if err != nil {
input[errorKey] = err
return err
}
finder := zorm.NewSelectFinder(tableVecDocumentChunkName, "rowid,distance as score,*").Append("WHERE embedding MATCH ?", query)
if documentID != "" {
finder.Append(" and documentID=?", documentID)
}
if knowledgeBaseID != "" {
// Only one of EQUALS, GREATER_THAN, LESS_THAN_OR_EQUAL, LESS_THAN, GREATER_THAN_OR_EQUAL, NOT_EQUALS is allowed
// vec不支持 like
//finder.Append(" and knowledgeBaseID like ?", knowledgeBaseID+"%")
finder.Append(" and knowledgeBaseID = ?", knowledgeBaseID)
}
// Only one of EQUALS, GREATER_THAN, LESS_THAN_OR_EQUAL, LESS_THAN, GREATER_THAN_OR_EQUAL, NOT_EQUALS is allowed
// vec不支持 范围查询
//if score > 0.0 {
// finder.Append(" and score >= ?", score)
//}
finder.Append("ORDER BY score LIMIT " + strconv.Itoa(topN))
documentChunks := make([]DocumentChunk, 0)
err = zorm.Query(ctx, finder, &documentChunks, nil)
if err != nil {
input[errorKey] = err
return err
}
//更新markdown内容
documentChunks, err = findDocumentChunkMarkDown(ctx, documentChunks)
if err != nil {
input[errorKey] = err
return err
}
//重新排序
documentChunks = sortDocumentChunksScore(documentChunks, topN, score)
oldDcs, has := input["documentChunks"]
if has && oldDcs != nil {
oldDocumentChunks := oldDcs.([]DocumentChunk)
documentChunks = append(oldDocumentChunks, documentChunks...)
}
input["documentChunks"] = documentChunks
return nil
}
// FtsKeywordRetriever 使用Fts5全文检索相似数据
type FtsKeywordRetriever struct {
// DocumentID 文档ID
DocumentID string `json:"documentID,omitempty"`
// KnowledgeBaseID 知识库ID
KnowledgeBaseID string `json:"knowledgeBaseID,omitempty"`
// Query 需要查询的关键字
Query string `json:"query,omitempty"`
// TopN 检索多少条
TopN int `json:"top_n,omitempty"`
// Score BM25的FTS5实现在返回结果之前将结果乘以-1,得分越小(数值上更负),表示匹配越好
Score float32 `json:"score,omitempty"`
}
func (component *FtsKeywordRetriever) Initialization(ctx context.Context, input map[string]interface{}) error {
return nil
}
func (component *FtsKeywordRetriever) Run(ctx context.Context, input map[string]interface{}) error {
documentID := ""
knowledgeBaseID := ""
topN := 0
query := ""
var score float32 = 0.0
qId, has := input["query"]
if has {
query = qId.(string)
}
if query == "" {
query = component.Query
}
if query == "" {
err := errors.New(funcT("The query of FtsKeywordRetriever cannot be empty"))
input[errorKey] = err
return err
}
dId, has := input["documentID"]
if has {
documentID = dId.(string)
}
if documentID == "" {
documentID = component.DocumentID
}
kId, has := input["knowledgeBaseID"]
if has {
knowledgeBaseID = kId.(string)
}
if knowledgeBaseID == "" {
knowledgeBaseID = component.KnowledgeBaseID
}
tId, has := input["topN"]
if has {
topN = tId.(int)
}
if topN == 0 {
topN = component.TopN
}
if topN == 0 {
topN = 5
}
disId, has := input["score"]
if has {
score = disId.(float32)
}
if score <= 0 {
score = component.Score
}
// BM25的FTS5实现在返回结果之前将结果乘以-1,得分越小(数值上更负),表示匹配越好
finder := zorm.NewFinder().Append("SELECT rowid,-1*rank as score,* from fts_document_chunk where fts_document_chunk match jieba_query(?)", query)
if documentID != "" {
finder.Append(" and documentID=?", documentID)
}
if knowledgeBaseID != "" {
finder.Append(" and knowledgeBaseID like ?", knowledgeBaseID+"%")
}
if score > 0.0 { // BM25的FTS5实现在返回结果之前将结果乘以-1,查询时再乘以-1
finder.Append(" and score >= ?", score)
}
finder.Append("ORDER BY score DESC LIMIT " + strconv.Itoa(topN))
documentChunks := make([]DocumentChunk, 0)
err := zorm.Query(ctx, finder, &documentChunks, nil)
if err != nil {
input[errorKey] = err
return err
}
oldDcs, has := input["documentChunks"]
if has && oldDcs != nil {
oldDocumentChunks := oldDcs.([]DocumentChunk)
documentChunks = append(oldDocumentChunks, documentChunks...)
}
input["documentChunks"] = documentChunks
return nil
}
// DocumentChunkReranker 对DocumentChunks进行重新排序
type DocumentChunkReranker struct {
APIKey string `json:"api_key,omitempty"`
Model string `json:"model,omitempty"`
BaseURL string `json:"base_url,omitempty"`
DefaultHeaders map[string]string `json:"defaultHeaders,omitempty"`
Timeout int `json:"timeout,omitempty"`
// Query 需要查询的关键字
Query string `json:"query,omitempty"`
// TopN 检索多少条
TopN int `json:"top_n,omitempty"`
// Score ranker的score匹配分数
Score float32 `json:"score,omitempty"`
client *http.Client `json:"-"`
}
func (component *DocumentChunkReranker) Initialization(ctx context.Context, input map[string]interface{}) error {
if component.Timeout == 0 {
component.Timeout = 180
}
component.client = &http.Client{
Timeout: time.Second * time.Duration(component.Timeout),
}
if component.APIKey == "" {
component.APIKey = config.AIAPIkey
}
if component.BaseURL == "" {
component.BaseURL = config.AIBaseURL + "/reranker"
}
if component.DefaultHeaders == nil {