Debian Codegraph @

internal/providers/openai/openai_test.go

raw
1 package openai_test
2
3 import (
4 "context"
5 "encoding/json"
6 "errors"
7 "io"
8 "net/http"
9 "net/http/httptest"
10 "strings"
11 "testing"
12
13 "github.com/clnkr-ai/clnkr"
14 "github.com/clnkr-ai/clnkr/internal/providers/openai"
15 )
16
17 func TestModelUsesStructuredOutputRequestBody(t *testing.T) {
18 var gotBody map[string]any
19 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
20 gotBody = readRequestBody(t, r)
21 writeChatResponse(t, w, openAIWrappedDone("ok"), 10, 20)
22 }))
23 defer server.Close()
24
25 m := openai.NewModel(server.URL, "test-key", "gpt-test", "sys prompt")
26 _, err := m.Query(context.Background(), []clnkr.Message{{Role: "user", Content: "hello"}})
27 if err != nil {
28 t.Fatalf("unexpected error: %v", err)
29 }
30
31 msgs := gotBody["messages"].([]any)
32 first := msgs[0].(map[string]any)
33 if first["role"] != "system" || first["content"] != "sys prompt" {
34 t.Errorf("first message should be system prompt, got %v", first)
35 }
36 responseFormat, ok := gotBody["response_format"].(map[string]any)
37 if !ok {
38 t.Fatalf("response_format = %T, want map[string]any", gotBody["response_format"])
39 }
40 if responseFormat["type"] != "json_schema" {
41 t.Fatalf("response_format.type = %v, want json_schema", responseFormat["type"])
42 }
43 jsonSchema, ok := responseFormat["json_schema"].(map[string]any)
44 if !ok {
45 t.Fatalf(
46 "response_format.json_schema = %T, want map[string]any",
47 responseFormat["json_schema"],
48 )
49 }
50 if jsonSchema["strict"] != true {
51 t.Fatalf("response_format.json_schema.strict = %v, want true", jsonSchema["strict"])
52 }
53 schema, ok := jsonSchema["schema"].(map[string]any)
54 if !ok {
55 t.Fatalf(
56 "response_format.json_schema.schema = %T, want map[string]any",
57 jsonSchema["schema"],
58 )
59 }
60 if schemaContainsKey(schema, "maxItems") {
61 t.Fatal("response_format.json_schema.schema unexpectedly includes maxItems")
62 }
63 if !schemaContainsKey(schema, "minItems") {
64 t.Fatal("response_format.json_schema.schema unexpectedly omits minItems")
65 }
66 }
67
68 func TestModelQueryTextReturnsPlainTextWithoutResponseFormat(t *testing.T) {
69 var gotBody map[string]any
70 history := []clnkr.Message{
71 {Role: "user", Content: "first task"},
72 {Role: "assistant", Content: doneTurn("canonical transcript")},
73 }
74 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
75 gotBody = readRequestBody(t, r)
76 writeChatResponse(t, w, "Older work summarized.", 10, 20)
77 }))
78 defer server.Close()
79
80 m := openai.NewModel(server.URL, "test-key", "gpt-test", "sys prompt")
81 summary, err := m.QueryText(context.Background(), history)
82 if err != nil {
83 t.Fatalf("unexpected error: %v", err)
84 }
85 if summary != "Older work summarized." {
86 t.Fatalf("summary = %q, want %q", summary, "Older work summarized.")
87 }
88 if _, ok := gotBody["response_format"]; ok {
89 t.Fatalf(
90 "response_format should be omitted for QueryText, got %#v",
91 gotBody["response_format"],
92 )
93 }
94 msgs, ok := gotBody["messages"].([]any)
95 if !ok || len(msgs) != len(history)+1 {
96 t.Fatalf(
97 "messages = %#v, want system plus %d transcript messages",
98 gotBody["messages"],
99 len(history),
100 )
101 }
102 last, ok := msgs[len(msgs)-1].(map[string]any)
103 if !ok {
104 t.Fatalf("last message = %#v, want map", msgs[len(msgs)-1])
105 }
106 if got, want := last["content"], doneTurn("canonical transcript"); got != want {
107 t.Fatalf("last assistant content = %#v, want %q", got, want)
108 }
109 }
110
111 func TestModelQueryTextRetriesTransientServerError(t *testing.T) {
112 attempts := 0
113 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
114 attempts++
115 if attempts == 1 {
116 writeAPIError(t, w, http.StatusBadGateway, "context deadline exceeded")
117 return
118 }
119 writeChatResponse(t, w, "ok after retry", 2, 3)
120 }))
121 defer server.Close()
122
123 m := openai.NewModel(server.URL, "test-key", "gpt-test", "sys")
124 summary, err := m.QueryText(
125 context.Background(),
126 []clnkr.Message{{Role: "user", Content: "hi"}},
127 )
128 if err != nil {
129 t.Fatalf("unexpected error: %v", err)
130 }
131 if attempts != 2 {
132 t.Fatalf("attempt count = %d, want 2", attempts)
133 }
134 if summary != "ok after retry" {
135 t.Fatalf("summary = %q, want ok after retry", summary)
136 }
137 }
138
139 func TestModelReturnsCanonicalJSONText(t *testing.T) {
140 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
141 writeChatResponse(t, w, openAIWrappedDone("hello back"), 15, 25)
142 }))
143 defer server.Close()
144
145 m := openai.NewModel(server.URL, "test-key", "gpt-test", "sys")
146 resp, err := m.Query(context.Background(), []clnkr.Message{{Role: "user", Content: "hi"}})
147 if err != nil {
148 t.Fatalf("unexpected error: %v", err)
149 }
150 if got, want := mustCanonicalTurn(t, resp.Turn), doneTurn("hello back"); got != want {
151 t.Errorf("got %q, want %q", got, want)
152 }
153 if resp.ProtocolErr != nil {
154 t.Fatalf("got protocol error %v, want nil", resp.ProtocolErr)
155 }
156 if resp.Usage.InputTokens != 15 || resp.Usage.OutputTokens != 25 {
157 t.Errorf("got usage %+v, want 15/25", resp.Usage)
158 }
159 }
160
161 func TestModelNormalizesAssistantHistoryToWrappedProviderJSON(t *testing.T) {
162 var gotBody map[string]any
163 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
164 gotBody = readRequestBody(t, r)
165 writeChatResponse(t, w, openAIWrappedDone("ok"), 1, 1)
166 }))
167 defer server.Close()
168
169 m := openai.NewModel(server.URL, "test-key", "gpt-test", "sys")
170 _, err := m.Query(context.Background(), []clnkr.Message{
171 {Role: "user", Content: "hi"},
172 {Role: "assistant", Content: doneTurn("hello back")},
173 })
174 if err != nil {
175 t.Fatalf("unexpected error: %v", err)
176 }
177
178 msgs := gotBody["messages"].([]any)
179 last := msgs[len(msgs)-1].(map[string]any)
180 if got, want := last["content"], openAIWrappedDone("hello back"); got != want {
181 t.Fatalf("assistant history content = %q, want %q", got, want)
182 }
183 }
184
185 func TestModelPostsToJoinedChatCompletionsEndpoint(t *testing.T) {
186 tests := []struct {
187 name string
188 base string
189 wantPath string
190 }{
191 {
192 name: "nested base URL",
193 base: "/v1beta/openai",
194 wantPath: "/v1beta/openai/chat/completions",
195 },
196 {name: "trailing slash base URL", base: "/v1/", wantPath: "/v1/chat/completions"},
197 }
198
199 for _, tt := range tests {
200 t.Run(tt.name, func(t *testing.T) {
201 var gotPath string
202 server := httptest.NewServer(
203 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
204 gotPath = r.URL.Path
205 writeChatResponse(t, w, openAIWrappedDone("ok"), 1, 1)
206 }),
207 )
208 defer server.Close()
209
210 m := openai.NewModel(server.URL+tt.base, "test-key", "gpt-test", "sys")
211 _, err := m.Query(context.Background(), []clnkr.Message{{Role: "user", Content: "hi"}})
212 if err != nil {
213 t.Fatalf("unexpected error: %v", err)
214 }
215 if gotPath != tt.wantPath {
216 t.Errorf("got path %q, want %q", gotPath, tt.wantPath)
217 }
218 })
219 }
220 }
221
222 func TestModelExtractsAPIErrorMessages(t *testing.T) {
223 tests := []struct {
224 name string
225 body string
226 want string
227 }{
228 {
229 name: "JSON error response",
230 body: `{"error":{"code":429,"message":"Rate limit exceeded"}}`,
231 want: "api error (status 429): Rate limit exceeded",
232 },
233 {
234 name: "array-wrapped response",
235 body: `[{"error":{"code":429,"message":"Quota exceeded"}}]`,
236 want: "api error (status 429): Quota exceeded",
237 },
238 }
239
240 for _, tt := range tests {
241 t.Run(tt.name, func(t *testing.T) {
242 server := httptest.NewServer(
243 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
244 w.Header().Set("Retry-After", "0")
245 w.WriteHeader(http.StatusTooManyRequests)
246 _, _ = w.Write([]byte(tt.body))
247 }),
248 )
249 defer server.Close()
250
251 m := openai.NewModel(server.URL, "test-key", "gpt-test", "sys")
252 _, err := m.Query(context.Background(), []clnkr.Message{{Role: "user", Content: "hi"}})
253 if err == nil {
254 t.Fatal("expected error on 429")
255 }
256 if err.Error() != tt.want {
257 t.Errorf("got %q, want %q", err.Error(), tt.want)
258 }
259 })
260 }
261 }
262
263 func TestModelClassifiesContextLengthErrors(t *testing.T) {
264 tests := []struct {
265 name string
266 message string
267 }{
268 {
269 name: "context length exceeded code",
270 message: "context_length_exceeded",
271 },
272 {
273 name: "maximum context length",
274 message: "This model's maximum context length is 128000 tokens. However, your messages resulted in 130000 tokens.",
275 },
276 {
277 name: "context length",
278 message: "Request exceeds context length.",
279 },
280 }
281
282 for _, tt := range tests {
283 t.Run(tt.name, func(t *testing.T) {
284 server := httptest.NewServer(
285 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
286 writeAPIError(t, w, http.StatusBadRequest, tt.message)
287 }),
288 )
289 defer server.Close()
290
291 m := openai.NewModel(server.URL, "test-key", "gpt-test", "sys")
292 _, err := m.Query(context.Background(), []clnkr.Message{{Role: "user", Content: "hi"}})
293 if !errors.Is(err, clnkr.ErrContextLengthExceeded) {
294 t.Fatalf("Query error = %v, want ErrContextLengthExceeded", err)
295 }
296 if err == nil || !strings.Contains(err.Error(), tt.message) {
297 t.Fatalf("Query error = %v, want provider message %q", err, tt.message)
298 }
299 })
300 }
301 }
302
303 func TestModelClassifiesContextLengthErrorCodeWithoutMessage(t *testing.T) {
304 server := httptest.NewServer(
305 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
306 writeAPIErrorBody(t, w, http.StatusBadRequest, map[string]any{
307 "error": map[string]any{"code": "context_length_exceeded"},
308 })
309 }),
310 )
311 defer server.Close()
312
313 m := openai.NewModel(server.URL, "test-key", "gpt-test", "sys")
314 _, err := m.Query(context.Background(), []clnkr.Message{{Role: "user", Content: "hi"}})
315 if !errors.Is(err, clnkr.ErrContextLengthExceeded) {
316 t.Fatalf("Query error = %v, want ErrContextLengthExceeded", err)
317 }
318 if err == nil || !strings.Contains(err.Error(), "context_length_exceeded") {
319 t.Fatalf("Query error = %v, want error code", err)
320 }
321 }
322
323 func TestModelClassifiesContextWindowWording(t *testing.T) {
324 message := "Your input exceeds the context window of this model. Please adjust your input and try again."
325 server := httptest.NewServer(
326 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
327 writeAPIError(t, w, http.StatusBadRequest, message)
328 }),
329 )
330 defer server.Close()
331
332 m := openai.NewModel(server.URL, "test-key", "gpt-test", "sys")
333 _, err := m.Query(context.Background(), []clnkr.Message{{Role: "user", Content: "hi"}})
334 if !errors.Is(err, clnkr.ErrContextLengthExceeded) {
335 t.Fatalf("Query error = %v, want ErrContextLengthExceeded", err)
336 }
337 if err == nil || !strings.Contains(err.Error(), message) {
338 t.Fatalf("Query error = %v, want provider message %q", err, message)
339 }
340 }
341
342 func TestModelDoesNotClassifyUnrelatedContextLengthMessage(t *testing.T) {
343 message := "invalid request: context length must be a positive integer"
344 server := httptest.NewServer(
345 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
346 writeAPIError(t, w, http.StatusBadRequest, message)
347 }),
348 )
349 defer server.Close()
350
351 m := openai.NewModel(server.URL, "test-key", "gpt-test", "sys")
352 _, err := m.Query(context.Background(), []clnkr.Message{{Role: "user", Content: "hi"}})
353 if errors.Is(err, clnkr.ErrContextLengthExceeded) {
354 t.Fatalf("Query error = %v, did not want ErrContextLengthExceeded", err)
355 }
356 if err == nil || !strings.Contains(err.Error(), message) {
357 t.Fatalf("Query error = %v, want provider message %q", err, message)
358 }
359 }
360
361 func TestModelRetriesQueryErrorsAndSucceeds(t *testing.T) {
362 tests := []struct {
363 name string
364 status int
365 message string
366 }{
367 {
368 name: "rate limit response",
369 status: http.StatusTooManyRequests,
370 message: "Rate limit exceeded",
371 },
372 {
373 name: "transient server error",
374 status: http.StatusBadGateway,
375 message: "context deadline exceeded",
376 },
377 }
378
379 for _, tt := range tests {
380 t.Run(tt.name, func(t *testing.T) {
381 attempts := 0
382 server := httptest.NewServer(
383 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
384 attempts++
385 if attempts == 1 {
386 writeAPIError(t, w, tt.status, tt.message)
387 return
388 }
389 writeChatResponse(t, w, openAIWrappedDone("ok after retry"), 2, 3)
390 }),
391 )
392 defer server.Close()
393
394 m := openai.NewModel(server.URL, "test-key", "gpt-test", "sys")
395 resp, err := m.Query(
396 context.Background(),
397 []clnkr.Message{{Role: "user", Content: "hi"}},
398 )
399 if err != nil {
400 t.Fatalf("unexpected error: %v", err)
401 }
402 if attempts != 2 {
403 t.Fatalf("attempt count = %d, want 2", attempts)
404 }
405 if got, want := mustCanonicalTurn(
406 t,
407 resp.Turn,
408 ), doneTurn(
409 "ok after retry",
410 ); got != want {
411 t.Fatalf("content = %q, want %q", got, want)
412 }
413 })
414 }
415 }
416
417 func TestModelFailsClosedOnUnsupportedStructuredOutputBackend(t *testing.T) {
418 attempts := 0
419 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
420 attempts++
421 writeAPIError(t, w, http.StatusBadRequest, "response_format json_schema is not supported")
422 }))
423 defer server.Close()
424
425 m := openai.NewModel(server.URL, "test-key", "gpt-test", "sys")
426 _, err := m.Query(context.Background(), []clnkr.Message{{Role: "user", Content: "hi"}})
427 if err == nil {
428 t.Fatal("expected unsupported feature error")
429 }
430 if attempts != 1 {
431 t.Fatalf("attempt count = %d, want 1", attempts)
432 }
433 }
434
435 func TestModelStopsAfterMaxAttemptsOnRepeatedRetryableErrors(t *testing.T) {
436 tests := []struct {
437 name string
438 status int
439 body string
440 want string
441 }{
442 {
443 name: "rate limits",
444 status: http.StatusTooManyRequests,
445 body: `{"error":{"code":429,"message":"Rate limit exceeded"}}`,
446 want: "api error (status 429): Rate limit exceeded",
447 },
448 {
449 name: "non-JSON server errors",
450 status: http.StatusBadGateway,
451 body: "Bad Gateway",
452 want: "api error (status 502): Bad Gateway",
453 },
454 }
455
456 for _, tt := range tests {
457 t.Run(tt.name, func(t *testing.T) {
458 attempts := 0
459 server := httptest.NewServer(
460 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
461 attempts++
462 w.Header().Set("Retry-After", "0")
463 w.WriteHeader(tt.status)
464 _, _ = w.Write([]byte(tt.body))
465 }),
466 )
467 defer server.Close()
468
469 m := openai.NewModel(server.URL, "test-key", "gpt-test", "sys")
470 _, err := m.Query(context.Background(), []clnkr.Message{{Role: "user", Content: "hi"}})
471 if err == nil {
472 t.Fatal("expected retryable error")
473 }
474 if err.Error() != tt.want {
475 t.Fatalf("got %q, want %q", err.Error(), tt.want)
476 }
477 if attempts != 5 {
478 t.Fatalf("attempt count = %d, want 5", attempts)
479 }
480 })
481 }
482 }
483
484 func TestModelCancellationStopsRateLimitBackoff(t *testing.T) {
485 attempts := 0
486 firstAttempt := make(chan struct{})
487 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
488 attempts++
489 if attempts != 1 {
490 t.Fatalf("unexpected retry after cancellation")
491 }
492 close(firstAttempt)
493 w.Header().Set("Retry-After", "10")
494 w.WriteHeader(http.StatusTooManyRequests)
495 _ = json.NewEncoder(w).Encode(map[string]any{
496 "error": map[string]any{"code": 429, "message": "Rate limit exceeded"},
497 })
498 }))
499 defer server.Close()
500
501 ctx, cancel := context.WithCancel(context.Background())
502 defer cancel()
503 go func() {
504 <-firstAttempt
505 cancel()
506 }()
507
508 m := openai.NewModel(server.URL, "test-key", "gpt-test", "sys")
509 _, err := m.Query(ctx, []clnkr.Message{{Role: "user", Content: "hi"}})
510 if err == nil {
511 t.Fatal("expected cancellation error")
512 }
513 if !errors.Is(err, context.Canceled) {
514 t.Fatalf("error = %v, want context canceled", err)
515 }
516 if attempts != 1 {
517 t.Fatalf("attempt count = %d, want 1", attempts)
518 }
519 }
520
521 func TestModelFailsOnUnusableSuccessfulResponses(t *testing.T) {
522 tests := []struct {
523 name string
524 response map[string]any
525 assertErr func(*testing.T, error)
526 }{
527 {
528 name: "empty choices",
529 response: map[string]any{
530 "choices": []any{},
531 "usage": map[string]int{"prompt_tokens": 0, "completion_tokens": 0},
532 },
533 assertErr: func(t *testing.T, err error) {
534 if err == nil {
535 t.Error("expected error on empty choices")
536 }
537 },
538 },
539 {
540 name: "empty choice content",
541 response: map[string]any{
542 "choices": []map[string]any{
543 {"message": map[string]string{"role": "assistant", "content": ""}},
544 },
545 "usage": map[string]int{"prompt_tokens": 0, "completion_tokens": 0},
546 },
547 assertErr: func(t *testing.T, err error) {
548 if err == nil {
549 t.Fatal("expected empty content error")
550 }
551 },
552 },
553 {
554 name: "refusal",
555 response: map[string]any{
556 "choices": []map[string]any{
557 {"message": map[string]string{"role": "assistant", "refusal": "refused"}},
558 },
559 "usage": map[string]int{"prompt_tokens": 0, "completion_tokens": 0},
560 },
561 assertErr: func(t *testing.T, err error) {
562 if err == nil {
563 t.Fatal("expected refusal error")
564 }
565 if err.Error() == "empty choice content" {
566 t.Fatal("expected refusal-specific error, got empty choice content")
567 }
568 },
569 },
570 }
571
572 for _, tt := range tests {
573 t.Run(tt.name, func(t *testing.T) {
574 server := httptest.NewServer(
575 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
576 if err := json.NewEncoder(w).Encode(tt.response); err != nil {
577 t.Fatalf("encode response: %v", err)
578 }
579 }),
580 )
581 defer server.Close()
582
583 m := openai.NewModel(server.URL, "test-key", "gpt-test", "sys")
584 _, err := m.Query(context.Background(), []clnkr.Message{{Role: "user", Content: "hi"}})
585 tt.assertErr(t, err)
586 })
587 }
588 }
589
590 func TestModelReturnsRawPayloadPlusProtocolErrorOnInvalidStructuredPayload(t *testing.T) {
591 content := `{"turn":{"type":"done","bash":{"commands":[{"command":"rm -rf tmp","workdir":null}]},"question":null,"summary":"done","reasoning":null}}`
592 resp := queryContent(t, content)
593 if resp.Raw != content {
594 t.Fatalf("raw = %q, want %q", resp.Raw, content)
595 }
596 if !errors.Is(resp.ProtocolErr, clnkr.ErrInvalidJSON) {
597 t.Fatalf("protocol error = %v, want ErrInvalidJSON", resp.ProtocolErr)
598 }
599 }
600
601 func TestModelAcceptsCanonicalJSONWhenResponseFormatWrapperIsIgnored(t *testing.T) {
602 tests := []struct {
603 name string
604 raw string
605 want string
606 }{
607 {
608 name: "done",
609 raw: doneTurn("ignored"),
610 want: doneTurn("ignored"),
611 },
612 {
613 name: "clarify",
614 raw: `{"type":"clarify","question":"Which repo?"}`,
615 want: `{"type":"clarify","question":"Which repo?"}`,
616 },
617 {
618 name: "act",
619 raw: `{"type":"act","bash":{"commands":[{"command":"pwd","workdir":null}]},"reasoning":"inspect cwd"}`,
620 want: `{"type":"act","bash":{"commands":[{"command":"pwd","workdir":null}]},"reasoning":"inspect cwd"}`,
621 },
622 }
623
624 for _, tt := range tests {
625 t.Run(tt.name, func(t *testing.T) {
626 resp := queryContent(t, tt.raw)
627 if resp.Raw != tt.raw {
628 t.Fatalf("raw = %q, want %q", resp.Raw, tt.raw)
629 }
630 if resp.ProtocolErr != nil {
631 t.Fatalf("protocol error = %v, want nil", resp.ProtocolErr)
632 }
633 if resp.Turn == nil {
634 t.Fatal("turn = nil, want parsed turn")
635 }
636 if got := mustCanonicalTurn(t, resp.Turn); got != tt.want {
637 t.Fatalf("turn = %q, want %q", got, tt.want)
638 }
639 })
640 }
641 }
642
643 func TestModelRejectsNonTurnJSONWhenResponseFormatWrapperIsIgnored(t *testing.T) {
644 raw := `[{"command":"pwd","workdir":null}]`
645 resp := queryContent(t, raw)
646 if resp.Raw != raw {
647 t.Fatalf("raw = %q, want %q", resp.Raw, raw)
648 }
649 if !errors.Is(resp.ProtocolErr, clnkr.ErrInvalidJSON) {
650 t.Fatalf("protocol error = %v, want ErrInvalidJSON", resp.ProtocolErr)
651 }
652 if resp.Turn != nil {
653 t.Fatalf("turn = %T, want nil", resp.Turn)
654 }
655 }
656
657 func readRequestBody(t *testing.T, r *http.Request) map[string]any {
658 t.Helper()
659 body, err := io.ReadAll(r.Body)
660 if err != nil {
661 t.Fatalf("read request body: %v", err)
662 }
663 var got map[string]any
664 if err := json.Unmarshal(body, &got); err != nil {
665 t.Fatalf("decode request body: %v", err)
666 }
667 return got
668 }
669
670 func writeChatResponse(
671 t *testing.T,
672 w http.ResponseWriter,
673 content string,
674 inputTokens, outputTokens int,
675 ) {
676 t.Helper()
677 if err := json.NewEncoder(w).Encode(map[string]any{
678 "choices": []map[string]any{
679 {"message": map[string]string{"role": "assistant", "content": content}},
680 },
681 "usage": map[string]int{"prompt_tokens": inputTokens, "completion_tokens": outputTokens},
682 }); err != nil {
683 t.Fatalf("encode response: %v", err)
684 }
685 }
686
687 func writeAPIError(t *testing.T, w http.ResponseWriter, status int, message string) {
688 t.Helper()
689 w.Header().Set("Retry-After", "0")
690 w.WriteHeader(status)
691 if err := json.NewEncoder(w).Encode(map[string]any{
692 "error": map[string]any{"code": status, "message": message},
693 }); err != nil {
694 t.Fatalf("encode error response: %v", err)
695 }
696 }
697
698 func writeAPIErrorBody(t *testing.T, w http.ResponseWriter, status int, body any) {
699 t.Helper()
700 w.WriteHeader(status)
701 if err := json.NewEncoder(w).Encode(body); err != nil {
702 t.Fatalf("write error body: %v", err)
703 }
704 }
705
706 func queryContent(t *testing.T, content string) clnkr.Response {
707 t.Helper()
708 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
709 writeChatResponse(t, w, content, 0, 0)
710 }))
711 defer server.Close()
712
713 m := openai.NewModel(server.URL, "test-key", "gpt-test", "sys")
714 resp, err := m.Query(context.Background(), []clnkr.Message{{Role: "user", Content: "hi"}})
715 if err != nil {
716 t.Fatalf("unexpected error: %v", err)
717 }
718 return resp
719 }
720
721 func doneTurn(summary string) string {
722 return `{"type":"done","summary":"` + summary + `","verification":{"status":"verified","checks":[{"command":"go test ./...","outcome":"passed","evidence":"go test ./... passed and ls output showed current directory entries for completion"}]},"known_risks":[]}`
723 }
724
725 func openAIWrappedDone(summary string) string {
726 return `{"turn":{"type":"done","bash":null,"question":null,"summary":"` + summary + `","verification":{"status":"verified","checks":[{"command":"go test ./...","outcome":"passed","evidence":"go test ./... passed and ls output showed current directory entries for completion"}]},"known_risks":[],"reasoning":null}}`
727 }
728
729 func schemaContainsKey(node any, key string) bool {
730 switch v := node.(type) {
731 case map[string]any:
732 if _, ok := v[key]; ok {
733 return true
734 }
735 for _, child := range v {
736 if schemaContainsKey(child, key) {
737 return true
738 }
739 }
740 case []any:
741 for _, child := range v {
742 if schemaContainsKey(child, key) {
743 return true
744 }
745 }
746 }
747
748 return false
749 }
750
751 func mustCanonicalTurn(t *testing.T, turn clnkr.Turn) string {
752 t.Helper()
753 raw, err := clnkr.CanonicalTurnJSON(turn)
754 if err != nil {
755 t.Fatalf("CanonicalTurnJSON: %v", err)
756 }
757 return raw
758 }