forked from tmc/langchaingo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
embeddings.go
54 lines (45 loc) · 1.34 KB
/
embeddings.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
package huggingfaceclient
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
)
type embeddingPayload struct {
Options map[string]any
Inputs []string `json:"inputs"`
}
// nolint:lll
func (c *Client) createEmbedding(ctx context.Context, model string, task string, payload *embeddingPayload) ([][]float32, error) {
body := map[string]any{
"inputs": payload.Inputs,
}
for key, value := range payload.Options {
body[key] = value
}
payloadBytes, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("marshal payload: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("%s/pipeline/%s/%s", c.url, task, model), bytes.NewReader(payloadBytes))
if err != nil {
return nil, fmt.Errorf("create request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+c.Token)
req.Header.Set("Content-Type", "application/json")
r, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer r.Body.Close()
if r.StatusCode != http.StatusOK {
msg := fmt.Sprintf("API returned unexpected status code: %d", r.StatusCode)
return nil, fmt.Errorf("%s: %s", msg, "unable to create embeddings") // nolint:goerr113
}
var response [][]float32
if err := json.NewDecoder(r.Body).Decode(&response); err != nil {
return nil, fmt.Errorf("decode response: %w", err)
}
return response, nil
}