-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.go
More file actions
295 lines (256 loc) · 7.96 KB
/
Copy pathclient.go
File metadata and controls
295 lines (256 loc) · 7.96 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
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package openrouter
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
)
const (
defaultBaseURL = "https://openrouter.ai/api/v1"
defaultTimeout = 30 * time.Second
)
// Client is the main client for interacting with the OpenRouter API.
type Client struct {
apiKey string
baseURL string
httpClient *http.Client
// Optional configurations
defaultModel string
referer string
appName string
maxRetries int
retryDelay time.Duration
customHeaders map[string]string
streamConfig *StreamConfig
circuitBreaker *CircuitBreaker
}
// NewClient creates a new OpenRouter API client.
// The API key can be provided either as the first argument (for backwards compatibility)
// or via WithAPIKey option. If both are provided, the option takes precedence.
func NewClient(opts ...ClientOption) *Client {
c := &Client{
baseURL: defaultBaseURL,
httpClient: &http.Client{
Timeout: defaultTimeout,
},
maxRetries: 3,
retryDelay: time.Second,
customHeaders: make(map[string]string),
}
for _, opt := range opts {
opt(c)
}
return c
}
// doRequestOnce performs a single HTTP request to the OpenRouter API without retry logic.
func (c *Client) doRequestOnce(ctx context.Context, method, endpoint string, body any, v any) error {
url := c.baseURL + endpoint
var reqBody io.Reader
if body != nil {
jsonData, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("failed to marshal request body: %w", err)
}
reqBody = strings.NewReader(string(jsonData))
}
req, err := http.NewRequestWithContext(ctx, method, url, reqBody)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
// Set headers
req.Header.Set("Authorization", "Bearer "+c.apiKey)
req.Header.Set("Content-Type", "application/json")
if c.referer != "" {
req.Header.Set("HTTP-Referer", c.referer)
}
if c.appName != "" {
req.Header.Set("X-Title", c.appName)
}
// Add custom headers
for key, value := range c.customHeaders {
req.Header.Set(key, value)
}
// Add metadata headers if present
if reqStruct, ok := body.(interface{ GetMetadata() map[string]any }); ok {
if metadata := reqStruct.GetMetadata(); metadata != nil {
for key, value := range metadata {
headerKey := "X-" + key
if strValue, ok := value.(string); ok {
req.Header.Set(headerKey, strValue)
}
}
}
}
// Perform request
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close() //nolint:errcheck
// Read response body
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %w", err)
}
// Check for errors
if resp.StatusCode >= 400 {
var errorResp ErrorResponse
if err := json.Unmarshal(respBody, &errorResp); err != nil {
msg := string(respBody)
if isHTMLResponse(resp.Header.Get("Content-Type"), respBody) {
msg = fmt.Sprintf("server returned HTML instead of JSON for %s %s (endpoint may not exist or may be misrouted)", method, url)
}
return &RequestError{
StatusCode: resp.StatusCode,
Message: msg,
}
}
return &RequestError{
StatusCode: resp.StatusCode,
Message: errorResp.Error.Message,
Type: errorResp.Error.Type,
Code: errorResp.Error.Code,
}
}
// Unmarshal response
if v != nil && len(respBody) > 0 {
if err := json.Unmarshal(respBody, v); err != nil {
return fmt.Errorf("failed to unmarshal response: %w", err)
}
}
return nil
}
// doRequestOnceRaw performs a single HTTP request and returns the raw response body bytes
// along with the response Content-Type. It is intended for endpoints that return binary
// payloads (e.g. /audio/speech) rather than JSON. Error responses are still decoded as JSON
// matching the OpenRouter API error schema.
func (c *Client) doRequestOnceRaw(ctx context.Context, method, endpoint string, body any) ([]byte, string, error) {
url := c.baseURL + endpoint
var reqBody io.Reader
if body != nil {
jsonData, err := json.Marshal(body)
if err != nil {
return nil, "", fmt.Errorf("failed to marshal request body: %w", err)
}
reqBody = strings.NewReader(string(jsonData))
}
req, err := http.NewRequestWithContext(ctx, method, url, reqBody)
if err != nil {
return nil, "", fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+c.apiKey)
req.Header.Set("Content-Type", "application/json")
if c.referer != "" {
req.Header.Set("HTTP-Referer", c.referer)
}
if c.appName != "" {
req.Header.Set("X-Title", c.appName)
}
for key, value := range c.customHeaders {
req.Header.Set(key, value)
}
if reqStruct, ok := body.(interface{ GetMetadata() map[string]any }); ok {
if metadata := reqStruct.GetMetadata(); metadata != nil {
for key, value := range metadata {
headerKey := "X-" + key
if strValue, ok := value.(string); ok {
req.Header.Set(headerKey, strValue)
}
}
}
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, "", fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close() //nolint:errcheck
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, "", fmt.Errorf("failed to read response body: %w", err)
}
if resp.StatusCode >= 400 {
var errorResp ErrorResponse
if err := json.Unmarshal(respBody, &errorResp); err != nil {
return nil, "", &RequestError{
StatusCode: resp.StatusCode,
Message: string(respBody),
}
}
return nil, "", &RequestError{
StatusCode: resp.StatusCode,
Message: errorResp.Error.Message,
Type: errorResp.Error.Type,
Code: errorResp.Error.Code,
}
}
return respBody, resp.Header.Get("Content-Type"), nil
}
// GetMetadata helper methods for request types
func (r *ChatCompletionRequest) GetMetadata() map[string]any {
return r.Metadata
}
func (r *CompletionRequest) GetMetadata() map[string]any {
return r.Metadata
}
// RequestWithProvider is a type constraint for requests that have provider settings.
// This constraint allows generic functions to work with both ChatCompletionRequest
// and CompletionRequest in a type-safe manner.
type RequestWithProvider interface {
*ChatCompletionRequest | *CompletionRequest
}
// getProvider returns the provider from a request (helper for generic functions).
func getProvider[T RequestWithProvider](req T) *Provider {
switch r := any(req).(type) {
case *ChatCompletionRequest:
return r.Provider
case *CompletionRequest:
return r.Provider
}
return nil
}
// setProviderField sets the provider on a request (helper for generic functions).
func setProviderField[T RequestWithProvider](req T, p *Provider) {
switch r := any(req).(type) {
case *ChatCompletionRequest:
r.Provider = p
case *CompletionRequest:
r.Provider = p
}
}
// processModelSuffix processes model suffixes like :nitro and :floor
// and applies the appropriate provider settings using generics.
func processModelSuffix[T RequestWithProvider](model string, req T) string {
if before, ok := strings.CutSuffix(model, ":nitro"); ok {
// Remove suffix and apply throughput sorting
model = before
provider := getProvider(req)
if provider == nil {
provider = &Provider{}
}
provider.Sort = "throughput"
setProviderField(req, provider)
} else if before, ok := strings.CutSuffix(model, ":floor"); ok {
// Remove suffix and apply price sorting
model = before
provider := getProvider(req)
if provider == nil {
provider = &Provider{}
}
provider.Sort = "price"
setProviderField(req, provider)
}
return model
}
// isHTMLResponse reports whether the response looks like HTML rather than JSON.
// OpenRouter's Next.js frontend returns HTML pages for missing/misrouted API
// paths, which produces confusing error messages when dumped verbatim.
func isHTMLResponse(contentType string, body []byte) bool {
if strings.Contains(strings.ToLower(contentType), "text/html") {
return true
}
trimmed := strings.TrimLeft(string(body), " \t\r\n")
return strings.HasPrefix(trimmed, "<!DOCTYPE") || strings.HasPrefix(trimmed, "<html")
}