-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
56 lines (50 loc) · 1.09 KB
/
api.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
package deepinfra
import (
"errors"
"io"
"net/http"
"strings"
)
const (
OpenAIDeepInfra = "https://api.deepinfra.com/v1/openai/chat/completions"
GenAIGoogle = "https://generativelanguage.googleapis.com/v1beta"
)
type API struct {
api string // api to call
key string // key in Authorization: Bearer
cli *http.Client
}
func NewAPI(api, key string) API {
return API{api: api, key: key}
}
func (api *API) SetHTTPClient(c *http.Client) {
api.cli = c
}
func (api *API) Request(model Model) (string, error) {
req, err := http.NewRequest("POST", model.API(api.api, api.key), model.Body())
if err != nil {
return "", err
}
model.Header(api.key, req.Header)
cli := http.DefaultClient
if api.cli != nil {
cli = api.cli
}
resp, err := cli.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
sb := strings.Builder{}
sb.WriteString(resp.Status)
sb.WriteByte(' ')
_, _ = io.Copy(&sb, resp.Body)
return "", errors.New(sb.String())
}
err = model.Parse(resp.Body)
if err != nil {
return "", err
}
return model.Output(), nil
}