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 TestComputeCost(t *testing.T) {
45 m, _ := FindModel("anthropic", "claude-sonnet-4-5")
46 cost := ComputeCost(m, Usage{InputTokens: 1_000_000, OutputTokens: 1_000_000})
47 want := m.PriceInput + m.PriceOutput
48 if cost != want {
49 t.Fatalf("cost=%v want=%v", cost, want)
50 }
51}
52
53func TestAnthropicErrorStatus(t *testing.T) {
54 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
55 w.WriteHeader(http.StatusUnauthorized)
56 _, _ = w.Write([]byte(`{"error":{"type":"auth","message":"bad key"}}`))
57 }))
58 defer srv.Close()
59
60 c := NewAnthropic("x", srv.URL)
61 _, err := c.Stream(context.Background(), Request{Model: "claude-sonnet-4-5"})
62 if err == nil || !strings.Contains(err.Error(), "401") {
63 t.Fatalf("want 401 err, got %v", err)
64 }
65}
66
67func TestOpenAIErrorStatus(t *testing.T) {
68 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
69 w.WriteHeader(http.StatusBadRequest)
70 _, _ = w.Write([]byte(`{"error":{"message":"nope"}}`))
71 }))
72 defer srv.Close()
73
74 c := NewOpenAI("x", srv.URL)
75 _, err := c.Stream(context.Background(), Request{Model: "gpt-5"})
76 if err == nil || !strings.Contains(err.Error(), "400") {
77 t.Fatalf("want 400 err, got %v", err)
78 }
79}
80
81func TestAnthropicAdaptiveThinking(t *testing.T) {
82 c := NewAnthropic("x", "").(*anthropicClient)
83 temp := float32(0.7)
84
85 // Opus 4.8 -> adaptive thinking, effort set, no budget, no temperature.
86 wire, err := c.buildRequest(Request{
87 Model: "claude-opus-4-8",
88 Reasoning: "high",
89 Temperature: &temp,
90 Messages: []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
91 })
92 if err != nil {
93 t.Fatal(err)
94 }
95 if wire.Thinking == nil || wire.Thinking.Type != "adaptive" {
96 t.Fatalf("want adaptive thinking, got %+v", wire.Thinking)
97 }
98 if wire.Thinking.BudgetTokens != 0 {
99 t.Fatalf("adaptive must not send budget_tokens, got %d", wire.Thinking.BudgetTokens)
100 }
101 if wire.OutputConfig == nil || wire.OutputConfig.Effort != "high" {
102 t.Fatalf("want effort=high, got %+v", wire.OutputConfig)
103 }
104 if wire.Temperature != nil {
105 t.Fatalf("adaptive must drop temperature, got %v", *wire.Temperature)
106 }
107
108 // maximum -> xhigh effort.
109 wire, err = c.buildRequest(Request{
110 Model: "claude-opus-4-8",
111 Reasoning: "maximum",
112 Messages: []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
113 })
114 if err != nil {
115 t.Fatal(err)
116 }
117 if wire.OutputConfig == nil || wire.OutputConfig.Effort != "xhigh" {
118 t.Fatalf("want effort=xhigh, got %+v", wire.OutputConfig)
119 }
120
121 // Sonnet 5 -> adaptive thinking, effort set, no budget, no temperature.
122 wire, err = c.buildRequest(Request{
123 Model: "claude-sonnet-5",
124 Reasoning: "high",
125 Temperature: &temp,
126 Messages: []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
127 })
128 if err != nil {
129 t.Fatal(err)
130 }
131 if wire.Thinking == nil || wire.Thinking.Type != "adaptive" {
132 t.Fatalf("want adaptive thinking for Sonnet 5, got %+v", wire.Thinking)
133 }
134 if wire.Thinking.BudgetTokens != 0 {
135 t.Fatalf("Sonnet 5 adaptive must not send budget_tokens, got %d", wire.Thinking.BudgetTokens)
136 }
137 if wire.OutputConfig == nil || wire.OutputConfig.Effort != "high" {
138 t.Fatalf("want Sonnet 5 effort=high, got %+v", wire.OutputConfig)
139 }
140 if wire.Temperature != nil {
141 t.Fatalf("Sonnet 5 adaptive must drop temperature, got %v", *wire.Temperature)
142 }
143
144 // Opus 4.5 -> budget-based thinking, no output_config, temperature kept.
145 wire, err = c.buildRequest(Request{
146 Model: "claude-opus-4-5",
147 Reasoning: "high",
148 Temperature: &temp,
149 Messages: []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
150 })
151 if err != nil {
152 t.Fatal(err)
153 }
154 if wire.Thinking == nil || wire.Thinking.Type != "enabled" || wire.Thinking.BudgetTokens <= 0 {
155 t.Fatalf("want budget thinking, got %+v", wire.Thinking)
156 }
157 if wire.OutputConfig != nil {
158 t.Fatalf("budget models must not send output_config, got %+v", wire.OutputConfig)
159 }
160 if wire.Temperature == nil || *wire.Temperature != temp {
161 t.Fatalf("budget model should keep temperature, got %v", wire.Temperature)
162 }
163}
164
165func TestAnthropicBuildRequestStripsAssistantImages(t *testing.T) {
166 c := NewAnthropic("x", "").(*anthropicClient)
167 wire, err := c.buildRequest(Request{
168 Model: "claude-sonnet-4-5",
169 Messages: []Message{
170 {Role: RoleUser, Content: []Content{TextBlock{Text: "make an image"}}},
171 {Role: RoleAssistant, Content: []Content{
172 TextBlock{Text: "done"},
173 ImageBlock{MimeType: "image/png", Data: []byte("png")},
174 TextBlock{Text: "Saved image: `zot-gemini-image-x.png`"},
175 }},
176 {Role: RoleUser, Content: []Content{TextBlock{Text: "hello"}}},
177 },
178 })
179 if err != nil {
180 t.Fatal(err)
181 }
182 if len(wire.Messages) != 3 {
183 t.Fatalf("messages=%d", len(wire.Messages))
184 }
185 assistant := wire.Messages[1]
186 if assistant.Role != "assistant" {
187 t.Fatalf("role=%q", assistant.Role)
188 }
189 if len(assistant.Content) != 2 {
190 t.Fatalf("assistant content=%+v", assistant.Content)
191 }
192 for _, b := range assistant.Content {
193 if _, ok := b.(anthImageBlock); ok {
194 t.Fatalf("assistant image block was not stripped: %+v", assistant.Content)
195 }
196 }
197}
198
199func TestAnthropicStreamHappyPath(t *testing.T) {
200 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
201 w.Header().Set("content-type", "text/event-stream")
202 w.WriteHeader(http.StatusOK)
203 fl, _ := w.(http.Flusher)
204 write := func(s string) {
205 _, _ = w.Write([]byte(s))
206 if fl != nil {
207 fl.Flush()
208 }
209 }
210 write("event: message_start\ndata: {\"message\":{\"usage\":{\"input_tokens\":10,\"output_tokens\":0}}}\n\n")
211 write("event: content_block_start\ndata: {\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n")
212 write("event: content_block_delta\ndata: {\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"hi\"}}\n\n")
213 write("event: content_block_stop\ndata: {\"index\":0}\n\n")
214 write("event: message_delta\ndata: {\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":5}}\n\n")
215 write("event: message_stop\ndata: {}\n\n")
216 }))
217 defer srv.Close()
218
219 c := NewAnthropic("x", srv.URL)
220 evs, err := c.Stream(context.Background(), Request{Model: "claude-sonnet-4-5"})
221 if err != nil {
222 t.Fatal(err)
223 }
224 var gotText string
225 var done EventDone
226 for ev := range evs {
227 switch e := ev.(type) {
228 case EventTextDelta:
229 gotText += e.Delta
230 case EventDone:
231 done = e
232 }
233 }
234 if gotText != "hi" {
235 t.Fatalf("text=%q", gotText)
236 }
237 if done.Stop != StopEnd {
238 t.Fatalf("stop=%v", done.Stop)
239 }
240}
241
242func TestClaudeSonnet5Catalog(t *testing.T) {
243 m, err := FindModel("anthropic", "claude-sonnet-5")
244 if err != nil {
245 t.Fatal(err)
246 }
247 if m.DisplayName != "Claude Sonnet 5" || m.ContextWindow != 1000000 || m.MaxOutput != 128000 || !m.Reasoning || !m.AdaptiveThinking {
248 t.Fatalf("unexpected Sonnet 5 model: %+v", m)
249 }
250 if m.PriceInput != 2 || m.PriceOutput != 10 || m.PriceCacheRead != 0.2 || m.PriceCacheWrite != 2.5 {
251 t.Fatalf("unexpected Sonnet 5 pricing: %+v", m)
252 }
253}
254
255func TestOpenAICompatAnthropicReasoningEffort(t *testing.T) {
256 c := NewOpenRouter("token", "").(*openaiClient)
257 wire, err := c.buildRequest(Request{
258 Model: "anthropic/claude-opus-4.8",
259 Reasoning: "maximum",
260 Messages: []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
261 })
262 if err != nil {
263 t.Fatal(err)
264 }
265 if wire.ReasoningEffort != "xhigh" {
266 t.Fatalf("want xhigh for adaptive Anthropic model over OpenAI-compatible wire, got %q", wire.ReasoningEffort)
267 }
268
269 wire, err = c.buildRequest(Request{
270 Model: "anthropic/claude-sonnet-5",
271 Reasoning: "maximum",
272 Messages: []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
273 })
274 if err != nil {
275 t.Fatal(err)
276 }
277 if wire.ReasoningEffort != "xhigh" {
278 t.Fatalf("want xhigh for Claude Sonnet 5 over OpenAI-compatible wire, got %q", wire.ReasoningEffort)
279 }
280
281 wire, err = c.buildRequest(Request{
282 Model: "gpt-5.1",
283 Reasoning: "maximum",
284 Messages: []Message{{Role: RoleUser, Content: []Content{TextBlock{Text: "hi"}}}},
285 })
286 if err != nil {
287 t.Fatal(err)
288 }
289 if wire.ReasoningEffort != "high" {
290 t.Fatalf("want generic OpenAI-compatible maximum clamped to high, got %q", wire.ReasoningEffort)
291 }
292}
293
294func TestOpenAIBuildRequestSkipsReasoningOnlyAssistantMessages(t *testing.T) {
295 c := NewKimi("token", "").(*openaiClient)
296 wire, err := c.buildRequest(Request{
297 Model: "kimi-for-coding",
298 Messages: []Message{
299 {Role: RoleUser, Content: []Content{TextBlock{Text: "first"}}},
300 {Role: RoleAssistant, Content: []Content{ReasoningBlock{Summary: "thinking only"}}},
301 {Role: RoleUser, Content: []Content{TextBlock{Text: "second"}}},
302 },
303 })
304 if err != nil {
305 t.Fatal(err)
306 }
307 for i, msg := range wire.Messages {
308 if msg.Role == "assistant" && msg.Content == nil && len(msg.ToolCalls) == 0 {
309 t.Fatalf("message %d is empty assistant: %+v", i, msg)
310 }
311 }
312 if got := len(wire.Messages); got != 2 {
313 t.Fatalf("messages=%d want 2 after skipping reasoning-only assistant", got)
314 }
315}
316
317func TestOpenAIStreamHappyPath(t *testing.T) {
318 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
319 w.Header().Set("content-type", "text/event-stream")
320 w.WriteHeader(http.StatusOK)
321 fl, _ := w.(http.Flusher)
322 write := func(s string) {
323 _, _ = w.Write([]byte(s))
324 if fl != nil {
325 fl.Flush()
326 }
327 }
328 write("data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"hel\"},\"finish_reason\":null}]}\n\n")
329 write("data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"lo\"},\"finish_reason\":\"stop\"}]}\n\n")
330 write("data: {\"choices\":[],\"usage\":{\"prompt_tokens\":8,\"completion_tokens\":2}}\n\n")
331 write("data: [DONE]\n\n")
332 }))
333 defer srv.Close()
334
335 c := NewOpenAI("x", srv.URL)
336 evs, err := c.Stream(context.Background(), Request{Model: "gpt-5"})
337 if err != nil {
338 t.Fatal(err)
339 }
340 var gotText string
341 var done EventDone
342 for ev := range evs {
343 switch e := ev.(type) {
344 case EventTextDelta:
345 gotText += e.Delta
346 case EventDone:
347 done = e
348 }
349 }
350 if gotText != "hello" {
351 t.Fatalf("text=%q", gotText)
352 }
353 if done.Stop != StopEnd {
354 t.Fatalf("stop=%v", done.Stop)
355 }
356}
357
358func TestDiscoverOpenRouter(t *testing.T) {
359 const body = `{"data":[
360 {"id":"x/full","pricing":{"prompt":"0.000003","completion":"0.000015"},
361 "context_length":200000,"top_provider":{"max_completion_tokens":64000},
362 "supported_parameters":["reasoning"]},
363 {"id":"x/fallback","top_provider":{"context_length":128000}},
364 {"id":""}]}`
365 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
366 _, _ = w.Write([]byte(body))
367 }))
368 defer srv.Close()
369
370 models, err := DiscoverOpenRouter(context.Background(), srv.URL)
371 if err != nil {
372 t.Fatal(err)
373 }
374 if len(models) != 2 { // empty id dropped
375 t.Fatalf("want 2 models, got %d", len(models))
376 }
377 // per-token USD -> per-1M; reasoning from supported_parameters.
378 if m := models[0]; m.Provider != "openrouter" || m.ContextWindow != 200000 ||
379 m.MaxOutput != 64000 || !m.Reasoning || m.PriceInput != 3 || m.PriceOutput != 15 {
380 t.Errorf("model[0]: %+v", m)
381 }
382 // context falls back to top_provider; no reasoning.
383 if m := models[1]; m.ContextWindow != 128000 || m.MaxOutput != 0 || m.Reasoning {
384 t.Errorf("model[1]: %+v", m)
385 }
386}
387
388func TestGPT56CatalogEntries(t *testing.T) {
389 cases := []struct {
390 provider string
391 id string
392 priceInput float64
393 priceOut float64
394 cacheRead float64
395 }{
396 {"openai", "gpt-5.6-sol", 5, 30, 0.5},
397 {"openai", "gpt-5.6-terra", 2.5, 15, 0.25},
398 {"openai-codex", "gpt-5.6-sol", 5, 30, 0.5},
399 {"openai-codex", "gpt-5.6-terra", 2.5, 15, 0.25},
400 }
401 for _, tc := range cases {
402 m, err := FindModel(tc.provider, tc.id)
403 if err != nil {
404 t.Fatal(err)
405 }
406 if m.ContextWindow != 1050000 || m.MaxOutput != 128000 || !m.Reasoning {
407 t.Fatalf("%s/%s limits: %+v", tc.provider, tc.id, m)
408 }
409 if m.PriceInput != tc.priceInput || m.PriceOutput != tc.priceOut || m.PriceCacheRead != tc.cacheRead {
410 t.Fatalf("%s/%s prices: %+v", tc.provider, tc.id, m)
411 }
412 }
413}
414
415// TestOpenAIOmitsZeroMaxTokens guards against sending max_tokens: 0 for
416// discovered models that don't advertise an output cap (MaxOutput == 0).
417func TestOpenAIOmitsZeroMaxTokens(t *testing.T) {
418 SetLiveModels([]Model{
419 {Provider: "openrouter", ID: "vendor/no-cap", DisplayName: "No Cap"},
420 {Provider: "openrouter", ID: "vendor/reason-no-cap", DisplayName: "Reason No Cap", Reasoning: true},
421 {Provider: "openrouter", ID: "vendor/capped", DisplayName: "Capped", MaxOutput: 4096},
422 })
423 defer SetLiveModels(nil)
424
425 c := NewOpenAI("x", "").(*openaiClient)
426
427 got, err := c.buildRequest(Request{Model: "vendor/no-cap"})
428 if err != nil {
429 t.Fatal(err)
430 }
431 if got.MaxTokens != nil {
432 t.Errorf("expected max_tokens omitted, got %d", *got.MaxTokens)
433 }
434
435 got, err = c.buildRequest(Request{Model: "vendor/reason-no-cap"})
436 if err != nil {
437 t.Fatal(err)
438 }
439 if got.MaxCompletionTok != nil {
440 t.Errorf("expected max_completion_tokens omitted, got %d", *got.MaxCompletionTok)
441 }
442
443 got, err = c.buildRequest(Request{Model: "vendor/capped"})
444 if err != nil {
445 t.Fatal(err)
446 }
447 if got.MaxTokens == nil || *got.MaxTokens != 4096 {
448 t.Errorf("expected max_tokens 4096, got %v", got.MaxTokens)
449 }
450}