| 1 |
package openai |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
"encoding/json" |
| 7 |
"fmt" |
| 8 |
"io" |
| 9 |
"math/rand/v2" |
| 10 |
"net/http" |
| 11 |
"net/url" |
| 12 |
"strconv" |
| 13 |
"strings" |
| 14 |
"time" |
| 15 |
|
| 16 |
"github.com/clnkr-ai/clnkr" |
| 17 |
"github.com/clnkr-ai/clnkr/internal/providers/openaiwire" |
| 18 |
) |
| 19 |
|
| 20 |
// Model talks to any OpenAI-compatible chat completions API. |
| 21 |
type Model struct { |
| 22 |
baseURL string |
| 23 |
apiKey string |
| 24 |
model string |
| 25 |
systemPrompt string |
| 26 |
unattended bool |
| 27 |
client *http.Client |
| 28 |
} |
| 29 |
|
| 30 |
// Options configures OpenAI-compatible request behavior. |
| 31 |
type Options struct { |
| 32 |
Unattended bool |
| 33 |
} |
| 34 |
|
| 35 |
// NewModel sets up an OpenAI-compatible adapter. |
| 36 |
func NewModel(baseURL, apiKey, model, systemPrompt string) *Model { |
| 37 |
return NewModelWithOptions(baseURL, apiKey, model, systemPrompt, Options{}) |
| 38 |
} |
| 39 |
|
| 40 |
// NewModelWithOptions sets up an OpenAI-compatible adapter with request options. |
| 41 |
func NewModelWithOptions(baseURL, apiKey, model, systemPrompt string, opts Options) *Model { |
| 42 |
return &Model{ |
| 43 |
baseURL: baseURL, |
| 44 |
apiKey: apiKey, |
| 45 |
model: model, |
| 46 |
systemPrompt: systemPrompt, |
| 47 |
unattended: opts.Unattended, |
| 48 |
client: &http.Client{Timeout: 240 * time.Second}, |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
type request struct { |
| 53 |
Model string `json:"model"` |
| 54 |
Messages []clnkr.Message `json:"messages"` |
| 55 |
ResponseFormat responseFormat `json:"response_format"` |
| 56 |
} |
| 57 |
|
| 58 |
type textRequest struct { |
| 59 |
Model string `json:"model"` |
| 60 |
Messages []clnkr.Message `json:"messages"` |
| 61 |
} |
| 62 |
|
| 63 |
type responseFormat struct { |
| 64 |
Type string `json:"type"` |
| 65 |
JSONSchema responseJSONSchema `json:"json_schema"` |
| 66 |
} |
| 67 |
|
| 68 |
type responseJSONSchema struct { |
| 69 |
Name string `json:"name,omitempty"` |
| 70 |
Strict bool `json:"strict"` |
| 71 |
Schema map[string]any `json:"schema"` |
| 72 |
} |
| 73 |
|
| 74 |
type response struct { |
| 75 |
Choices []struct { |
| 76 |
Message struct { |
| 77 |
Role string `json:"role"` |
| 78 |
Content string `json:"content"` |
| 79 |
Refusal string `json:"refusal"` |
| 80 |
} `json:"message"` |
| 81 |
} `json:"choices"` |
| 82 |
Usage struct { |
| 83 |
PromptTokens int `json:"prompt_tokens"` |
| 84 |
CompletionTokens int `json:"completion_tokens"` |
| 85 |
} `json:"usage"` |
| 86 |
} |
| 87 |
|
| 88 |
const ( |
| 89 |
maxResponseBytes = 1 << 20 // 1MB |
| 90 |
maxAttempts = 5 |
| 91 |
baseRetryDelay = time.Second |
| 92 |
) |
| 93 |
|
| 94 |
// extractErrorMessage pulls the message from an API error response body. |
| 95 |
// Handles both {"error":{"message":"..."}} and [{...}] array-wrapped forms. |
| 96 |
// Falls back to the raw body if parsing fails. |
| 97 |
func extractErrorMessage(body []byte) string { |
| 98 |
type errorBody struct { |
| 99 |
Error struct { |
| 100 |
Code json.RawMessage `json:"code"` |
| 101 |
Message string `json:"message"` |
| 102 |
} `json:"error"` |
| 103 |
} |
| 104 |
|
| 105 |
var single errorBody |
| 106 |
if err := json.Unmarshal(body, &single); err == nil { |
| 107 |
if text := openaiwire.FormatErrorMessage( |
| 108 |
single.Error.Code, |
| 109 |
single.Error.Message, |
| 110 |
); text != "" { |
| 111 |
return text |
| 112 |
} |
| 113 |
} |
| 114 |
|
| 115 |
var arr []errorBody |
| 116 |
if err := json.Unmarshal(body, &arr); err == nil && len(arr) > 0 { |
| 117 |
if text := openaiwire.FormatErrorMessage( |
| 118 |
arr[0].Error.Code, |
| 119 |
arr[0].Error.Message, |
| 120 |
); text != "" { |
| 121 |
return text |
| 122 |
} |
| 123 |
} |
| 124 |
|
| 125 |
return string(body) |
| 126 |
} |
| 127 |
|
| 128 |
func apiError(statusCode int, message string) error { |
| 129 |
err := fmt.Errorf("api error (status %d): %s", statusCode, message) |
| 130 |
if isContextLengthError(statusCode, message) { |
| 131 |
return fmt.Errorf("%w: %w", clnkr.ErrContextLengthExceeded, err) |
| 132 |
} |
| 133 |
return err |
| 134 |
} |
| 135 |
|
| 136 |
func isContextLengthError(statusCode int, message string) bool { |
| 137 |
if statusCode != http.StatusBadRequest { |
| 138 |
return false |
| 139 |
} |
| 140 |
return openaiwire.IsContextLengthErrorText(message) |
| 141 |
} |
| 142 |
|
| 143 |
func (m *Model) Query(ctx context.Context, messages []clnkr.Message) (clnkr.Response, error) { |
| 144 |
messages = openaiwire.NormalizeMessagesForProvider(messages) |
| 145 |
schema := openaiwire.RequestSchema() |
| 146 |
if m.unattended { |
| 147 |
schema = openaiwire.UnattendedRequestSchema() |
| 148 |
} |
| 149 |
allMessages := make([]clnkr.Message, 0, len(messages)+1) |
| 150 |
allMessages = append(allMessages, clnkr.Message{Role: "system", Content: m.systemPrompt}) |
| 151 |
allMessages = append(allMessages, messages...) |
| 152 |
|
| 153 |
body, err := json.Marshal(request{ |
| 154 |
Model: m.model, |
| 155 |
Messages: allMessages, |
| 156 |
ResponseFormat: responseFormat{ |
| 157 |
Type: "json_schema", |
| 158 |
JSONSchema: responseJSONSchema{ |
| 159 |
Name: "agent_turn", |
| 160 |
Strict: true, |
| 161 |
Schema: schema, |
| 162 |
}, |
| 163 |
}, |
| 164 |
}) |
| 165 |
if err != nil { |
| 166 |
return clnkr.Response{}, fmt.Errorf("marshal request: %w", err) |
| 167 |
} |
| 168 |
|
| 169 |
for attempt := 1; attempt <= maxAttempts; attempt++ { |
| 170 |
respBody, statusCode, retryAfter, err := m.doRequest(ctx, body) |
| 171 |
if err != nil { |
| 172 |
return clnkr.Response{}, err |
| 173 |
} |
| 174 |
if statusCode == http.StatusOK { |
| 175 |
return parseResponse(respBody) |
| 176 |
} |
| 177 |
|
| 178 |
apiErr := apiError(statusCode, extractErrorMessage(respBody)) |
| 179 |
if !retryableStatus(statusCode) || attempt == maxAttempts { |
| 180 |
return clnkr.Response{}, apiErr |
| 181 |
} |
| 182 |
if err := waitForRetry(ctx, retryDelay(retryAfter, attempt)); err != nil { |
| 183 |
return clnkr.Response{}, fmt.Errorf("wait before retry: %w", err) |
| 184 |
} |
| 185 |
} |
| 186 |
|
| 187 |
return clnkr.Response{}, fmt.Errorf("retry loop exhausted") |
| 188 |
} |
| 189 |
|
| 190 |
func (m *Model) QueryText(ctx context.Context, messages []clnkr.Message) (string, error) { |
| 191 |
allMessages := make([]clnkr.Message, 0, len(messages)+1) |
| 192 |
allMessages = append(allMessages, clnkr.Message{Role: "system", Content: m.systemPrompt}) |
| 193 |
allMessages = append(allMessages, messages...) |
| 194 |
|
| 195 |
body, err := json.Marshal(textRequest{ |
| 196 |
Model: m.model, |
| 197 |
Messages: allMessages, |
| 198 |
}) |
| 199 |
if err != nil { |
| 200 |
return "", fmt.Errorf("marshal request: %w", err) |
| 201 |
} |
| 202 |
|
| 203 |
for attempt := 1; attempt <= maxAttempts; attempt++ { |
| 204 |
respBody, statusCode, retryAfter, err := m.doRequest(ctx, body) |
| 205 |
if err != nil { |
| 206 |
return "", err |
| 207 |
} |
| 208 |
if statusCode == http.StatusOK { |
| 209 |
return parseTextResponse(respBody) |
| 210 |
} |
| 211 |
|
| 212 |
apiErr := apiError(statusCode, extractErrorMessage(respBody)) |
| 213 |
if !retryableStatus(statusCode) || attempt == maxAttempts { |
| 214 |
return "", apiErr |
| 215 |
} |
| 216 |
if err := waitForRetry(ctx, retryDelay(retryAfter, attempt)); err != nil { |
| 217 |
return "", fmt.Errorf("wait before retry: %w", err) |
| 218 |
} |
| 219 |
} |
| 220 |
|
| 221 |
return "", fmt.Errorf("retry loop exhausted") |
| 222 |
} |
| 223 |
|
| 224 |
func (m *Model) doRequest(ctx context.Context, body []byte) ([]byte, int, string, error) { |
| 225 |
req, err := http.NewRequestWithContext( |
| 226 |
ctx, |
| 227 |
"POST", |
| 228 |
endpointURL(m.baseURL, "/chat/completions"), |
| 229 |
bytes.NewReader(body), |
| 230 |
) |
| 231 |
if err != nil { |
| 232 |
return nil, 0, "", fmt.Errorf("create request: %w", err) |
| 233 |
} |
| 234 |
req.Header.Set("Content-Type", "application/json") |
| 235 |
req.Header.Set("Authorization", "Bearer "+m.apiKey) |
| 236 |
|
| 237 |
resp, err := m.client.Do(req) |
| 238 |
if err != nil { |
| 239 |
return nil, 0, "", fmt.Errorf("send request: %w", err) |
| 240 |
} |
| 241 |
defer resp.Body.Close() //nolint:errcheck // best-effort cleanup |
| 242 |
|
| 243 |
respBody, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes)) |
| 244 |
if err != nil { |
| 245 |
return nil, 0, "", fmt.Errorf("read response: %w", err) |
| 246 |
} |
| 247 |
return respBody, resp.StatusCode, resp.Header.Get("Retry-After"), nil |
| 248 |
} |
| 249 |
|
| 250 |
func endpointURL(baseURL, endpoint string) string { |
| 251 |
parsed, err := url.Parse(baseURL) |
| 252 |
if err != nil || parsed.Scheme == "" || parsed.Host == "" || parsed.Opaque != "" { |
| 253 |
return joinURLBoundary(baseURL, endpoint) |
| 254 |
} |
| 255 |
|
| 256 |
escapedPath := strings.TrimRight( |
| 257 |
parsed.EscapedPath(), |
| 258 |
"/", |
| 259 |
) + "/" + strings.TrimLeft( |
| 260 |
endpoint, |
| 261 |
"/", |
| 262 |
) |
| 263 |
decodedPath, err := url.PathUnescape(escapedPath) |
| 264 |
if err != nil { |
| 265 |
return joinURLBoundary(baseURL, endpoint) |
| 266 |
} |
| 267 |
parsed.Path = decodedPath |
| 268 |
parsed.RawPath = "" |
| 269 |
if escapedPath != (&url.URL{Path: decodedPath}).EscapedPath() { |
| 270 |
parsed.RawPath = escapedPath |
| 271 |
} |
| 272 |
return parsed.String() |
| 273 |
} |
| 274 |
|
| 275 |
func joinURLBoundary(baseURL, endpoint string) string { |
| 276 |
return strings.TrimRight(baseURL, "/") + "/" + strings.TrimLeft(endpoint, "/") |
| 277 |
} |
| 278 |
|
| 279 |
func parseResponse(respBody []byte) (clnkr.Response, error) { |
| 280 |
var apiResp response |
| 281 |
if err := json.Unmarshal(respBody, &apiResp); err != nil { |
| 282 |
return clnkr.Response{}, fmt.Errorf("unmarshal response: %w", err) |
| 283 |
} |
| 284 |
if len(apiResp.Choices) == 0 { |
| 285 |
return clnkr.Response{}, fmt.Errorf("no choices in response") |
| 286 |
} |
| 287 |
|
| 288 |
choice := apiResp.Choices[0] |
| 289 |
if strings.TrimSpace(choice.Message.Refusal) != "" { |
| 290 |
return clnkr.Response{}, fmt.Errorf("structured output refusal: %s", choice.Message.Refusal) |
| 291 |
} |
| 292 |
if strings.TrimSpace(choice.Message.Content) == "" { |
| 293 |
return clnkr.Response{}, fmt.Errorf("empty choice content") |
| 294 |
} |
| 295 |
turn, err := openaiwire.ParseChatCompletionTurn(choice.Message.Content) |
| 296 |
if err != nil { |
| 297 |
return clnkr.Response{ |
| 298 |
Raw: choice.Message.Content, |
| 299 |
Usage: clnkr.Usage{ |
| 300 |
InputTokens: apiResp.Usage.PromptTokens, |
| 301 |
OutputTokens: apiResp.Usage.CompletionTokens, |
| 302 |
}, |
| 303 |
ProtocolErr: err, |
| 304 |
}, nil |
| 305 |
} |
| 306 |
if _, err := clnkr.CanonicalTurnJSON(turn); err != nil { |
| 307 |
return clnkr.Response{}, fmt.Errorf("canonicalize structured output payload: %w", err) |
| 308 |
} |
| 309 |
return clnkr.Response{ |
| 310 |
Turn: turn, |
| 311 |
Raw: choice.Message.Content, |
| 312 |
Usage: clnkr.Usage{ |
| 313 |
InputTokens: apiResp.Usage.PromptTokens, |
| 314 |
OutputTokens: apiResp.Usage.CompletionTokens, |
| 315 |
}, |
| 316 |
}, nil |
| 317 |
} |
| 318 |
|
| 319 |
func parseTextResponse(respBody []byte) (string, error) { |
| 320 |
var apiResp response |
| 321 |
if err := json.Unmarshal(respBody, &apiResp); err != nil { |
| 322 |
return "", fmt.Errorf("unmarshal response: %w", err) |
| 323 |
} |
| 324 |
if len(apiResp.Choices) == 0 { |
| 325 |
return "", fmt.Errorf("no choices in response") |
| 326 |
} |
| 327 |
|
| 328 |
choice := apiResp.Choices[0] |
| 329 |
if strings.TrimSpace(choice.Message.Refusal) != "" { |
| 330 |
return "", fmt.Errorf("free-form refusal: %s", choice.Message.Refusal) |
| 331 |
} |
| 332 |
if strings.TrimSpace(choice.Message.Content) == "" { |
| 333 |
return "", fmt.Errorf("empty choice content") |
| 334 |
} |
| 335 |
return choice.Message.Content, nil |
| 336 |
} |
| 337 |
|
| 338 |
func retryableStatus(statusCode int) bool { |
| 339 |
switch statusCode { |
| 340 |
case http.StatusTooManyRequests, |
| 341 |
http.StatusBadGateway, |
| 342 |
http.StatusServiceUnavailable, |
| 343 |
http.StatusGatewayTimeout: |
| 344 |
return true |
| 345 |
default: |
| 346 |
return statusCode >= 500 && statusCode < 600 |
| 347 |
} |
| 348 |
} |
| 349 |
|
| 350 |
func retryDelay(retryAfter string, attempt int) time.Duration { |
| 351 |
if delay, ok := parseRetryAfter(retryAfter); ok { |
| 352 |
return delay |
| 353 |
} |
| 354 |
|
| 355 |
delay := baseRetryDelay |
| 356 |
if attempt > 1 { |
| 357 |
delay <<= (attempt - 1) |
| 358 |
} |
| 359 |
maxJitter := delay / 4 |
| 360 |
if maxJitter == 0 { |
| 361 |
return delay |
| 362 |
} |
| 363 |
jitter := time.Duration(rand.Int64N(int64(maxJitter)*2+1)) - maxJitter |
| 364 |
return delay + jitter |
| 365 |
} |
| 366 |
|
| 367 |
func parseRetryAfter(value string) (time.Duration, bool) { |
| 368 |
value = strings.TrimSpace(value) |
| 369 |
if value == "" { |
| 370 |
return 0, false |
| 371 |
} |
| 372 |
if seconds, err := strconv.Atoi(value); err == nil { |
| 373 |
if seconds <= 0 { |
| 374 |
return 0, true |
| 375 |
} |
| 376 |
return time.Duration(seconds) * time.Second, true |
| 377 |
} |
| 378 |
if t, err := http.ParseTime(value); err == nil { |
| 379 |
if !t.After(time.Now()) { |
| 380 |
return 0, true |
| 381 |
} |
| 382 |
return time.Until(t), true |
| 383 |
} |
| 384 |
return 0, false |
| 385 |
} |
| 386 |
|
| 387 |
func waitForRetry(ctx context.Context, delay time.Duration) error { |
| 388 |
if delay <= 0 { |
| 389 |
select { |
| 390 |
case <-ctx.Done(): |
| 391 |
return ctx.Err() |
| 392 |
default: |
| 393 |
return nil |
| 394 |
} |
| 395 |
} |
| 396 |
|
| 397 |
timer := time.NewTimer(delay) |
| 398 |
defer timer.Stop() |
| 399 |
|
| 400 |
select { |
| 401 |
case <-ctx.Done(): |
| 402 |
return ctx.Err() |
| 403 |
case <-timer.C: |
| 404 |
return nil |
| 405 |
} |
| 406 |
} |