Debian Codegraph @

internal/providers/openairesponses/openairesponses.go

raw
1 package openairesponses
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 the OpenAI Responses API.
21 type Model struct {
22 baseURL string
23 apiKey string
24 model string
25 systemPrompt string
26 reasoningEffort string
27 maxOutputTokens int
28 hasMaxOutputTokens bool
29 useBashToolCalls bool
30 unattended bool
31 client *http.Client
32 }
33
34 type Options struct {
35 ReasoningEffort string
36 MaxOutputTokens int
37 HasMaxOutputTokens bool
38 UseBashToolCalls bool
39 Unattended bool
40 }
41
42 // NewModel sets up an OpenAI Responses adapter.
43 func NewModel(baseURL, apiKey, model, systemPrompt string) *Model {
44 return NewModelWithOptions(baseURL, apiKey, model, systemPrompt, Options{})
45 }
46
47 // NewModelWithOptions sets up an OpenAI Responses adapter with request options.
48 func NewModelWithOptions(baseURL, apiKey, model, systemPrompt string, opts Options) *Model {
49 return &Model{
50 baseURL: baseURL,
51 apiKey: apiKey,
52 model: model,
53 systemPrompt: systemPrompt,
54 reasoningEffort: opts.ReasoningEffort,
55 maxOutputTokens: opts.MaxOutputTokens,
56 hasMaxOutputTokens: opts.HasMaxOutputTokens,
57 useBashToolCalls: opts.UseBashToolCalls,
58 unattended: opts.Unattended,
59 client: &http.Client{Timeout: 240 * time.Second},
60 }
61 }
62
63 type request struct {
64 Model string `json:"model"`
65 Instructions string `json:"instructions,omitempty"`
66 Input []responsesInputItem `json:"input"`
67 Include []string `json:"include,omitempty"`
68 Text *textOptions `json:"text,omitempty"`
69 Reasoning *reasoningOptions `json:"reasoning,omitempty"`
70 MaxOutputTokens *int `json:"max_output_tokens,omitempty"`
71 Tools []openAITool `json:"tools,omitempty"`
72 ParallelTools *bool `json:"parallel_tool_calls,omitempty"`
73 }
74
75 type textOptions struct {
76 Format *responseFormat `json:"format,omitempty"`
77 }
78
79 type reasoningOptions struct {
80 Effort string `json:"effort"`
81 }
82
83 type responseFormat struct {
84 Type string `json:"type"`
85 Name string `json:"name"`
86 Strict bool `json:"strict"`
87 Schema map[string]any `json:"schema"`
88 }
89
90 type openAITool struct {
91 Type string `json:"type"`
92 Name string `json:"name"`
93 Description string `json:"description,omitempty"`
94 Strict bool `json:"strict"`
95 Parameters map[string]any `json:"parameters"`
96 }
97
98 type responsesInputItem struct {
99 Raw json.RawMessage `json:"-"`
100 Type string `json:"type,omitempty"`
101 ID string `json:"id,omitempty"`
102 CallID string `json:"call_id,omitempty"`
103 Name string `json:"name,omitempty"`
104 Arguments string `json:"arguments,omitempty"`
105 Output string `json:"output,omitempty"`
106 Role string `json:"role,omitempty"`
107 Status string `json:"status,omitempty"`
108 Content []responsesContentItem `json:"content,omitempty"`
109 }
110
111 func (i responsesInputItem) MarshalJSON() ([]byte, error) {
112 if len(i.Raw) > 0 {
113 return i.Raw, nil
114 }
115 type alias responsesInputItem
116 return json.Marshal(alias(i))
117 }
118
119 type responsesContentItem struct {
120 Type string `json:"type"`
121 Text string `json:"text"`
122 Annotations *[]any `json:"annotations,omitempty"`
123 }
124
125 type response struct {
126 Status string `json:"status"`
127 Error *responseError `json:"error"`
128 Output []outputItem `json:"output"`
129 RawOutput []json.RawMessage `json:"-"`
130 Usage struct {
131 InputTokens int `json:"input_tokens"`
132 OutputTokens int `json:"output_tokens"`
133 } `json:"usage"`
134 }
135
136 type responseError struct {
137 Code json.RawMessage `json:"code"`
138 Message string `json:"message"`
139 }
140
141 type outputItem struct {
142 Type string `json:"type"`
143 ID string `json:"id"`
144 CallID string `json:"call_id"`
145 Name string `json:"name"`
146 Arguments string `json:"arguments"`
147 Status string `json:"status"`
148 Role string `json:"role"`
149 Content []responseItem `json:"content"`
150 }
151
152 type responseItem struct {
153 Type string `json:"type"`
154 Text string `json:"text"`
155 Refusal string `json:"refusal"`
156 }
157
158 const (
159 maxResponseBytes = 1 << 20 // 1MB
160 maxAttempts = 5
161 baseRetryDelay = time.Second
162 replayProvider = "openai"
163 replayProviderAPI = "openai-responses"
164 includeReasoning = "reasoning.encrypted_content"
165 )
166
167 func (m *Model) Query(ctx context.Context, messages []clnkr.Message) (clnkr.Response, error) {
168 schema := openaiwire.RequestSchema()
169 if m.unattended {
170 schema = openaiwire.UnattendedRequestSchema()
171 }
172 input := mapMessages(messages)
173 var tools []openAITool
174 var parallelTools *bool
175 if m.useBashToolCalls {
176 schema = openaiwire.FinalTurnSchema()
177 if m.unattended {
178 schema = openaiwire.DoneOnlySchema()
179 }
180 input = mapToolCallMessages(messages)
181 tools = []openAITool{bashToolSchema()}
182 }
183 return m.queryStructured(ctx, input, schema, tools, parallelTools)
184 }
185
186 func (m *Model) QueryFinal(ctx context.Context, messages []clnkr.Message) (clnkr.Response, error) {
187 return m.queryStructured(ctx, mapMessages(messages), openaiwire.DoneOnlySchema(), nil, nil)
188 }
189
190 func (m *Model) queryStructured(
191 ctx context.Context,
192 input []responsesInputItem,
193 schema map[string]any,
194 tools []openAITool,
195 parallelTools *bool,
196 ) (clnkr.Response, error) {
197 body, err := json.Marshal(request{
198 Model: m.model,
199 Instructions: m.systemPrompt,
200 Input: input,
201 Include: includeOptions(tools),
202 Reasoning: m.reasoningOptions(),
203 MaxOutputTokens: m.maxOutputTokensValue(),
204 Tools: tools,
205 ParallelTools: parallelTools,
206 Text: &textOptions{
207 Format: &responseFormat{
208 Type: "json_schema",
209 Name: "agent_turn",
210 Strict: true,
211 Schema: schema,
212 },
213 },
214 })
215 if err != nil {
216 return clnkr.Response{}, fmt.Errorf("marshal request: %w", err)
217 }
218
219 for attempt := 1; attempt <= maxAttempts; attempt++ {
220 respBody, statusCode, retryAfter, err := m.doRequest(ctx, body)
221 if err != nil {
222 return clnkr.Response{}, err
223 }
224 if statusCode == http.StatusOK {
225 if m.useBashToolCalls && len(tools) > 0 {
226 return parseToolCallResponse(respBody)
227 }
228 return parseStructuredResponse(respBody)
229 }
230
231 apiErr := apiError(statusCode, extractErrorMessage(respBody))
232 if !retryableStatus(statusCode) || attempt == maxAttempts {
233 return clnkr.Response{}, apiErr
234 }
235 if err := waitForRetry(ctx, retryDelay(retryAfter, attempt)); err != nil {
236 return clnkr.Response{}, fmt.Errorf("wait before retry: %w", err)
237 }
238 }
239
240 return clnkr.Response{}, fmt.Errorf("retry loop exhausted")
241 }
242
243 func (m *Model) QueryText(ctx context.Context, messages []clnkr.Message) (string, error) {
244 body, err := json.Marshal(request{
245 Model: m.model,
246 Instructions: m.systemPrompt,
247 Input: mapMessages(messages),
248 Reasoning: m.reasoningOptions(),
249 MaxOutputTokens: m.maxOutputTokensValue(),
250 })
251 if err != nil {
252 return "", fmt.Errorf("marshal request: %w", err)
253 }
254
255 for attempt := 1; attempt <= maxAttempts; attempt++ {
256 respBody, statusCode, retryAfter, err := m.doRequest(ctx, body)
257 if err != nil {
258 return "", err
259 }
260 if statusCode == http.StatusOK {
261 return parseTextResponse(respBody)
262 }
263
264 apiErr := apiError(statusCode, extractErrorMessage(respBody))
265 if !retryableStatus(statusCode) || attempt == maxAttempts {
266 return "", apiErr
267 }
268 if err := waitForRetry(ctx, retryDelay(retryAfter, attempt)); err != nil {
269 return "", fmt.Errorf("wait before retry: %w", err)
270 }
271 }
272
273 return "", fmt.Errorf("retry loop exhausted")
274 }
275
276 func (m *Model) reasoningOptions() *reasoningOptions {
277 if m.reasoningEffort == "" {
278 return nil
279 }
280 return &reasoningOptions{Effort: m.reasoningEffort}
281 }
282
283 func (m *Model) maxOutputTokensValue() *int {
284 if !m.hasMaxOutputTokens {
285 return nil
286 }
287 return &m.maxOutputTokens
288 }
289
290 func mapMessages(messages []clnkr.Message) []responsesInputItem {
291 normalized := openaiwire.NormalizeMessagesForProvider(messages)
292 input := make([]responsesInputItem, 0, len(normalized))
293 assistantIndex := 0
294 for _, msg := range normalized {
295 if msg.Role == "assistant" {
296 assistantIndex++
297 annotations := []any{}
298 input = append(input, responsesInputItem{
299 Type: "message",
300 ID: fmt.Sprintf("msg_prev_%d", assistantIndex),
301 Role: "assistant",
302 Status: "completed",
303 Content: []responsesContentItem{{
304 Type: "output_text",
305 Text: msg.Content,
306 Annotations: &annotations,
307 }},
308 })
309 continue
310 }
311
312 input = append(input, responsesInputItem{
313 Type: "message",
314 Role: msg.Role,
315 Content: []responsesContentItem{{
316 Type: "input_text",
317 Text: msg.Content,
318 }},
319 })
320 }
321 return input
322 }
323
324 func mapToolCallMessages(messages []clnkr.Message) []responsesInputItem {
325 normalized := openaiwire.NormalizeMessagesForProvider(messages)
326 input := make([]responsesInputItem, 0, len(normalized))
327 knownCalls := make(map[string]struct{})
328 assistantIndex := 0
329 for _, msg := range normalized {
330 if msg.Role == "assistant" && len(msg.BashToolCalls) > 0 {
331 for _, item := range msg.ProviderReplay {
332 input = appendProviderReplayInput(input, item)
333 }
334 for _, call := range msg.BashToolCalls {
335 knownCalls[call.ID] = struct{}{}
336 input = append(input, functionCallInput(call))
337 }
338 continue
339 }
340 if msg.BashToolResult != nil {
341 if _, ok := knownCalls[msg.BashToolResult.ID]; ok {
342 input = append(input, responsesInputItem{
343 Type: "function_call_output",
344 CallID: msg.BashToolResult.ID,
345 Output: msg.BashToolResult.Content,
346 })
347 continue
348 }
349 }
350 if msg.Role == "assistant" {
351 assistantIndex++
352 annotations := []any{}
353 input = append(input, responsesInputItem{
354 Type: "message",
355 ID: fmt.Sprintf("msg_prev_%d", assistantIndex),
356 Role: "assistant",
357 Status: "completed",
358 Content: []responsesContentItem{{
359 Type: "output_text",
360 Text: msg.Content,
361 Annotations: &annotations,
362 }},
363 })
364 continue
365 }
366 input = append(input, responsesInputItem{
367 Type: "message",
368 Role: msg.Role,
369 Content: []responsesContentItem{{
370 Type: "input_text",
371 Text: msg.Content,
372 }},
373 })
374 }
375 return input
376 }
377
378 func includeOptions(tools []openAITool) []string {
379 if len(tools) == 0 {
380 return nil
381 }
382 return []string{includeReasoning}
383 }
384
385 func appendProviderReplayInput(
386 input []responsesInputItem,
387 item clnkr.ProviderReplayItem,
388 ) []responsesInputItem {
389 if item.Provider != replayProvider || item.ProviderAPI != replayProviderAPI ||
390 len(item.JSON) == 0 {
391 return input
392 }
393 if item.Type == "reasoning" && !hasEncryptedReasoning(item.JSON) {
394 return input
395 }
396 return append(input, responsesInputItem{Raw: append(json.RawMessage(nil), item.JSON...)})
397 }
398
399 func hasEncryptedReasoning(raw json.RawMessage) bool {
400 var item struct {
401 EncryptedContent string `json:"encrypted_content"`
402 }
403 if err := json.Unmarshal(raw, &item); err != nil {
404 return false
405 }
406 return strings.TrimSpace(item.EncryptedContent) != ""
407 }
408
409 func functionCallInput(call clnkr.BashToolCall) responsesInputItem {
410 args := struct {
411 Command string `json:"command"`
412 Workdir *string `json:"workdir"`
413 }{Command: call.Command}
414 if call.Workdir != "" {
415 args.Workdir = &call.Workdir
416 }
417 body, err := json.Marshal(args)
418 if err != nil {
419 body = []byte(`{"command":"","workdir":null}`)
420 }
421 return responsesInputItem{
422 Type: "function_call",
423 CallID: call.ID,
424 Name: "bash",
425 Arguments: string(body),
426 Status: "completed",
427 }
428 }
429
430 func bashToolSchema() openAITool {
431 return openAITool{
432 Type: "function",
433 Name: "bash",
434 Description: "Run one bash command in the current clnkr shell session.",
435 Strict: true,
436 Parameters: map[string]any{
437 "type": "object",
438 "additionalProperties": false,
439 "properties": map[string]any{
440 "command": map[string]any{"type": "string"},
441 "workdir": map[string]any{
442 "anyOf": []any{
443 map[string]any{"type": "string"},
444 map[string]any{"type": "null"},
445 },
446 },
447 },
448 "required": []string{"command", "workdir"},
449 },
450 }
451 }
452
453 func (m *Model) doRequest(ctx context.Context, body []byte) ([]byte, int, string, error) {
454 req, err := http.NewRequestWithContext(
455 ctx,
456 "POST",
457 endpointURL(m.baseURL, "/responses"),
458 bytes.NewReader(body),
459 )
460 if err != nil {
461 return nil, 0, "", fmt.Errorf("create request: %w", err)
462 }
463 req.Header.Set("Content-Type", "application/json")
464 req.Header.Set("Authorization", "Bearer "+m.apiKey)
465
466 resp, err := m.client.Do(req)
467 if err != nil {
468 return nil, 0, "", fmt.Errorf("send request: %w", err)
469 }
470 defer resp.Body.Close() //nolint:errcheck
471
472 respBody, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes))
473 if err != nil {
474 return nil, 0, "", fmt.Errorf("read response: %w", err)
475 }
476 return respBody, resp.StatusCode, resp.Header.Get("Retry-After"), nil
477 }
478
479 func endpointURL(baseURL, endpoint string) string {
480 parsed, err := url.Parse(baseURL)
481 if err != nil || parsed.Scheme == "" || parsed.Host == "" || parsed.Opaque != "" {
482 return joinURLBoundary(baseURL, endpoint)
483 }
484
485 escapedPath := strings.TrimRight(
486 parsed.EscapedPath(),
487 "/",
488 ) + "/" + strings.TrimLeft(
489 endpoint,
490 "/",
491 )
492 decodedPath, err := url.PathUnescape(escapedPath)
493 if err != nil {
494 return joinURLBoundary(baseURL, endpoint)
495 }
496 parsed.Path = decodedPath
497 parsed.RawPath = ""
498 if escapedPath != (&url.URL{Path: decodedPath}).EscapedPath() {
499 parsed.RawPath = escapedPath
500 }
501 return parsed.String()
502 }
503
504 func joinURLBoundary(baseURL, endpoint string) string {
505 return strings.TrimRight(baseURL, "/") + "/" + strings.TrimLeft(endpoint, "/")
506 }
507
508 func parseStructuredResponse(respBody []byte) (clnkr.Response, error) {
509 text, usage, err := extractOutputText(respBody, "structured output")
510 if err != nil {
511 return clnkr.Response{}, err
512 }
513
514 turn, err := openaiwire.ParseProviderTurn(text)
515 if err != nil {
516 return clnkr.Response{
517 Raw: text,
518 Usage: usage,
519 ProtocolErr: err,
520 }, nil
521 }
522 if _, err := clnkr.CanonicalTurnJSON(turn); err != nil {
523 return clnkr.Response{}, fmt.Errorf("canonicalize structured output payload: %w", err)
524 }
525 return clnkr.Response{
526 Turn: turn,
527 Raw: text,
528 Usage: usage,
529 }, nil
530 }
531
532 func unmarshalResponse(respBody []byte) (response, error) {
533 var raw struct {
534 Status string `json:"status"`
535 Error *responseError `json:"error"`
536 Output []json.RawMessage `json:"output"`
537 Usage struct {
538 InputTokens int `json:"input_tokens"`
539 OutputTokens int `json:"output_tokens"`
540 } `json:"usage"`
541 }
542 if err := json.Unmarshal(respBody, &raw); err != nil {
543 return response{}, fmt.Errorf("unmarshal response: %w", err)
544 }
545 apiResp := response{Status: raw.Status, Error: raw.Error, RawOutput: raw.Output}
546 apiResp.Usage = raw.Usage
547 apiResp.Output = make([]outputItem, len(raw.Output))
548 for i, item := range raw.Output {
549 if err := json.Unmarshal(item, &apiResp.Output[i]); err != nil {
550 return response{}, fmt.Errorf("unmarshal response output item %d: %w", i, err)
551 }
552 }
553 return apiResp, nil
554 }
555
556 func parseTextResponse(respBody []byte) (string, error) {
557 text, _, err := extractOutputText(respBody, "free-form")
558 if err != nil {
559 return "", err
560 }
561 return text, nil
562 }
563
564 func extractOutputText(respBody []byte, mode string) (string, clnkr.Usage, error) {
565 var apiResp response
566 if err := json.Unmarshal(respBody, &apiResp); err != nil {
567 return "", clnkr.Usage{}, fmt.Errorf("unmarshal response: %w", err)
568 }
569 if err := failedResponseError(apiResp); err != nil {
570 return "", clnkr.Usage{}, err
571 }
572
573 var b strings.Builder
574 for _, item := range apiResp.Output {
575 if item.Type != "message" || item.Role != "assistant" {
576 continue
577 }
578 for _, content := range item.Content {
579 switch content.Type {
580 case "output_text":
581 b.WriteString(content.Text)
582 case "refusal":
583 if strings.TrimSpace(content.Refusal) != "" {
584 return "", clnkr.Usage{}, fmt.Errorf("%s refusal: %s", mode, content.Refusal)
585 }
586 }
587 }
588 }
589
590 text := b.String()
591 if strings.TrimSpace(text) == "" {
592 return "", clnkr.Usage{}, fmt.Errorf("no usable output_text in response")
593 }
594 return text, clnkr.Usage{
595 InputTokens: apiResp.Usage.InputTokens,
596 OutputTokens: apiResp.Usage.OutputTokens,
597 }, nil
598 }
599
600 // extractErrorMessage pulls the message from an API error response body.
601 func extractErrorMessage(body []byte) string {
602 type errorBody struct {
603 Error responseError `json:"error"`
604 }
605
606 var single errorBody
607 if err := json.Unmarshal(body, &single); err == nil {
608 if text := openaiwire.FormatErrorMessage(
609 single.Error.Code,
610 single.Error.Message,
611 ); text != "" {
612 return text
613 }
614 }
615
616 var arr []errorBody
617 if err := json.Unmarshal(body, &arr); err == nil && len(arr) > 0 {
618 if text := openaiwire.FormatErrorMessage(
619 arr[0].Error.Code,
620 arr[0].Error.Message,
621 ); text != "" {
622 return text
623 }
624 }
625
626 return string(body)
627 }
628
629 func failedResponseError(apiResp response) error {
630 if apiResp.Status != "failed" || apiResp.Error == nil {
631 return nil
632 }
633 message := openaiwire.FormatErrorMessage(apiResp.Error.Code, apiResp.Error.Message)
634 if message == "" {
635 message = "response failed"
636 }
637 err := fmt.Errorf("response failed: %s", message)
638 if openaiwire.IsContextLengthErrorText(message) {
639 return fmt.Errorf("%w: %w", clnkr.ErrContextLengthExceeded, err)
640 }
641 return err
642 }
643
644 func apiError(statusCode int, message string) error {
645 err := fmt.Errorf("api error (status %d): %s", statusCode, message)
646 if isContextLengthError(statusCode, message) {
647 return fmt.Errorf("%w: %w", clnkr.ErrContextLengthExceeded, err)
648 }
649 return err
650 }
651
652 func isContextLengthError(statusCode int, message string) bool {
653 if statusCode != http.StatusBadRequest {
654 return false
655 }
656 return openaiwire.IsContextLengthErrorText(message)
657 }
658
659 func retryableStatus(statusCode int) bool {
660 switch statusCode {
661 case http.StatusTooManyRequests,
662 http.StatusBadGateway,
663 http.StatusServiceUnavailable,
664 http.StatusGatewayTimeout:
665 return true
666 default:
667 return statusCode >= 500 && statusCode < 600
668 }
669 }
670
671 func retryDelay(retryAfter string, attempt int) time.Duration {
672 if delay, ok := parseRetryAfter(retryAfter); ok {
673 return delay
674 }
675
676 delay := baseRetryDelay
677 if attempt > 1 {
678 delay <<= (attempt - 1)
679 }
680 maxJitter := delay / 4
681 if maxJitter == 0 {
682 return delay
683 }
684 jitter := time.Duration(rand.Int64N(int64(maxJitter)*2+1)) - maxJitter
685 return delay + jitter
686 }
687
688 func parseRetryAfter(value string) (time.Duration, bool) {
689 value = strings.TrimSpace(value)
690 if value == "" {
691 return 0, false
692 }
693 if seconds, err := strconv.Atoi(value); err == nil {
694 if seconds <= 0 {
695 return 0, true
696 }
697 return time.Duration(seconds) * time.Second, true
698 }
699 if t, err := http.ParseTime(value); err == nil {
700 if !t.After(time.Now()) {
701 return 0, true
702 }
703 return time.Until(t), true
704 }
705 return 0, false
706 }
707
708 func waitForRetry(ctx context.Context, delay time.Duration) error {
709 if delay <= 0 {
710 select {
711 case <-ctx.Done():
712 return ctx.Err()
713 default:
714 return nil
715 }
716 }
717
718 timer := time.NewTimer(delay)
719 defer timer.Stop()
720
721 select {
722 case <-ctx.Done():
723 return ctx.Err()
724 case <-timer.C:
725 return nil
726 }
727 }