| 1 |
package anthropic_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/anthropic" |
| 15 |
) |
| 16 |
|
| 17 |
func TestModelRequestSerialization(t *testing.T) { |
| 18 |
t.Run("uses structured output request body", func(t *testing.T) { |
| 19 |
var gotBody map[string]any |
| 20 |
var gotHeaders http.Header |
| 21 |
server := jsonServer(t, func(r *http.Request) any { |
| 22 |
gotHeaders = r.Header |
| 23 |
gotBody = requestBody(t, r) |
| 24 |
return textResponse(anthropicWrappedDone("ok")) |
| 25 |
}) |
| 26 |
defer server.Close() |
| 27 |
|
| 28 |
m := anthropic.NewModel(server.URL, "test-key", "claude-test", "sys prompt") |
| 29 |
if _, err := m.Query( |
| 30 |
context.Background(), |
| 31 |
[]clnkr.Message{{Role: "user", Content: "hello"}}, |
| 32 |
); err != nil { |
| 33 |
t.Fatalf("Query: %v", err) |
| 34 |
} |
| 35 |
|
| 36 |
if gotHeaders.Get("x-api-key") != "test-key" { |
| 37 |
t.Errorf("x-api-key = %q, want test-key", gotHeaders.Get("x-api-key")) |
| 38 |
} |
| 39 |
if gotHeaders.Get("anthropic-version") == "" { |
| 40 |
t.Error("missing anthropic-version header") |
| 41 |
} |
| 42 |
if gotBody["system"] != "sys prompt" { |
| 43 |
t.Errorf("system = %#v, want sys prompt", gotBody["system"]) |
| 44 |
} |
| 45 |
if gotBody["max_tokens"] != float64(4096) { |
| 46 |
t.Errorf("max_tokens = %#v, want 4096", gotBody["max_tokens"]) |
| 47 |
} |
| 48 |
if _, ok := gotBody["thinking"]; ok { |
| 49 |
t.Fatalf("thinking = %#v, want omitted", gotBody["thinking"]) |
| 50 |
} |
| 51 |
|
| 52 |
format := gotBody["output_config"].(map[string]any)["format"].(map[string]any) |
| 53 |
if format["type"] != "json_schema" { |
| 54 |
t.Fatalf("output_config.format.type = %#v, want json_schema", format["type"]) |
| 55 |
} |
| 56 |
schema := format["schema"].(map[string]any) |
| 57 |
if schemaContainsKey(schema, "maxItems") { |
| 58 |
t.Fatal("output_config.format.schema unexpectedly contains maxItems") |
| 59 |
} |
| 60 |
if !schemaContainsKey(schema, "minItems") { |
| 61 |
t.Fatal("output_config.format.schema unexpectedly omits minItems") |
| 62 |
} |
| 63 |
}) |
| 64 |
|
| 65 |
t.Run("QueryText returns plain text without output config", func(t *testing.T) { |
| 66 |
var gotBody map[string]any |
| 67 |
server := jsonServer(t, func(r *http.Request) any { |
| 68 |
gotBody = requestBody(t, r) |
| 69 |
return textResponse("Older work summarized.") |
| 70 |
}) |
| 71 |
defer server.Close() |
| 72 |
|
| 73 |
history := []clnkr.Message{ |
| 74 |
{Role: "user", Content: "first task"}, |
| 75 |
{Role: "assistant", Content: doneTurn("canonical transcript")}, |
| 76 |
} |
| 77 |
m := anthropic.NewModel(server.URL, "test-key", "claude-test", "sys prompt") |
| 78 |
summary, err := m.QueryText(context.Background(), history) |
| 79 |
if err != nil { |
| 80 |
t.Fatalf("QueryText: %v", err) |
| 81 |
} |
| 82 |
if summary != "Older work summarized." { |
| 83 |
t.Fatalf("summary = %q, want Older work summarized.", summary) |
| 84 |
} |
| 85 |
if outputCfg, ok := gotBody["output_config"]; ok && outputCfg != nil { |
| 86 |
t.Fatalf("output_config = %#v, want omitted", outputCfg) |
| 87 |
} |
| 88 |
if gotBody["max_tokens"] != float64(4096) { |
| 89 |
t.Fatalf("max_tokens = %#v, want 4096", gotBody["max_tokens"]) |
| 90 |
} |
| 91 |
if _, ok := gotBody["thinking"]; ok { |
| 92 |
t.Fatalf("thinking = %#v, want omitted", gotBody["thinking"]) |
| 93 |
} |
| 94 |
msgs := gotBody["messages"].([]any) |
| 95 |
if len(msgs) != len(history) { |
| 96 |
t.Fatalf("messages = %#v, want %d transcript messages", msgs, len(history)) |
| 97 |
} |
| 98 |
last := msgs[len(msgs)-1].(map[string]any) |
| 99 |
if got := last["content"]; got != doneTurn("canonical transcript") { |
| 100 |
t.Fatalf("last assistant content = %#v, want canonical transcript", got) |
| 101 |
} |
| 102 |
}) |
| 103 |
|
| 104 |
t.Run("QueryText classifies context window stop reason", func(t *testing.T) { |
| 105 |
server := jsonServer(t, func(r *http.Request) any { |
| 106 |
return map[string]any{ |
| 107 |
"stop_reason": "model_context_window_exceeded", |
| 108 |
"usage": map[string]any{ |
| 109 |
"input_tokens": 200000, |
| 110 |
"output_tokens": 1, |
| 111 |
}, |
| 112 |
"content": []map[string]any{ |
| 113 |
{"type": "text", "text": "partial summary"}, |
| 114 |
}, |
| 115 |
} |
| 116 |
}) |
| 117 |
defer server.Close() |
| 118 |
|
| 119 |
m := anthropic.NewModel(server.URL, "test-key", "claude-test", "sys prompt") |
| 120 |
_, err := m.QueryText(context.Background(), []clnkr.Message{{Role: "user", Content: "hi"}}) |
| 121 |
if !errors.Is(err, clnkr.ErrContextLengthExceeded) { |
| 122 |
t.Fatalf("QueryText error = %v, want ErrContextLengthExceeded", err) |
| 123 |
} |
| 124 |
if err == nil || !strings.Contains(err.Error(), "model_context_window_exceeded") { |
| 125 |
t.Fatalf("QueryText error = %v, want stop reason in error", err) |
| 126 |
} |
| 127 |
}) |
| 128 |
|
| 129 |
t.Run("serializes harness options", func(t *testing.T) { |
| 130 |
var gotBody map[string]any |
| 131 |
server := jsonServer(t, func(r *http.Request) any { |
| 132 |
gotBody = requestBody(t, r) |
| 133 |
return textResponse(anthropicWrappedDone("ok")) |
| 134 |
}) |
| 135 |
defer server.Close() |
| 136 |
|
| 137 |
m := anthropic.NewModelWithOptions( |
| 138 |
server.URL, |
| 139 |
"test-key", |
| 140 |
"claude-sonnet-4-20250514", |
| 141 |
"sys", |
| 142 |
anthropic.Options{ |
| 143 |
MaxTokens: 8000, |
| 144 |
ThinkingBudgetTokens: 2048, |
| 145 |
}, |
| 146 |
) |
| 147 |
if _, err := m.Query( |
| 148 |
context.Background(), |
| 149 |
[]clnkr.Message{{Role: "user", Content: "hello"}}, |
| 150 |
); err != nil { |
| 151 |
t.Fatalf("Query: %v", err) |
| 152 |
} |
| 153 |
if gotBody["max_tokens"] != float64(8000) { |
| 154 |
t.Fatalf("max_tokens = %#v, want 8000", gotBody["max_tokens"]) |
| 155 |
} |
| 156 |
thinking := gotBody["thinking"].(map[string]any) |
| 157 |
if got := thinking["type"]; got != "enabled" { |
| 158 |
t.Fatalf("thinking.type = %#v, want enabled", got) |
| 159 |
} |
| 160 |
if got := thinking["budget_tokens"]; got != float64(2048) { |
| 161 |
t.Fatalf("thinking.budget_tokens = %#v, want 2048", got) |
| 162 |
} |
| 163 |
}) |
| 164 |
|
| 165 |
t.Run("joins trailing slash base URL", func(t *testing.T) { |
| 166 |
var gotPath string |
| 167 |
server := jsonServer(t, func(r *http.Request) any { |
| 168 |
gotPath = r.URL.Path |
| 169 |
return textResponse(anthropicWrappedDone("ok")) |
| 170 |
}) |
| 171 |
defer server.Close() |
| 172 |
|
| 173 |
m := anthropic.NewModel(server.URL+"/", "test-key", "claude-test", "sys") |
| 174 |
if _, err := m.Query( |
| 175 |
context.Background(), |
| 176 |
[]clnkr.Message{{Role: "user", Content: "hi"}}, |
| 177 |
); err != nil { |
| 178 |
t.Fatalf("Query: %v", err) |
| 179 |
} |
| 180 |
if gotPath != "/v1/messages" { |
| 181 |
t.Errorf("path = %q, want /v1/messages", gotPath) |
| 182 |
} |
| 183 |
}) |
| 184 |
} |
| 185 |
|
| 186 |
func TestModelStructuredResponses(t *testing.T) { |
| 187 |
t.Run("returns canonical json text", func(t *testing.T) { |
| 188 |
server := jsonServer(t, func(r *http.Request) any { |
| 189 |
return response( |
| 190 |
50, |
| 191 |
30, |
| 192 |
map[string]any{"type": "text", "text": anthropicWrappedDone("hello back")}, |
| 193 |
) |
| 194 |
}) |
| 195 |
defer server.Close() |
| 196 |
|
| 197 |
m := anthropic.NewModel(server.URL, "test-key", "claude-test", "sys") |
| 198 |
resp, err := m.Query(context.Background(), []clnkr.Message{{Role: "user", Content: "hi"}}) |
| 199 |
if err != nil { |
| 200 |
t.Fatalf("Query: %v", err) |
| 201 |
} |
| 202 |
if got, want := mustCanonicalTurn(t, resp.Turn), doneTurn("hello back"); got != want { |
| 203 |
t.Errorf("content = %q, want %q", got, want) |
| 204 |
} |
| 205 |
if resp.ProtocolErr != nil { |
| 206 |
t.Fatalf("ProtocolErr = %v, want nil", resp.ProtocolErr) |
| 207 |
} |
| 208 |
if resp.Usage.InputTokens != 50 || resp.Usage.OutputTokens != 30 { |
| 209 |
t.Errorf("usage = %+v, want 50/30", resp.Usage) |
| 210 |
} |
| 211 |
}) |
| 212 |
|
| 213 |
t.Run("normalizes assistant history to wrapped provider json", func(t *testing.T) { |
| 214 |
var gotBody map[string]any |
| 215 |
server := jsonServer(t, func(r *http.Request) any { |
| 216 |
gotBody = requestBody(t, r) |
| 217 |
return textResponse(anthropicWrappedDone("ok")) |
| 218 |
}) |
| 219 |
defer server.Close() |
| 220 |
|
| 221 |
m := anthropic.NewModel(server.URL, "test-key", "claude-test", "sys") |
| 222 |
_, err := m.Query(context.Background(), []clnkr.Message{ |
| 223 |
{Role: "user", Content: "hi"}, |
| 224 |
{Role: "assistant", Content: doneTurn("hello back")}, |
| 225 |
}) |
| 226 |
if err != nil { |
| 227 |
t.Fatalf("Query: %v", err) |
| 228 |
} |
| 229 |
|
| 230 |
msgs := gotBody["messages"].([]any) |
| 231 |
last := msgs[len(msgs)-1].(map[string]any) |
| 232 |
if got, want := last["content"], anthropicWrappedDone("hello back"); got != want { |
| 233 |
t.Fatalf("assistant history content = %q, want %q", got, want) |
| 234 |
} |
| 235 |
}) |
| 236 |
|
| 237 |
t.Run("fails closed on missing or empty structured text payload", func(t *testing.T) { |
| 238 |
tests := []struct { |
| 239 |
name string |
| 240 |
content []map[string]string |
| 241 |
}{ |
| 242 |
{name: "no text block", content: []map[string]string{{"type": "tool_use"}}}, |
| 243 |
{name: "empty text block", content: []map[string]string{{"type": "text", "text": ""}}}, |
| 244 |
{ |
| 245 |
name: "multiple text blocks", |
| 246 |
content: []map[string]string{ |
| 247 |
{"type": "text", "text": doneTurn("one")}, |
| 248 |
{"type": "text", "text": doneTurn("two")}, |
| 249 |
}, |
| 250 |
}, |
| 251 |
} |
| 252 |
|
| 253 |
for _, tt := range tests { |
| 254 |
t.Run(tt.name, func(t *testing.T) { |
| 255 |
server := jsonServer(t, func(r *http.Request) any { |
| 256 |
return map[string]any{ |
| 257 |
"content": tt.content, |
| 258 |
"usage": map[string]int{"input_tokens": 1, "output_tokens": 1}, |
| 259 |
} |
| 260 |
}) |
| 261 |
defer server.Close() |
| 262 |
|
| 263 |
m := anthropic.NewModel(server.URL, "test-key", "claude-test", "sys") |
| 264 |
if _, err := m.Query( |
| 265 |
context.Background(), |
| 266 |
[]clnkr.Message{{Role: "user", Content: "hi"}}, |
| 267 |
); err == nil { |
| 268 |
t.Fatal("expected fail-closed error") |
| 269 |
} |
| 270 |
}) |
| 271 |
} |
| 272 |
}) |
| 273 |
|
| 274 |
t.Run( |
| 275 |
"returns raw payload plus protocol error on invalid structured payload", |
| 276 |
func(t *testing.T) { |
| 277 |
text := `{"turn":{"type":"done","bash":{"commands":[{"command":"rm -rf tmp","workdir":null}]},"question":null,"summary":"done","reasoning":null}}` |
| 278 |
server := jsonServer(t, func(r *http.Request) any { return textResponse(text) }) |
| 279 |
defer server.Close() |
| 280 |
|
| 281 |
m := anthropic.NewModel(server.URL, "test-key", "claude-test", "sys") |
| 282 |
resp, err := m.Query( |
| 283 |
context.Background(), |
| 284 |
[]clnkr.Message{{Role: "user", Content: "hi"}}, |
| 285 |
) |
| 286 |
if err != nil { |
| 287 |
t.Fatalf("Query: %v", err) |
| 288 |
} |
| 289 |
if resp.Raw != text { |
| 290 |
t.Fatalf("raw = %q, want %q", resp.Raw, text) |
| 291 |
} |
| 292 |
if !errors.Is(resp.ProtocolErr, clnkr.ErrInvalidJSON) { |
| 293 |
t.Fatalf("ProtocolErr = %v, want ErrInvalidJSON", resp.ProtocolErr) |
| 294 |
} |
| 295 |
}, |
| 296 |
) |
| 297 |
|
| 298 |
t.Run( |
| 299 |
"returns raw payload plus protocol error when output config is ignored", |
| 300 |
func(t *testing.T) { |
| 301 |
raw := doneTurn("ignored schema") |
| 302 |
server := jsonServer(t, func(r *http.Request) any { return textResponse(raw) }) |
| 303 |
defer server.Close() |
| 304 |
|
| 305 |
m := anthropic.NewModel(server.URL, "test-key", "claude-test", "sys") |
| 306 |
resp, err := m.Query( |
| 307 |
context.Background(), |
| 308 |
[]clnkr.Message{{Role: "user", Content: "hi"}}, |
| 309 |
) |
| 310 |
if err != nil { |
| 311 |
t.Fatalf("Query: %v", err) |
| 312 |
} |
| 313 |
if resp.Raw != raw { |
| 314 |
t.Fatalf("raw = %q, want %q", resp.Raw, raw) |
| 315 |
} |
| 316 |
if !errors.Is(resp.ProtocolErr, clnkr.ErrInvalidJSON) { |
| 317 |
t.Fatalf("ProtocolErr = %v, want ErrInvalidJSON", resp.ProtocolErr) |
| 318 |
} |
| 319 |
}, |
| 320 |
) |
| 321 |
} |
| 322 |
|
| 323 |
func TestModelErrors(t *testing.T) { |
| 324 |
tests := []struct { |
| 325 |
name string |
| 326 |
status int |
| 327 |
body any |
| 328 |
want string |
| 329 |
}{ |
| 330 |
{ |
| 331 |
name: "extracts error message from JSON error response", |
| 332 |
status: http.StatusTooManyRequests, |
| 333 |
body: map[string]any{ |
| 334 |
"type": "error", |
| 335 |
"error": map[string]any{ |
| 336 |
"type": "rate_limit_error", |
| 337 |
"message": "Rate limit exceeded", |
| 338 |
}, |
| 339 |
}, |
| 340 |
want: "api error (status 429): Rate limit exceeded", |
| 341 |
}, |
| 342 |
{ |
| 343 |
name: "falls back to raw body for non-JSON errors", |
| 344 |
status: http.StatusBadGateway, |
| 345 |
body: "Bad Gateway", |
| 346 |
want: "api error (status 502): Bad Gateway", |
| 347 |
}, |
| 348 |
} |
| 349 |
|
| 350 |
for _, tt := range tests { |
| 351 |
t.Run(tt.name, func(t *testing.T) { |
| 352 |
server := httptest.NewServer( |
| 353 |
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 354 |
w.WriteHeader(tt.status) |
| 355 |
switch body := tt.body.(type) { |
| 356 |
case string: |
| 357 |
_, _ = w.Write([]byte(body)) |
| 358 |
default: |
| 359 |
_ = json.NewEncoder(w).Encode(body) |
| 360 |
} |
| 361 |
}), |
| 362 |
) |
| 363 |
defer server.Close() |
| 364 |
|
| 365 |
m := anthropic.NewModel(server.URL, "test-key", "claude-test", "sys") |
| 366 |
_, err := m.Query(context.Background(), []clnkr.Message{{Role: "user", Content: "hi"}}) |
| 367 |
if err == nil { |
| 368 |
t.Fatal("expected API error") |
| 369 |
} |
| 370 |
if err.Error() != tt.want { |
| 371 |
t.Fatalf("error = %q, want %q", err.Error(), tt.want) |
| 372 |
} |
| 373 |
}) |
| 374 |
} |
| 375 |
} |
| 376 |
|
| 377 |
func TestModelClassifiesContextLengthErrors(t *testing.T) { |
| 378 |
tests := []struct { |
| 379 |
name string |
| 380 |
message string |
| 381 |
}{ |
| 382 |
{ |
| 383 |
name: "context window", |
| 384 |
message: "prompt is too long: 200000 tokens exceeds the context window", |
| 385 |
}, |
| 386 |
{ |
| 387 |
name: "prompt is too long", |
| 388 |
message: "prompt is too long", |
| 389 |
}, |
| 390 |
{ |
| 391 |
name: "too many tokens", |
| 392 |
message: "too many tokens in request", |
| 393 |
}, |
| 394 |
{ |
| 395 |
name: "context length", |
| 396 |
message: "request exceeds context length", |
| 397 |
}, |
| 398 |
} |
| 399 |
|
| 400 |
for _, tt := range tests { |
| 401 |
t.Run(tt.name, func(t *testing.T) { |
| 402 |
server := httptest.NewServer( |
| 403 |
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 404 |
w.WriteHeader(http.StatusBadRequest) |
| 405 |
_ = json.NewEncoder(w).Encode(map[string]any{ |
| 406 |
"error": map[string]any{"message": tt.message}, |
| 407 |
}) |
| 408 |
}), |
| 409 |
) |
| 410 |
defer server.Close() |
| 411 |
|
| 412 |
m := anthropic.NewModel(server.URL, "test-key", "claude-test", "sys") |
| 413 |
_, err := m.Query(context.Background(), []clnkr.Message{{Role: "user", Content: "hi"}}) |
| 414 |
if !errors.Is(err, clnkr.ErrContextLengthExceeded) { |
| 415 |
t.Fatalf("Query error = %v, want ErrContextLengthExceeded", err) |
| 416 |
} |
| 417 |
if err == nil || !strings.Contains(err.Error(), tt.message) { |
| 418 |
t.Fatalf("Query error = %v, want provider message %q", err, tt.message) |
| 419 |
} |
| 420 |
}) |
| 421 |
} |
| 422 |
} |
| 423 |
|
| 424 |
func TestModelClassifiesAnthropicContextLimitError(t *testing.T) { |
| 425 |
message := "input length and `max_tokens` exceed context limit: 188059 + 20000 > 200000" |
| 426 |
server := httptest.NewServer( |
| 427 |
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 428 |
w.WriteHeader(http.StatusBadRequest) |
| 429 |
_ = json.NewEncoder(w).Encode(map[string]any{ |
| 430 |
"error": map[string]any{"message": message}, |
| 431 |
}) |
| 432 |
}), |
| 433 |
) |
| 434 |
defer server.Close() |
| 435 |
|
| 436 |
m := anthropic.NewModel(server.URL, "test-key", "claude-test", "sys") |
| 437 |
_, err := m.Query(context.Background(), []clnkr.Message{{Role: "user", Content: "hi"}}) |
| 438 |
if !errors.Is(err, clnkr.ErrContextLengthExceeded) { |
| 439 |
t.Fatalf("Query error = %v, want ErrContextLengthExceeded", err) |
| 440 |
} |
| 441 |
if err == nil || !strings.Contains(err.Error(), message) { |
| 442 |
t.Fatalf("Query error = %v, want provider message %q", err, message) |
| 443 |
} |
| 444 |
} |
| 445 |
|
| 446 |
func TestModelClassifiesAnthropicContextWindowStopReason(t *testing.T) { |
| 447 |
server := jsonServer(t, func(r *http.Request) any { |
| 448 |
return map[string]any{ |
| 449 |
"stop_reason": "model_context_window_exceeded", |
| 450 |
"usage": map[string]any{ |
| 451 |
"input_tokens": 200000, |
| 452 |
"output_tokens": 1, |
| 453 |
}, |
| 454 |
"content": []map[string]any{ |
| 455 |
{"type": "text", "text": `{"type":"done","summary":"partial"}`}, |
| 456 |
}, |
| 457 |
} |
| 458 |
}) |
| 459 |
defer server.Close() |
| 460 |
|
| 461 |
m := anthropic.NewModel(server.URL, "test-key", "claude-test", "sys") |
| 462 |
_, err := m.Query(context.Background(), []clnkr.Message{{Role: "user", Content: "hi"}}) |
| 463 |
if !errors.Is(err, clnkr.ErrContextLengthExceeded) { |
| 464 |
t.Fatalf("Query error = %v, want ErrContextLengthExceeded", err) |
| 465 |
} |
| 466 |
if err == nil || !strings.Contains(err.Error(), "model_context_window_exceeded") { |
| 467 |
t.Fatalf("Query error = %v, want stop reason in error", err) |
| 468 |
} |
| 469 |
} |
| 470 |
|
| 471 |
func TestModelDoesNotClassifyAnthropicRateLimitTokenWordingAsContextLength(t *testing.T) { |
| 472 |
tests := []string{ |
| 473 |
"rate limit exceeded: too many tokens per minute", |
| 474 |
"too many requests: token quota exhausted", |
| 475 |
"throttling error: too many tokens", |
| 476 |
} |
| 477 |
|
| 478 |
for _, message := range tests { |
| 479 |
t.Run(message, func(t *testing.T) { |
| 480 |
server := httptest.NewServer( |
| 481 |
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 482 |
w.WriteHeader(http.StatusBadRequest) |
| 483 |
_ = json.NewEncoder(w).Encode(map[string]any{ |
| 484 |
"error": map[string]any{"message": message}, |
| 485 |
}) |
| 486 |
}), |
| 487 |
) |
| 488 |
defer server.Close() |
| 489 |
|
| 490 |
m := anthropic.NewModel(server.URL, "test-key", "claude-test", "sys") |
| 491 |
_, err := m.Query(context.Background(), []clnkr.Message{{Role: "user", Content: "hi"}}) |
| 492 |
if errors.Is(err, clnkr.ErrContextLengthExceeded) { |
| 493 |
t.Fatalf("Query error = %v, did not want ErrContextLengthExceeded", err) |
| 494 |
} |
| 495 |
if err == nil || !strings.Contains(err.Error(), message) { |
| 496 |
t.Fatalf("Query error = %v, want provider message %q", err, message) |
| 497 |
} |
| 498 |
}) |
| 499 |
} |
| 500 |
} |
| 501 |
|
| 502 |
func TestModelToolCalls(t *testing.T) { |
| 503 |
var gotBody map[string]any |
| 504 |
server := jsonServer(t, func(r *http.Request) any { |
| 505 |
gotBody = requestBody(t, r) |
| 506 |
return response(3, 4, |
| 507 |
toolUse("toolu_1", "pwd", nil), |
| 508 |
toolUse("toolu_2", "git status", nil), |
| 509 |
) |
| 510 |
}) |
| 511 |
defer server.Close() |
| 512 |
|
| 513 |
m := anthropic.NewModelWithOptions( |
| 514 |
server.URL, |
| 515 |
"test-key", |
| 516 |
"claude-test", |
| 517 |
"sys prompt", |
| 518 |
anthropic.Options{UseBashToolCalls: true}, |
| 519 |
) |
| 520 |
resp, err := m.Query(context.Background(), []clnkr.Message{{Role: "user", Content: "where"}}) |
| 521 |
if err != nil { |
| 522 |
t.Fatalf("Query: %v", err) |
| 523 |
} |
| 524 |
tools := gotBody["tools"].([]any) |
| 525 |
if len(tools) != 1 { |
| 526 |
t.Fatalf("tools = %#v, want one bash tool", tools) |
| 527 |
} |
| 528 |
tool := tools[0].(map[string]any) |
| 529 |
if tool["name"] != "bash" { |
| 530 |
t.Fatalf("tool = %#v, want bash", tool) |
| 531 |
} |
| 532 |
schema := tool["input_schema"].(map[string]any) |
| 533 |
if schema["additionalProperties"] != false { |
| 534 |
t.Fatalf("additionalProperties = %#v, want false", schema["additionalProperties"]) |
| 535 |
} |
| 536 |
turn := resp.Turn.(*clnkr.ActTurn) |
| 537 |
if got := len(turn.Bash.Commands); got != 2 { |
| 538 |
t.Fatalf("commands = %d, want 2", got) |
| 539 |
} |
| 540 |
if got := turn.Bash.Commands[0]; got.ID != "toolu_1" || got.Command != "pwd" { |
| 541 |
t.Fatalf("first command = %#v, want provider ID and command", got) |
| 542 |
} |
| 543 |
if got := turn.Bash.Commands[1]; got.ID != "toolu_2" || got.Command != "git status" { |
| 544 |
t.Fatalf("second command = %#v, want provider ID and command", got) |
| 545 |
} |
| 546 |
if len(resp.BashToolCalls) != 2 || resp.BashToolCalls[0].ID != "toolu_1" || |
| 547 |
resp.BashToolCalls[1].ID != "toolu_2" { |
| 548 |
t.Fatalf("BashToolCalls = %#v", resp.BashToolCalls) |
| 549 |
} |
| 550 |
} |
| 551 |
|
| 552 |
func TestModelToolCallsAllowsTextAlongsideToolUse(t *testing.T) { |
| 553 |
server := jsonServer(t, func(r *http.Request) any { |
| 554 |
return response(3, 4, |
| 555 |
map[string]any{"type": "text", "text": "I will inspect the working directory first."}, |
| 556 |
toolUse("toolu_1", "pwd", nil), |
| 557 |
) |
| 558 |
}) |
| 559 |
defer server.Close() |
| 560 |
|
| 561 |
m := anthropic.NewModelWithOptions( |
| 562 |
server.URL, |
| 563 |
"test-key", |
| 564 |
"claude-test", |
| 565 |
"sys prompt", |
| 566 |
anthropic.Options{UseBashToolCalls: true}, |
| 567 |
) |
| 568 |
resp, err := m.Query(context.Background(), []clnkr.Message{{Role: "user", Content: "where"}}) |
| 569 |
if err != nil { |
| 570 |
t.Fatalf("Query: %v", err) |
| 571 |
} |
| 572 |
if resp.ProtocolErr != nil { |
| 573 |
t.Fatalf("ProtocolErr = %v, want nil", resp.ProtocolErr) |
| 574 |
} |
| 575 |
turn := resp.Turn.(*clnkr.ActTurn) |
| 576 |
if got := turn.Reasoning; got != "I will inspect the working directory first." { |
| 577 |
t.Fatalf("Reasoning = %q, want text block", got) |
| 578 |
} |
| 579 |
if got := turn.Bash.Commands[0]; got.ID != "toolu_1" || got.Command != "pwd" { |
| 580 |
t.Fatalf("command = %#v, want provider ID and command", got) |
| 581 |
} |
| 582 |
} |
| 583 |
|
| 584 |
func TestModelToolCallsReplayToolMessagesWithoutDuplicateText(t *testing.T) { |
| 585 |
var gotMessages []any |
| 586 |
server := jsonServer(t, func(r *http.Request) any { |
| 587 |
gotMessages = requestBody(t, r)["messages"].([]any) |
| 588 |
return textResponse(anthropicWrappedDone("ok")) |
| 589 |
}) |
| 590 |
defer server.Close() |
| 591 |
|
| 592 |
m := anthropic.NewModelWithOptions( |
| 593 |
server.URL, |
| 594 |
"test-key", |
| 595 |
"claude-test", |
| 596 |
"sys prompt", |
| 597 |
anthropic.Options{UseBashToolCalls: true}, |
| 598 |
) |
| 599 |
_, err := m.Query(context.Background(), []clnkr.Message{ |
| 600 |
{ |
| 601 |
Role: "assistant", |
| 602 |
Content: `{"type":"act","bash":{"commands":[{"command":"pwd","workdir":null}]}}`, |
| 603 |
BashToolCalls: []clnkr.BashToolCall{{ID: "toolu_1", Command: "pwd"}}, |
| 604 |
}, |
| 605 |
{ |
| 606 |
Role: "user", |
| 607 |
Content: "payload", |
| 608 |
BashToolResult: &clnkr.BashToolResult{ID: "toolu_1", Content: "payload"}, |
| 609 |
}, |
| 610 |
}) |
| 611 |
if err != nil { |
| 612 |
t.Fatalf("Query: %v", err) |
| 613 |
} |
| 614 |
if len(gotMessages) != 2 { |
| 615 |
t.Fatalf("messages = %#v, want tool_use and tool_result", gotMessages) |
| 616 |
} |
| 617 |
firstContent := gotMessages[0].(map[string]any)["content"].([]any) |
| 618 |
secondContent := gotMessages[1].(map[string]any)["content"].([]any) |
| 619 |
if firstContent[0].(map[string]any)["type"] != "tool_use" { |
| 620 |
t.Fatalf("first content = %#v, want tool_use", firstContent) |
| 621 |
} |
| 622 |
if secondContent[0].(map[string]any)["type"] != "tool_result" || |
| 623 |
secondContent[0].(map[string]any)["content"] != "payload" { |
| 624 |
t.Fatalf("second content = %#v, want tool_result payload", secondContent) |
| 625 |
} |
| 626 |
} |
| 627 |
|
| 628 |
func TestModelToolCallsReplayConsecutiveToolResultsTogether(t *testing.T) { |
| 629 |
var gotMessages []any |
| 630 |
server := jsonServer(t, func(r *http.Request) any { |
| 631 |
gotMessages = requestBody(t, r)["messages"].([]any) |
| 632 |
return textResponse(anthropicWrappedDone("ok")) |
| 633 |
}) |
| 634 |
defer server.Close() |
| 635 |
|
| 636 |
m := anthropic.NewModelWithOptions( |
| 637 |
server.URL, |
| 638 |
"test-key", |
| 639 |
"claude-test", |
| 640 |
"sys prompt", |
| 641 |
anthropic.Options{UseBashToolCalls: true}, |
| 642 |
) |
| 643 |
_, err := m.Query(context.Background(), []clnkr.Message{ |
| 644 |
{ |
| 645 |
Role: "assistant", |
| 646 |
Content: `{"type":"act","bash":{"commands":[{"command":"pwd","workdir":null},{"command":"false","workdir":null}]}}`, |
| 647 |
BashToolCalls: []clnkr.BashToolCall{ |
| 648 |
{ID: "toolu_1", Command: "pwd"}, |
| 649 |
{ID: "toolu_2", Command: "false"}, |
| 650 |
}, |
| 651 |
}, |
| 652 |
{ |
| 653 |
Role: "user", |
| 654 |
Content: "payload 1", |
| 655 |
BashToolResult: &clnkr.BashToolResult{ID: "toolu_1", Content: "payload 1"}, |
| 656 |
}, |
| 657 |
{ |
| 658 |
Role: "user", |
| 659 |
Content: "payload 2", |
| 660 |
BashToolResult: &clnkr.BashToolResult{ |
| 661 |
ID: "toolu_2", |
| 662 |
Content: "payload 2", |
| 663 |
IsError: true, |
| 664 |
}, |
| 665 |
}, |
| 666 |
}) |
| 667 |
if err != nil { |
| 668 |
t.Fatalf("Query: %v", err) |
| 669 |
} |
| 670 |
if len(gotMessages) != 2 { |
| 671 |
t.Fatalf( |
| 672 |
"messages = %#v, want assistant tool_use and one user tool_result message", |
| 673 |
gotMessages, |
| 674 |
) |
| 675 |
} |
| 676 |
results := gotMessages[1].(map[string]any)["content"].([]any) |
| 677 |
if len(results) != 2 { |
| 678 |
t.Fatalf("second content = %#v, want two tool_result blocks", results) |
| 679 |
} |
| 680 |
first := results[0].(map[string]any) |
| 681 |
second := results[1].(map[string]any) |
| 682 |
if first["tool_use_id"] != "toolu_1" || first["content"] != "payload 1" { |
| 683 |
t.Fatalf("first tool result = %#v", first) |
| 684 |
} |
| 685 |
if second["tool_use_id"] != "toolu_2" || second["content"] != "payload 2" || |
| 686 |
second["is_error"] != true { |
| 687 |
t.Fatalf("second tool result = %#v", second) |
| 688 |
} |
| 689 |
} |
| 690 |
|
| 691 |
func TestModelQueryFinalOmitsBashTool(t *testing.T) { |
| 692 |
var gotBody map[string]any |
| 693 |
server := jsonServer(t, func(r *http.Request) any { |
| 694 |
gotBody = requestBody(t, r) |
| 695 |
return textResponse(anthropicWrappedDone("final")) |
| 696 |
}) |
| 697 |
defer server.Close() |
| 698 |
|
| 699 |
m := anthropic.NewModelWithOptions( |
| 700 |
server.URL, |
| 701 |
"test-key", |
| 702 |
"claude-test", |
| 703 |
"sys prompt", |
| 704 |
anthropic.Options{UseBashToolCalls: true}, |
| 705 |
) |
| 706 |
if _, err := m.QueryFinal( |
| 707 |
context.Background(), |
| 708 |
[]clnkr.Message{{Role: "user", Content: "summarize"}}, |
| 709 |
); err != nil { |
| 710 |
t.Fatalf("QueryFinal: %v", err) |
| 711 |
} |
| 712 |
if _, ok := gotBody["tools"]; ok { |
| 713 |
t.Fatalf("tools = %#v, want omitted", gotBody["tools"]) |
| 714 |
} |
| 715 |
schema := gotBody["output_config"].(map[string]any)["format"].(map[string]any)["schema"].(map[string]any) |
| 716 |
choices := schema["properties"].(map[string]any)["turn"].(map[string]any)["anyOf"].([]any) |
| 717 |
if len(choices) != 1 { |
| 718 |
t.Fatalf("final schema choices = %#v, want done only", choices) |
| 719 |
} |
| 720 |
} |
| 721 |
|
| 722 |
func TestModelQueryFinalClassifiesContextWindowStopReason(t *testing.T) { |
| 723 |
server := jsonServer(t, func(r *http.Request) any { |
| 724 |
return map[string]any{ |
| 725 |
"stop_reason": "model_context_window_exceeded", |
| 726 |
"usage": map[string]any{ |
| 727 |
"input_tokens": 200000, |
| 728 |
"output_tokens": 1, |
| 729 |
}, |
| 730 |
"content": []map[string]any{ |
| 731 |
{"type": "text", "text": anthropicWrappedDone("final")}, |
| 732 |
}, |
| 733 |
} |
| 734 |
}) |
| 735 |
defer server.Close() |
| 736 |
|
| 737 |
m := anthropic.NewModel(server.URL, "test-key", "claude-test", "sys prompt") |
| 738 |
_, err := m.QueryFinal( |
| 739 |
context.Background(), |
| 740 |
[]clnkr.Message{{Role: "user", Content: "summarize"}}, |
| 741 |
) |
| 742 |
if !errors.Is(err, clnkr.ErrContextLengthExceeded) { |
| 743 |
t.Fatalf("QueryFinal error = %v, want ErrContextLengthExceeded", err) |
| 744 |
} |
| 745 |
if err == nil || !strings.Contains(err.Error(), "model_context_window_exceeded") { |
| 746 |
t.Fatalf("QueryFinal error = %v, want stop reason in error", err) |
| 747 |
} |
| 748 |
} |
| 749 |
|
| 750 |
func jsonServer(t *testing.T, handle func(*http.Request) any) *httptest.Server { |
| 751 |
t.Helper() |
| 752 |
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 753 |
_ = json.NewEncoder(w).Encode(handle(r)) |
| 754 |
})) |
| 755 |
} |
| 756 |
|
| 757 |
func requestBody(t *testing.T, r *http.Request) map[string]any { |
| 758 |
t.Helper() |
| 759 |
body, err := io.ReadAll(r.Body) |
| 760 |
if err != nil { |
| 761 |
t.Fatalf("ReadAll request body: %v", err) |
| 762 |
} |
| 763 |
var got map[string]any |
| 764 |
if err := json.Unmarshal(body, &got); err != nil { |
| 765 |
t.Fatalf("Unmarshal request body: %v", err) |
| 766 |
} |
| 767 |
return got |
| 768 |
} |
| 769 |
|
| 770 |
func textResponse(text string) map[string]any { |
| 771 |
return response(1, 1, map[string]any{"type": "text", "text": text}) |
| 772 |
} |
| 773 |
|
| 774 |
func response(inputTokens, outputTokens int, content ...map[string]any) map[string]any { |
| 775 |
return map[string]any{ |
| 776 |
"content": content, |
| 777 |
"usage": map[string]int{"input_tokens": inputTokens, "output_tokens": outputTokens}, |
| 778 |
} |
| 779 |
} |
| 780 |
|
| 781 |
func toolUse(id, command string, workdir any) map[string]any { |
| 782 |
return map[string]any{ |
| 783 |
"type": "tool_use", |
| 784 |
"id": id, |
| 785 |
"name": "bash", |
| 786 |
"input": map[string]any{"command": command, "workdir": workdir}, |
| 787 |
} |
| 788 |
} |
| 789 |
|
| 790 |
func doneTurn(summary string) string { |
| 791 |
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":[]}` |
| 792 |
} |
| 793 |
|
| 794 |
func anthropicWrappedDone(summary string) string { |
| 795 |
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}}` |
| 796 |
} |
| 797 |
|
| 798 |
func mustCanonicalTurn(t *testing.T, turn clnkr.Turn) string { |
| 799 |
t.Helper() |
| 800 |
raw, err := clnkr.CanonicalTurnJSON(turn) |
| 801 |
if err != nil { |
| 802 |
t.Fatalf("CanonicalTurnJSON: %v", err) |
| 803 |
} |
| 804 |
return raw |
| 805 |
} |
| 806 |
|
| 807 |
func schemaContainsKey(node any, key string) bool { |
| 808 |
switch v := node.(type) { |
| 809 |
case map[string]any: |
| 810 |
if _, ok := v[key]; ok { |
| 811 |
return true |
| 812 |
} |
| 813 |
for _, child := range v { |
| 814 |
if schemaContainsKey(child, key) { |
| 815 |
return true |
| 816 |
} |
| 817 |
} |
| 818 |
case []any: |
| 819 |
for _, child := range v { |
| 820 |
if schemaContainsKey(child, key) { |
| 821 |
return true |
| 822 |
} |
| 823 |
} |
| 824 |
} |
| 825 |
|
| 826 |
return false |
| 827 |
} |