diff --git a/translate_anthropic.go b/translate_anthropic.go index c1be72a..c1908e4 100644 --- a/translate_anthropic.go +++ b/translate_anthropic.go @@ -3,6 +3,7 @@ package traefikllmgateway import ( "encoding/json" "fmt" + "math" "strconv" "strings" "unicode/utf8" @@ -100,12 +101,20 @@ func toFloat64(v any) (float64, bool) { } // toInt64 is toFloat64 truncated to an integer, for fields (max_tokens) -// Anthropic's API requires as a JSON integer. +// Anthropic's API requires as a JSON integer. A value outside the int64 +// range saturates, because Go leaves that conversion implementation-defined; +// NaN is refused. func toInt64(v any) (int64, bool) { f, ok := toFloat64(v) - if !ok { + if !ok || math.IsNaN(f) { return 0, false } + switch { + case f >= math.MaxInt64: + return math.MaxInt64, true + case f <= math.MinInt64: + return math.MinInt64, true + } return int64(f), true } diff --git a/translate_anthropic_test.go b/translate_anthropic_test.go index 0286434..77a7475 100644 --- a/translate_anthropic_test.go +++ b/translate_anthropic_test.go @@ -5,6 +5,7 @@ import ( "context" "encoding/json" "errors" + "math" "net/http" "net/http/httptest" "os" @@ -1189,3 +1190,36 @@ func TestAppendJSONStringMatchesMarshal(t *testing.T) { } } } + +// TestToInt64_Saturates pins toInt64's defined behaviour for out-of-range +// and non-finite floats, which Go otherwise leaves implementation-defined. +func TestToInt64_Saturates(t *testing.T) { + t.Parallel() + tests := []struct { + in any + name string + want int64 + wantOK bool + }{ + {name: "fraction truncates toward zero", in: 42.9, want: 42, wantOK: true}, + {name: "negative fraction truncates toward zero", in: -3.7, want: -3, wantOK: true}, + {name: "zero", in: 0.0, want: 0, wantOK: true}, + {name: "int passes through", in: 7, want: 7, wantOK: true}, + {name: "huge positive saturates", in: 1e300, want: math.MaxInt64, wantOK: true}, + {name: "huge negative saturates", in: -1e300, want: math.MinInt64, wantOK: true}, + {name: "just above int64 saturates", in: 9.3e18, want: math.MaxInt64, wantOK: true}, + {name: "positive infinity saturates", in: math.Inf(1), want: math.MaxInt64, wantOK: true}, + {name: "negative infinity saturates", in: math.Inf(-1), want: math.MinInt64, wantOK: true}, + {name: "NaN is refused", in: math.NaN(), want: 0, wantOK: false}, + {name: "string is refused", in: "5", want: 0, wantOK: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got, ok := toInt64(tt.in) + if got != tt.want || ok != tt.wantOK { + t.Errorf("toInt64(%v) = (%d, %v), want (%d, %v)", tt.in, got, ok, tt.want, tt.wantOK) + } + }) + } +}