-
Notifications
You must be signed in to change notification settings - Fork 20
/
embed_cohere.go
168 lines (148 loc) · 6.03 KB
/
embed_cohere.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
package chromem
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"sync"
)
type EmbeddingModelCohere string
const (
EmbeddingModelCohereMultilingualV2 EmbeddingModelCohere = "embed-multilingual-v2.0"
EmbeddingModelCohereEnglishLightV2 EmbeddingModelCohere = "embed-english-light-v2.0"
EmbeddingModelCohereEnglishV2 EmbeddingModelCohere = "embed-english-v2.0"
EmbeddingModelCohereMultilingualLightV3 EmbeddingModelCohere = "embed-multilingual-light-v3.0"
EmbeddingModelCohereEnglishLightV3 EmbeddingModelCohere = "embed-english-light-v3.0"
EmbeddingModelCohereMultilingualV3 EmbeddingModelCohere = "embed-multilingual-v3.0"
EmbeddingModelCohereEnglishV3 EmbeddingModelCohere = "embed-english-v3.0"
)
// Prefixes for external use.
const (
InputTypeCohereSearchDocumentPrefix string = "search_document: "
InputTypeCohereSearchQueryPrefix string = "search_query: "
InputTypeCohereClassificationPrefix string = "classification: "
InputTypeCohereClusteringPrefix string = "clustering: "
)
// Input types for internal use.
const (
inputTypeCohereSearchDocument string = "search_document"
inputTypeCohereSearchQuery string = "search_query"
inputTypeCohereClassification string = "classification"
inputTypeCohereClustering string = "clustering"
)
const baseURLCohere = "https://api.cohere.ai/v1"
var validInputTypesCohere = map[string]string{
inputTypeCohereSearchDocument: InputTypeCohereSearchDocumentPrefix,
inputTypeCohereSearchQuery: InputTypeCohereSearchQueryPrefix,
inputTypeCohereClassification: InputTypeCohereClassificationPrefix,
inputTypeCohereClustering: InputTypeCohereClusteringPrefix,
}
type cohereResponse struct {
Embeddings [][]float32 `json:"embeddings"`
}
// NewEmbeddingFuncCohere returns a function that creates embeddings for a text
// using Cohere's API. One important difference to OpenAI's and other's APIs is
// that Cohere differentiates between document embeddings and search/query embeddings.
// In order for this embedding func to do the differentiation, you have to prepend
// the text with either "search_document" or "search_query". We'll cut off that
// prefix before sending the document/query body to the API, we'll just use the
// prefix to choose the right "input type" as they call it.
//
// When you set up a chromem-go collection with this embedding function, you might
// want to create the document separately with [NewDocument] and then cut off the
// prefix before adding the document to the collection. Otherwise, when you query
// the collection, the returned documents will still have the prefix in their content.
//
// cohereFunc := chromem.NewEmbeddingFuncCohere(cohereApiKey, chromem.EmbeddingModelCohereEnglishV3)
// content := "The sky is blue because of Rayleigh scattering."
// // Create the document with the prefix.
// contentWithPrefix := chromem.InputTypeCohereSearchDocumentPrefix + content
// doc, _ := NewDocument(ctx, id, metadata, nil, contentWithPrefix, cohereFunc)
// // Remove the prefix so that later query results don't have it.
// doc.Content = content
// _ = collection.AddDocument(ctx, doc)
//
// This is not necessary if you don't keep the content in the documents, as chromem-go
// also works when documents only have embeddings.
// You can also keep the prefix in the document, and only remove it after querying.
//
// We plan to improve this in the future.
func NewEmbeddingFuncCohere(apiKey string, model EmbeddingModelCohere) EmbeddingFunc {
// We don't set a default timeout here, although it's usually a good idea.
// In our case though, the library user can set the timeout on the context,
// and it might have to be a long timeout, depending on the text length.
client := &http.Client{}
var checkedNormalized bool
checkNormalized := sync.Once{}
return func(ctx context.Context, text string) ([]float32, error) {
var inputType string
for validInputType, validInputTypePrefix := range validInputTypesCohere {
if strings.HasPrefix(text, validInputTypePrefix) {
inputType = validInputType
text = strings.TrimPrefix(text, validInputTypePrefix)
break
}
}
if inputType == "" {
return nil, errors.New("text must start with a valid input type plus colon and space")
}
// Prepare the request body.
reqBody, err := json.Marshal(map[string]any{
"model": model,
"texts": []string{text},
"input_type": inputType,
})
if err != nil {
return nil, fmt.Errorf("couldn't marshal request body: %w", err)
}
// Create the request. Creating it with context is important for a timeout
// to be possible, because the client is configured without a timeout.
req, err := http.NewRequestWithContext(ctx, "POST", baseURLCohere+"/embed", bytes.NewBuffer(reqBody))
if err != nil {
return nil, fmt.Errorf("couldn't create request: %w", err)
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+apiKey)
// Send the request.
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("couldn't send request: %w", err)
}
defer resp.Body.Close()
// Check the response status.
if resp.StatusCode != http.StatusOK {
return nil, errors.New("error response from the embedding API: " + resp.Status)
}
// Read and decode the response body.
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("couldn't read response body: %w", err)
}
var embeddingResponse cohereResponse
err = json.Unmarshal(body, &embeddingResponse)
if err != nil {
return nil, fmt.Errorf("couldn't unmarshal response body: %w", err)
}
// Check if the response contains embeddings.
if len(embeddingResponse.Embeddings) == 0 || len(embeddingResponse.Embeddings[0]) == 0 {
return nil, errors.New("no embeddings found in the response")
}
v := embeddingResponse.Embeddings[0]
checkNormalized.Do(func() {
if isNormalized(v) {
checkedNormalized = true
} else {
checkedNormalized = false
}
})
if !checkedNormalized {
v = normalizeVector(v)
}
return v, nil
}
}