-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenai.go
More file actions
84 lines (71 loc) · 1.83 KB
/
openai.go
File metadata and controls
84 lines (71 loc) · 1.83 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
//
// Copyright (C) 2024 Dmitry Kolesnikov
//
// This file may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
// https://github.com/kshard/embeddings
//
package openai
import (
"context"
"errors"
"github.com/fogfish/gurl/v2/http"
ƒ "github.com/fogfish/gurl/v2/http/recv"
ø "github.com/fogfish/gurl/v2/http/send"
"github.com/fogfish/opts"
"github.com/kshard/embeddings"
)
// Creates OpenAI embeddings client.
//
// By default OpenAI reads access token from `~/.netrc`,
// supply custom secret `WithSecret(secret string)` if needed.
//
// The client is configurable using
//
// WithSecret(secret string)
// WithNetRC(host string)
// WithModel(...)
// WithHTTP(opts ...http.Config)
func New(opt ...Option) (*Client, error) {
api := &Client{
host: ø.Authority("https://api.openai.com"),
}
if err := opts.Apply(api, opt); err != nil {
return nil, err
}
if api.Stack == nil {
api.Stack = http.New()
}
return api, api.checkRequired()
}
// Number of tokens consumed within the session
func (c *Client) UsedTokens() int { return c.usedTokens }
// Calculates embedding vector
func (c *Client) Embedding(ctx context.Context, text string) (embeddings.Embedding, error) {
bag, err := http.IO[embedding](c.WithContext(ctx),
http.POST(
ø.URI("%s/v1/embeddings", c.host),
ø.Accept.JSON,
ø.Authorization.Set("Bearer "+c.secret),
ø.ContentType.JSON,
ø.Send(request{
Model: c.model,
Text: text,
}),
ƒ.Status.OK,
ƒ.ContentType.JSON,
),
)
if err != nil {
return embeddings.Embedding{}, err
}
if len(bag.Vectors) != 1 {
return embeddings.Embedding{}, errors.New("invalid response")
}
c.usedTokens += bag.Usage.UsedTokens
return embeddings.Embedding{
Text: text,
Vector: bag.Vectors[0].Vector,
UsedTokens: bag.Usage.UsedTokens,
}, nil
}