1package provider
2
3import (
4 "context"
5 "net/http"
6 "net/http/httptest"
7 "strings"
8 "testing"
9)
10
11func TestSSEParse(t *testing.T) {
12 r := strings.NewReader("event: foo\ndata: {\"a\":1}\n\ndata: hello\ndata: world\n\n")
13 ch := make(chan sseEvent, 4)
14 go readSSE(r, ch)
15
16 e := <-ch
17 if e.Event != "foo" || e.Data != `{"a":1}` {
18 t.Fatalf("event 1: %+v", e)
19 }
20 e = <-ch
21 if e.Event != "" || e.Data != "hello\nworld" {
22 t.Fatalf("event 2: %+v", e)
23 }
24 if _, ok := <-ch; ok {
25 t.Fatalf("channel not closed")
26 }
27}
28
29func TestModelCatalog(t *testing.T) {
30 if len(Catalog) == 0 {
31 t.Fatal("empty catalog")
32 }
33 if _, err := FindModel("anthropic", "claude-sonnet-4-5"); err != nil {
34 t.Fatal(err)
35 }
36 if _, err := FindModel("openai", "gpt-5"); err != nil {
37 t.Fatal(err)
38 }
39 if _, err := FindModel("", "nope"); err == nil {
40 t.Fatal("expected error")
41 }
42}
43
44func TestVertexGeminiFlashCatalogLimits(t *testing.T) {
45 for _, id := range []string{"gemini-3.1-flash-lite", "gemini-3.5-flash"} {
46 m, err := FindModel("google-vertex", id)
47 if err != nil {
48 t.Fatal(err)
49 }
50 if m.ContextWindow != 1048576 || m.MaxOutput != 65535 || !m.Reasoning {
51 t.Errorf("%s metadata = %+v", id, m)
52 }
53 }
54}
55
56func TestComputeCost(t *testing.T) {
57 m, _ := FindModel("anthropic", "claude-sonnet-4-5")
58 cost := ComputeCost(m, Usage{InputTokens: 1_000_000, OutputTokens: 1_000_000})
59 want := m.PriceInput + m.PriceOutput
60 if cost != want {
61 t.Fatalf("cost=%v want=%v", cost, want)
62 }
63}
64
65func TestAnthropicErrorStatus(t *testing.T) {
66 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
67 w.WriteHeader(http.StatusUnauthorized)
68 _, _ = w.Write([]byte(`{"error":{"type":"auth","message":"bad key"}}`))
69 }))
70 defer srv.Close()
71
72 c := NewAnthropic("x", srv.URL)
73 _, err := c.Stream(context.Background(), Request{Model: "claude-sonnet-4-5"})
74 if err == nil || !strings.Contains(err.Error(), "401") {
75 t.Fatalf("want 401 err, got %v", err)
76 }
77}
78
79func TestOpenAIErrorStatus(t *testing.T) {
80 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
81 w.WriteHeader(http.StatusBadRequest)
82 _, _ = w.Write([]byte(`{"error":{"message":"nope"}}`))
83 }))
84 defer srv.Close()
85
86 c := NewOpenAI("x", srv.URL)
87 _, err := c.Stream(context.Background(), Request{Model: "gpt-5"})
88 if err == nil || !strings.Contains(err.Error(), "400") {
89 t.Fatalf("want 400 err, got %v", err)
90 }
91}
92
93func TestAnthropicAdaptiveThinking(t *testing.T) {
94 c := NewAnthropic("x", "").(*anthropicClient)
95 temp := float32(0.7)
96
97 // Opus 4.8 -> adaptive thinking, effort set, no budget, no temperature.
98 wire, err := c.buildRequest(Request{
99 Model: "claude-opus-4-8",
100 Reasoning: "high",
101 Temperature: &temp,
102 Messages: []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
103 })
104 if err != nil {
105 t.Fatal(err)
106 }
107 if wire.Thinking == nil || wire.Thinking.Type != "adaptive" {
108 t.Fatalf("want adaptive thinking, got %+v", wire.Thinking)
109 }
110 if wire.Thinking.BudgetTokens != 0 {
111 t.Fatalf("adaptive must not send budget_tokens, got %d", wire.Thinking.BudgetTokens)
112 }
113 if wire.OutputConfig == nil || wire.OutputConfig.Effort != "high" {
114 t.Fatalf("want effort=high, got %+v", wire.OutputConfig)
115 }
116 if wire.Temperature != nil {
117 t.Fatalf("adaptive must drop temperature, got %v", *wire.Temperature)
118 }
119
120 // maximum -> xhigh effort.
121 wire, err = c.buildRequest(Request{
122 Model: "claude-opus-4-8",
123 Reasoning: "maximum",
124 Messages: []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
125 })
126 if err != nil {
127 t.Fatal(err)
128 }
129 if wire.OutputConfig == nil || wire.OutputConfig.Effort != "xhigh" {
130 t.Fatalf("want effort=xhigh, got %+v", wire.OutputConfig)
131 }
132
133 // max is a separate native tier above xhigh on adaptive models.
134 wire, err = c.buildRequest(Request{
135 Model: "claude-opus-4-8",
136 Reasoning: "max",
137 Messages: []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
138 })
139 if err != nil {
140 t.Fatal(err)
141 }
142 if wire.OutputConfig == nil || wire.OutputConfig.Effort != "max" {
143 t.Fatalf("want effort=max, got %+v", wire.OutputConfig)
144 }
145
146 // Sonnet 5 -> adaptive thinking, effort set, no budget, no temperature.
147 wire, err = c.buildRequest(Request{
148 Model: "claude-sonnet-5",
149 Reasoning: "high",
150 Temperature: &temp,
151 Messages: []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
152 })
153 if err != nil {
154 t.Fatal(err)
155 }
156 if wire.Thinking == nil || wire.Thinking.Type != "adaptive" {
157 t.Fatalf("want adaptive thinking for Sonnet 5, got %+v", wire.Thinking)
158 }
159 if wire.Thinking.BudgetTokens != 0 {
160 t.Fatalf("Sonnet 5 adaptive must not send budget_tokens, got %d", wire.Thinking.BudgetTokens)
161 }
162 if wire.OutputConfig == nil || wire.OutputConfig.Effort != "high" {
163 t.Fatalf("want Sonnet 5 effort=high, got %+v", wire.OutputConfig)
164 }
165 if wire.Temperature != nil {
166 t.Fatalf("Sonnet 5 adaptive must drop temperature, got %v", *wire.Temperature)
167 }
168
169 // Opus 4.5 -> budget-based thinking, no output_config, temperature kept.
170 wire, err = c.buildRequest(Request{
171 Model: "claude-opus-4-5",
172 Reasoning: "high",
173 Temperature: &temp,
174 Messages: []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
175 })
176 if err != nil {
177 t.Fatal(err)
178 }
179 if wire.Thinking == nil || wire.Thinking.Type != "enabled" || wire.Thinking.BudgetTokens <= 0 {
180 t.Fatalf("want budget thinking, got %+v", wire.Thinking)
181 }
182 if wire.OutputConfig != nil {
183 t.Fatalf("budget models must not send output_config, got %+v", wire.OutputConfig)
184 }
185 if wire.Temperature == nil || *wire.Temperature != temp {
186 t.Fatalf("budget model should keep temperature, got %v", wire.Temperature)
187 }
188}
189
190func TestAnthropicBuildRequestStripsAssistantImages(t *testing.T) {
191 c := NewAnthropic("x", "").(*anthropicClient)
192 wire, err := c.buildRequest(Request{
193 Model: "claude-sonnet-4-5",
194 Messages: []Message{
195 {Role: RoleUser, Content: []Content{TextBlock{Text: "make an image"}}},
196 {Role: RoleAssistant, Content: []Content{
197 TextBlock{Text: "done"},
198 ImageBlock{MimeType: "image/png", Data: []byte("png")},
199 TextBlock{Text: "Saved image: `zot-gemini-image-x.png`"},
200 }},
201 {Role: RoleUser, Content: []Content{TextBlock{Text: "hello"}}},
202 },
203 })
204 if err != nil {
205 t.Fatal(err)
206 }
207 if len(wire.Messages) != 3 {
208 t.Fatalf("messages=%d", len(wire.Messages))
209 }
210 assistant := wire.Messages[1]
211 if assistant.Role != "assistant" {
212 t.Fatalf("role=%q", assistant.Role)
213 }
214 if len(assistant.Content) != 2 {
215 t.Fatalf("assistant content=%+v", assistant.Content)
216 }
217 for _, b := range assistant.Content {
218 if _, ok := b.(anthImageBlock); ok {
219 t.Fatalf("assistant image block was not stripped: %+v", assistant.Content)
220 }
221 }
222}
223
224func TestAnthropicStreamHappyPath(t *testing.T) {
225 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
226 w.Header().Set("content-type", "text/event-stream")
227 w.WriteHeader(http.StatusOK)
228 fl, _ := w.(http.Flusher)
229 write := func(s string) {
230 _, _ = w.Write([]byte(s))
231 if fl != nil {
232 fl.Flush()
233 }
234 }
235 write("event: message_start\ndata: {\"message\":{\"usage\":{\"input_tokens\":10,\"output_tokens\":0}}}\n\n")
236 write("event: content_block_start\ndata: {\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n")
237 write("event: content_block_delta\ndata: {\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"hi\"}}\n\n")
238 write("event: content_block_stop\ndata: {\"index\":0}\n\n")
239 write("event: message_delta\ndata: {\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":5}}\n\n")
240 write("event: message_stop\ndata: {}\n\n")
241 }))
242 defer srv.Close()
243
244 c := NewAnthropic("x", srv.URL)
245 evs, err := c.Stream(context.Background(), Request{Model: "claude-sonnet-4-5"})
246 if err != nil {
247 t.Fatal(err)
248 }
249 var gotText string
250 var done EventDone
251 for ev := range evs {
252 switch e := ev.(type) {
253 case EventTextDelta:
254 gotText += e.Delta
255 case EventDone:
256 done = e
257 }
258 }
259 if gotText != "hi" {
260 t.Fatalf("text=%q", gotText)
261 }
262 if done.Stop != StopEnd {
263 t.Fatalf("stop=%v", done.Stop)
264 }
265}
266
267func TestClaudeSonnet5Catalog(t *testing.T) {
268 m, err := FindModel("anthropic", "claude-sonnet-5")
269 if err != nil {
270 t.Fatal(err)
271 }
272 if m.DisplayName != "Claude Sonnet 5" || m.ContextWindow != 1000000 || m.MaxOutput != 128000 || !m.Reasoning || !m.AdaptiveThinking {
273 t.Fatalf("unexpected Sonnet 5 model: %+v", m)
274 }
275 if m.PriceInput != 2 || m.PriceOutput != 10 || m.PriceCacheRead != 0.2 || m.PriceCacheWrite != 2.5 {
276 t.Fatalf("unexpected Sonnet 5 pricing: %+v", m)
277 }
278}
279
280func TestOpenAICompatAnthropicReasoningEffort(t *testing.T) {
281 c := NewOpenRouter("token", "").(*openaiClient)
282 wire, err := c.buildRequest(Request{
283 Model: "anthropic/claude-opus-4.8",
284 Reasoning: "maximum",
285 Messages: []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
286 })
287 if err != nil {
288 t.Fatal(err)
289 }
290 if wire.ReasoningEffort != "xhigh" {
291 t.Fatalf("want xhigh for adaptive Anthropic model over OpenAI-compatible wire, got %q", wire.ReasoningEffort)
292 }
293
294 wire, err = c.buildRequest(Request{
295 Model: "anthropic/claude-sonnet-5",
296 Reasoning: "maximum",
297 Messages: []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
298 })
299 if err != nil {
300 t.Fatal(err)
301 }
302 if wire.ReasoningEffort != "xhigh" {
303 t.Fatalf("want xhigh for Claude Sonnet 5 over OpenAI-compatible wire, got %q", wire.ReasoningEffort)
304 }
305
306 wire, err = c.buildRequest(Request{
307 Model: "gpt-5.1",
308 Reasoning: "maximum",
309 Messages: []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
310 })
311 if err != nil {
312 t.Fatal(err)
313 }
314 if wire.ReasoningEffort != "high" {
315 t.Fatalf("want generic OpenAI-compatible maximum clamped to high, got %q", wire.ReasoningEffort)
316 }
317}
318
319func TestOpenAIBuildRequestSkipsReasoningOnlyAssistantMessages(t *testing.T) {
320 c := NewKimi("token", "").(*openaiClient)
321 wire, err := c.buildRequest(Request{
322 Model: "kimi-for-coding",
323 Messages: []Message{
324 {Role: RoleUser, Content: []Content{TextBlock{Text: "first"}}},
325 {Role: RoleAssistant, Content: []Content{ReasoningBlock{Summary: "thinking only"}}},
326 {Role: RoleUser, Content: []Content{TextBlock{Text: "second"}}},
327 },
328 })
329 if err != nil {
330 t.Fatal(err)
331 }
332 for i, msg := range wire.Messages {
333 if msg.Role == "assistant" && msg.Content == nil && len(msg.ToolCalls) == 0 {
334 t.Fatalf("message %d is empty assistant: %+v", i, msg)
335 }
336 }
337 if got := len(wire.Messages); got != 2 {
338 t.Fatalf("messages=%d want 2 after skipping reasoning-only assistant", got)
339 }
340}
341
342func TestOpenAIStreamHappyPath(t *testing.T) {
343 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
344 w.Header().Set("content-type", "text/event-stream")
345 w.WriteHeader(http.StatusOK)
346 fl, _ := w.(http.Flusher)
347 write := func(s string) {
348 _, _ = w.Write([]byte(s))
349 if fl != nil {
350 fl.Flush()
351 }
352 }
353 write("data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"hel\"},\"finish_reason\":null}]}\n\n")
354 write("data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"lo\"},\"finish_reason\":\"stop\"}]}\n\n")
355 write("data: {\"choices\":[],\"usage\":{\"prompt_tokens\":8,\"completion_tokens\":2}}\n\n")
356 write("data: [DONE]\n\n")
357 }))
358 defer srv.Close()
359
360 c := NewOpenAI("x", srv.URL)
361 evs, err := c.Stream(context.Background(), Request{Model: "gpt-5"})
362 if err != nil {
363 t.Fatal(err)
364 }
365 var gotText string
366 var done EventDone
367 for ev := range evs {
368 switch e := ev.(type) {
369 case EventTextDelta:
370 gotText += e.Delta
371 case EventDone:
372 done = e
373 }
374 }
375 if gotText != "hello" {
376 t.Fatalf("text=%q", gotText)
377 }
378 if done.Stop != StopEnd {
379 t.Fatalf("stop=%v", done.Stop)
380 }
381}
382
383func TestDiscoverOpenRouter(t *testing.T) {
384 const body = `{"data":[
385 {"id":"x/full","pricing":{"prompt":"0.000003","completion":"0.000015"},
386 "context_length":200000,"top_provider":{"max_completion_tokens":64000},
387 "supported_parameters":["reasoning"]},
388 {"id":"x/fallback","top_provider":{"context_length":128000}},
389 {"id":""}]}`
390 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
391 _, _ = w.Write([]byte(body))
392 }))
393 defer srv.Close()
394
395 models, err := DiscoverOpenRouter(context.Background(), srv.URL)
396 if err != nil {
397 t.Fatal(err)
398 }
399 if len(models) != 2 { // empty id dropped
400 t.Fatalf("want 2 models, got %d", len(models))
401 }
402 // per-token USD -> per-1M; reasoning from supported_parameters.
403 if m := models[0]; m.Provider != "openrouter" || m.ContextWindow != 200000 ||
404 m.MaxOutput != 64000 || !m.Reasoning || m.PriceInput != 3 || m.PriceOutput != 15 {
405 t.Errorf("model[0]: %+v", m)
406 }
407 // context falls back to top_provider; no reasoning.
408 if m := models[1]; m.ContextWindow != 128000 || m.MaxOutput != 0 || m.Reasoning {
409 t.Errorf("model[1]: %+v", m)
410 }
411}
412
413func TestGPT56CatalogEntries(t *testing.T) {
414 cases := []struct {
415 provider string
416 id string
417 context int
418 priceInput float64
419 priceOut float64
420 cacheRead float64
421 cacheWrite float64
422 }{
423 {"openai", "gpt-5.6-luna", 272000, 1, 6, 0.1, 1.25},
424 {"openai", "gpt-5.6-sol", 272000, 5, 30, 0.5, 6.25},
425 {"openai", "gpt-5.6-terra", 272000, 2.5, 15, 0.25, 3.125},
426 {"openai-codex", "gpt-5.6-luna", 372000, 1, 6, 0.1, 1.25},
427 {"openai-codex", "gpt-5.6-sol", 372000, 5, 30, 0.5, 6.25},
428 {"openai-codex", "gpt-5.6-terra", 372000, 2.5, 15, 0.25, 3.125},
429 {"azure-openai-responses", "gpt-5.6-luna", 1050000, 1, 6, 0.1, 1.25},
430 {"azure-openai-responses", "gpt-5.6-sol", 1050000, 5, 30, 0.5, 6.25},
431 {"azure-openai-responses", "gpt-5.6-terra", 1050000, 2.5, 15, 0.25, 3.125},
432 {"vercel-ai-gateway", "openai/gpt-5.6-luna", 1050000, 1, 6, 0.1, 1.25},
433 {"vercel-ai-gateway", "openai/gpt-5.6-sol", 1050000, 5, 30, 0.5, 6.25},
434 {"vercel-ai-gateway", "openai/gpt-5.6-terra", 1050000, 2.5, 15, 0.25, 3.125},
435 }
436 for _, tc := range cases {
437 m, err := FindModel(tc.provider, tc.id)
438 if err != nil {
439 t.Fatal(err)
440 }
441 if m.ContextWindow != tc.context || m.MaxOutput != 128000 || !m.Reasoning {
442 t.Fatalf("%s/%s limits: %+v", tc.provider, tc.id, m)
443 }
444 if m.PriceInput != tc.priceInput || m.PriceOutput != tc.priceOut || m.PriceCacheRead != tc.cacheRead || m.PriceCacheWrite != tc.cacheWrite {
445 t.Fatalf("%s/%s prices: %+v", tc.provider, tc.id, m)
446 }
447 }
448}
449
450// TestOpenCodeGoCatalog pins the Grok 4.5 and Kimi K3 entries added to
451// the OpenCode Go provider. Both are listed in the vendor's current Go
452// model lineup (https://opencode.ai/docs/go) and were missing from the
453// baked-in catalog.
454func TestOpenCodeGoCatalog(t *testing.T) {
455 cases := []struct {
456 id string
457 context int
458 maxOut int
459 priceIn float64
460 priceOut float64
461 cacheRead float64
462 }{
463 {"grok-4.5", 500000, 500000, 2, 6, 0.3},
464 {"kimi-k3", 1048576, 131072, 3, 15, 0.3},
465 }
466 for _, tc := range cases {
467 m, err := FindModel("opencode-go", tc.id)
468 if err != nil {
469 t.Fatal(err)
470 }
471 if m.ContextWindow != tc.context || m.MaxOutput != tc.maxOut || !m.Reasoning {
472 t.Fatalf("opencode-go/%s limits: %+v", tc.id, m)
473 }
474 if m.PriceInput != tc.priceIn || m.PriceOutput != tc.priceOut || m.PriceCacheRead != tc.cacheRead {
475 t.Fatalf("opencode-go/%s prices: %+v", tc.id, m)
476 }
477 if m.BaseURL != "https://opencode.ai/zen/go/v1" {
478 t.Fatalf("opencode-go/%s baseURL: %s", tc.id, m.BaseURL)
479 }
480 }
481}
482
483// TestOpenAIOmitsZeroMaxTokens guards against sending max_tokens: 0 for
484// discovered models that don't advertise an output cap (MaxOutput == 0).
485func TestOpenAIOmitsZeroMaxTokens(t *testing.T) {
486 SetLiveModels([]Model{
487 {Provider: "openrouter", ID: "vendor/no-cap", DisplayName: "No Cap"},
488 {Provider: "openrouter", ID: "vendor/reason-no-cap", DisplayName: "Reason No Cap", Reasoning: true},
489 {Provider: "openrouter", ID: "vendor/capped", DisplayName: "Capped", MaxOutput: 4096},
490 })
491 defer SetLiveModels(nil)
492
493 c := NewOpenAI("x", "").(*openaiClient)
494
495 got, err := c.buildRequest(Request{Model: "vendor/no-cap"})
496 if err != nil {
497 t.Fatal(err)
498 }
499 if got.MaxTokens != nil {
500 t.Errorf("expected max_tokens omitted, got %d", *got.MaxTokens)
501 }
502
503 got, err = c.buildRequest(Request{Model: "vendor/reason-no-cap"})
504 if err != nil {
505 t.Fatal(err)
506 }
507 if got.MaxCompletionTok != nil {
508 t.Errorf("expected max_completion_tokens omitted, got %d", *got.MaxCompletionTok)
509 }
510
511 got, err = c.buildRequest(Request{Model: "vendor/capped"})
512 if err != nil {
513 t.Fatal(err)
514 }
515 if got.MaxTokens == nil || *got.MaxTokens != 4096 {
516 t.Errorf("expected max_tokens 4096, got %v", got.MaxTokens)
517 }
518}