forked from tmc/langchaingo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
huggingface.go
72 lines (56 loc) · 1.51 KB
/
huggingface.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
package huggingface
import (
"context"
"strings"
"github.com/aresa7796/langchaingo/embeddings"
"github.com/aresa7796/langchaingo/llms/huggingface"
)
// Huggingface is the embedder using the Huggingface hub api.
type Huggingface struct {
client *huggingface.LLM
Model string
Task string
StripNewLines bool
BatchSize int
}
var _ embeddings.Embedder = &Huggingface{}
func NewHuggingface(opts ...Option) (*Huggingface, error) {
v, err := applyOptions(opts...)
if err != nil {
return nil, err
}
return v, nil
}
func (e *Huggingface) EmbedDocuments(ctx context.Context, texts []string) ([][]float64, error) {
batchedTexts := embeddings.BatchTexts(
embeddings.MaybeRemoveNewLines(texts, e.StripNewLines),
e.BatchSize,
)
emb := make([][]float64, 0, len(texts))
for _, texts := range batchedTexts {
curTextEmbeddings, err := e.client.CreateEmbedding(ctx, texts, e.Model, e.Task)
if err != nil {
return nil, err
}
textLengths := make([]int, 0, len(texts))
for _, text := range texts {
textLengths = append(textLengths, len(text))
}
combined, err := embeddings.CombineVectors(curTextEmbeddings, textLengths)
if err != nil {
return nil, err
}
emb = append(emb, combined)
}
return emb, nil
}
func (e *Huggingface) EmbedQuery(ctx context.Context, text string) ([]float64, error) {
if e.StripNewLines {
text = strings.ReplaceAll(text, "\n", " ")
}
emb, err := e.client.CreateEmbedding(ctx, []string{text}, e.Model, e.Task)
if err != nil {
return nil, err
}
return emb[0], nil
}