-
Notifications
You must be signed in to change notification settings - Fork 19
/
client.go
167 lines (136 loc) · 3.34 KB
/
client.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
package anthropic
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)
type Client struct {
config ClientConfig
}
type Response interface {
SetHeader(http.Header)
}
type httpHeader http.Header
func (h *httpHeader) SetHeader(header http.Header) {
*h = httpHeader(header)
}
func (h *httpHeader) Header() http.Header {
return http.Header(*h)
}
func (h *httpHeader) GetRateLimitHeaders() (RateLimitHeaders, error) {
return newRateLimitHeaders(h.Header())
}
// NewClient create new Anthropic API client
func NewClient(apiKey string, opts ...ClientOption) *Client {
return &Client{
config: newConfig(apiKey, opts...),
}
}
func (c *Client) sendRequest(req *http.Request, v Response) error {
res, err := c.config.HTTPClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
v.SetHeader(res.Header)
if err := c.handlerRequestError(res); err != nil {
return err
}
if err = json.NewDecoder(res.Body).Decode(v); err != nil {
return err
}
return nil
}
func (c *Client) handlerRequestError(resp *http.Response) error {
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusBadRequest {
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("error, reading response body: %w", err)
}
// use the adapter to translate the error, if it can
if err, handled := c.config.Adapter.TranslateError(resp, body); handled {
return err
}
var errRes ErrorResponse
err = json.Unmarshal(body, &errRes)
if err != nil || errRes.Error == nil {
reqErr := RequestError{
StatusCode: resp.StatusCode,
Err: err,
Body: body,
}
return &reqErr
}
return fmt.Errorf("error, status code: %d, message: %w", resp.StatusCode, errRes.Error)
}
return nil
}
type requestSetter func(req *http.Request)
func withBetaVersion(betaVersion ...BetaVersion) requestSetter {
version := ""
for i, v := range betaVersion {
version += string(v)
if i < len(betaVersion)-1 {
version += ","
}
}
return func(req *http.Request) {
req.Header.Set("anthropic-beta", version)
}
}
func (c *Client) newRequest(
ctx context.Context,
method, urlSuffix string,
body any,
requestSetters ...requestSetter,
) (req *http.Request, err error) {
// prepare the request
var fullURL string
fullURL, err = c.config.Adapter.PrepareRequest(c, method, urlSuffix, body)
if err != nil {
return nil, err
}
var reqBody []byte
if body != nil {
reqBody, err = json.Marshal(body)
if err != nil {
return nil, err
}
}
req, err = http.NewRequestWithContext(
ctx,
method,
fullURL,
bytes.NewBuffer(reqBody),
)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Accept", "application/json; charset=utf-8")
// set any provider-specific headers (including Authorization)
c.config.Adapter.SetRequestHeaders(c, req)
for _, setter := range requestSetters {
setter(req)
}
return req, nil
}
func (c *Client) newStreamRequest(
ctx context.Context,
method, urlSuffix string,
body any,
requestSetters ...requestSetter,
) (req *http.Request,
err error) {
req, err = c.newRequest(ctx, method, urlSuffix, body, requestSetters...)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "text/event-stream")
req.Header.Set("Cache-Control", "no-cache")
req.Header.Set("Connection", "keep-alive")
return req, nil
}