fix(translator,executor): preserve native Claude max_tokens and remove Vertex silent cap

- Replace ClaudePositiveMaxTokens with ClaudeMaxTokensRaw to forward raw JSON numeric max_tokens verbatim (including 0 for Claude cache pre-warming and >65536 values for Gemini 4 long decodes) without silent filtering, truncation, or clamping.
- Remove silent maxOutputTokens capping from GeminiVertexExecutor so Vertex requests (including Gemini 4 long decodes up to 1,048,576 tokens) follow official Vertex API semantics.
- Avoid intermediate slice allocation in ClaudeStopSequences with ForEach.
- Synchronize captured request bodies via buffered channels in claude_generation_config_regression_test.go and add end-to-end gemini-interactions coverage.
This commit is contained in:
sususu98
2026-11-24 00:16:32 +08:00
parent ac415c083a
commit 62c419e049
11 changed files with 271 additions and 119 deletions

View File

@@ -154,7 +154,7 @@ func TestAntigravityClaudeFormatOutputConfigAndStopSequences(t *testing.T) {
})
}
func TestGeminiAndVertexExecutors_ClaudeGenerationConfigAndMaxTokensCap(t *testing.T) {
func TestGeminiAndVertexExecutors_ClaudeGenerationConfigAndMaxTokens(t *testing.T) {
claudePayload := []byte(`{
"model": "gemini-3.1-pro-preview",
"max_tokens": 500000,
@@ -215,6 +215,17 @@ func TestGeminiAndVertexExecutors_ClaudeGenerationConfigAndMaxTokensCap(t *testi
return text.String()
}
readCapturedBody := func(t *testing.T, captured <-chan []byte) []byte {
t.Helper()
select {
case body := <-captured:
return body
default:
t.Fatal("expected upstream request body to be captured")
return nil
}
}
t.Run("gemini executor maps fields and caps max_tokens", func(t *testing.T) {
for _, stream := range []bool{false, true} {
name := "execute"
@@ -222,7 +233,7 @@ func TestGeminiAndVertexExecutors_ClaudeGenerationConfigAndMaxTokensCap(t *testi
name = "stream"
}
t.Run(name, func(t *testing.T) {
var upstreamBody []byte
captured := make(chan []byte, 1)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, errRead := io.ReadAll(r.Body)
if errRead != nil {
@@ -230,7 +241,10 @@ func TestGeminiAndVertexExecutors_ClaudeGenerationConfigAndMaxTokensCap(t *testi
w.WriteHeader(http.StatusInternalServerError)
return
}
upstreamBody = append([]byte(nil), body...)
select {
case captured <- append([]byte(nil), body...):
default:
}
if stream {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte("data: " + geminiResp + "\n\n"))
@@ -265,12 +279,127 @@ func TestGeminiAndVertexExecutors_ClaudeGenerationConfigAndMaxTokensCap(t *testi
t.Fatalf("response text = %q, want {\"answer\":\"ok\"}; payload=%s", got, resp.Payload)
}
}
assertOutbound(t, upstreamBody, 65536)
assertOutbound(t, readCapturedBody(t, captured), 65536)
})
}
})
t.Run("vertex executor maps fields, caps max_tokens, and keeps payload override final", func(t *testing.T) {
t.Run("gemini interactions executor maps fields without silently capping max_tokens, and keeps payload override final", func(t *testing.T) {
interactionsResp := `{"id":"interaction_1","object":"interaction","status":"completed","steps":[{"type":"model_output","content":[{"type":"text","text":"{\"answer\":\"ok\"}"}]}],"usage":{"total_input_tokens":1,"total_output_tokens":1,"total_tokens":2}}`
interactionsSSE := strings.Join([]string{
`event: interaction.created`,
`data: {"event_type":"interaction.created","interaction":{"id":"interaction_1","model":"gemini-4-neon"}}`,
``,
`event: step.start`,
`data: {"event_type":"step.start","index":0,"step":{"type":"model_output"}}`,
``,
`event: step.delta`,
`data: {"event_type":"step.delta","index":0,"delta":{"type":"text","text":"{\"answer\":\"ok\"}"}}`,
``,
`event: step.stop`,
`data: {"event_type":"step.stop","index":0}`,
``,
`event: interaction.completed`,
`data: {"event_type":"interaction.completed","interaction":{"id":"interaction_1","model":"gemini-4-neon","usage":{"total_input_tokens":1,"total_output_tokens":1}}}`,
``,
`event: done`,
`data: [DONE]`,
``,
``,
}, "\n")
for _, tc := range []struct {
name string
stream bool
override int64
wantMax int64
}{
{name: "execute_preserves_requested_max", stream: false, wantMax: 500000},
{name: "stream_preserves_requested_max", stream: true, wantMax: 500000},
{name: "execute_payload_override_final", stream: false, override: 123456, wantMax: 123456},
{name: "stream_payload_override_final", stream: true, override: 123456, wantMax: 123456},
} {
t.Run(tc.name, func(t *testing.T) {
captured := make(chan []byte, 1)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, errRead := io.ReadAll(r.Body)
if errRead != nil {
t.Errorf("read request body: %v", errRead)
w.WriteHeader(http.StatusInternalServerError)
return
}
select {
case captured <- append([]byte(nil), body...):
default:
}
if tc.stream {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = io.WriteString(w, interactionsSSE)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, interactionsResp)
}))
defer server.Close()
cfg := &config.Config{}
if tc.override > 0 {
cfg.Payload = config.PayloadConfig{
Override: []config.PayloadRule{{
Models: []config.PayloadModelRule{{Name: "gemini-4-neon", Protocol: "interactions"}},
Params: map[string]any{"generation_config.max_output_tokens": tc.override},
}},
}
}
exec := NewGeminiInteractionsExecutor(cfg)
auth := &cliproxyauth.Auth{
Provider: "gemini-interactions",
Attributes: map[string]string{
"api_key": "test-key",
"base_url": server.URL,
},
}
req := cliproxyexecutor.Request{Model: "gemini-4-neon", Payload: claudePayload}
opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, ResponseFormat: sdktranslator.FormatClaude, Stream: tc.stream}
if tc.stream {
res, errStream := exec.ExecuteStream(context.Background(), auth, req, opts)
if errStream != nil {
t.Fatalf("ExecuteStream() error = %v", errStream)
}
if got := collectClaudeStreamText(t, res.Chunks); got != `{"answer":"ok"}` {
t.Fatalf("stream text = %q, want {\"answer\":\"ok\"}", got)
}
} else {
resp, errExec := exec.Execute(context.Background(), auth, req, opts)
if errExec != nil {
t.Fatalf("Execute() error = %v", errExec)
}
if got := ojson.GetBytes(resp.Payload, "content.0.text").String(); got != `{"answer":"ok"}` {
t.Fatalf("response text = %q, want {\"answer\":\"ok\"}; payload=%s", got, resp.Payload)
}
}
upstreamBody := readCapturedBody(t, captured)
if got := ojson.GetBytes(upstreamBody, "generation_config.max_output_tokens").Int(); got != tc.wantMax {
t.Fatalf("generation_config.max_output_tokens = %d, want %d; body=%s", got, tc.wantMax, upstreamBody)
}
if got := ojson.GetBytes(upstreamBody, "generation_config.stop_sequences.0").String(); got != "STOP_NOW" {
t.Fatalf("generation_config.stop_sequences[0] = %q, want STOP_NOW; body=%s", got, upstreamBody)
}
if got := ojson.GetBytes(upstreamBody, "response_format.type").String(); got != "text" {
t.Fatalf("response_format.type = %q, want text; body=%s", got, upstreamBody)
}
if got := ojson.GetBytes(upstreamBody, "response_format.mime_type").String(); got != "application/json" {
t.Fatalf("response_format.mime_type = %q, want application/json; body=%s", got, upstreamBody)
}
if got := ojson.GetBytes(upstreamBody, "response_format.schema.properties.answer.type").String(); got != "string" {
t.Fatalf("response_format.schema.properties.answer.type = %q, want string; body=%s", got, upstreamBody)
}
})
}
})
t.Run("vertex executor maps fields without silently capping max_tokens, and keeps payload override final", func(t *testing.T) {
for _, authMode := range []string{"api_key", "service_account"} {
for _, tc := range []struct {
name string
@@ -278,13 +407,13 @@ func TestGeminiAndVertexExecutors_ClaudeGenerationConfigAndMaxTokensCap(t *testi
override int64
wantMax int64
}{
{name: "execute_capped", stream: false, wantMax: 65536},
{name: "stream_capped", stream: true, wantMax: 65536},
{name: "execute_preserves_requested_max", stream: false, wantMax: 500000},
{name: "stream_preserves_requested_max", stream: true, wantMax: 500000},
{name: "execute_payload_override_final", stream: false, override: 123456, wantMax: 123456},
{name: "stream_payload_override_final", stream: true, override: 123456, wantMax: 123456},
} {
t.Run(authMode+"/"+tc.name, func(t *testing.T) {
var upstreamBody []byte
captured := make(chan []byte, 1)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/token" {
w.Header().Set("Content-Type", "application/json")
@@ -297,7 +426,10 @@ func TestGeminiAndVertexExecutors_ClaudeGenerationConfigAndMaxTokensCap(t *testi
w.WriteHeader(http.StatusInternalServerError)
return
}
upstreamBody = append([]byte(nil), body...)
select {
case captured <- append([]byte(nil), body...):
default:
}
if tc.stream {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte("data: " + geminiResp + "\n\n"))
@@ -364,7 +496,7 @@ func TestGeminiAndVertexExecutors_ClaudeGenerationConfigAndMaxTokensCap(t *testi
t.Fatalf("response text = %q, want {\"answer\":\"ok\"}; payload=%s", got, resp.Payload)
}
}
assertOutbound(t, upstreamBody, tc.wantMax)
assertOutbound(t, readCapturedBody(t, captured), tc.wantMax)
})
}
}

View File

@@ -1296,10 +1296,6 @@ func capGeminiMaxOutputTokens(body []byte, modelName string) []byte {
}
func capGeminiMaxOutputTokensDoc(doc *ojson.Doc, modelName string) bool {
return capMaxOutputTokensForProviderDoc(doc, modelName, "gemini")
}
func capMaxOutputTokensForProviderDoc(doc *ojson.Doc, modelName, provider string) bool {
if doc == nil {
return false
}
@@ -1307,7 +1303,7 @@ func capMaxOutputTokensForProviderDoc(doc *ojson.Doc, modelName, provider string
if !maxOut.Exists() || maxOut.Type != ojson.Number {
return false
}
modelInfo := registry.LookupModelInfo(modelName, provider)
modelInfo := registry.LookupModelInfo(modelName, "gemini")
if modelInfo == nil {
return false
}

View File

@@ -489,7 +489,6 @@ func (e *GeminiVertexExecutor) executeWithServiceAccount(ctx context.Context, au
return resp, err
}
capMaxOutputTokensForProviderDoc(doc, baseModel, "vertex")
fixGeminiImageAspectRatioDoc(baseModel, doc)
helps.SetStringIfDifferentDoc(doc, "model", baseModel)
internalsignature.SanitizeGeminiRequestThoughtSignaturesDoc(doc, "contents")
@@ -684,7 +683,6 @@ func (e *GeminiVertexExecutor) executeWithAPIKey(ctx context.Context, auth *clip
return resp, err
}
capMaxOutputTokensForProviderDoc(doc, baseModel, "vertex")
fixGeminiImageAspectRatioDoc(baseModel, doc)
helps.SetStringIfDifferentDoc(doc, "model", baseModel)
internalsignature.SanitizeGeminiRequestThoughtSignaturesDoc(doc, "contents")
@@ -868,7 +866,6 @@ func (e *GeminiVertexExecutor) executeStreamWithServiceAccount(ctx context.Conte
return nil, err
}
capMaxOutputTokensForProviderDoc(doc, baseModel, "vertex")
fixGeminiImageAspectRatioDoc(baseModel, doc)
helps.SetStringIfDifferentDoc(doc, "model", baseModel)
internalsignature.SanitizeGeminiRequestThoughtSignaturesDoc(doc, "contents")
@@ -1288,7 +1285,6 @@ func (e *GeminiVertexExecutor) executeStreamWithAPIKey(ctx context.Context, auth
return nil, err
}
capMaxOutputTokensForProviderDoc(doc, baseModel, "vertex")
fixGeminiImageAspectRatioDoc(baseModel, doc)
helps.SetStringIfDifferentDoc(doc, "model", baseModel)
internalsignature.SanitizeGeminiRequestThoughtSignaturesDoc(doc, "contents")

View File

@@ -1010,8 +1010,8 @@ func convertClaudeRequestToAntigravityWithWebSearchContext(ctx context.Context,
if v := ojson.GetBytesNoCopy(rawJSON, "top_k"); v.Exists() && v.Type == ojson.Number {
_ = outDoc.Set("request.generationConfig.topK", v.Num)
}
if maxTokens, ok := translatorcommon.ClaudePositiveMaxTokens(ojson.GetBytesNoCopy(rawJSON, "max_tokens")); ok {
_ = outDoc.Set("request.generationConfig.maxOutputTokens", maxTokens)
if rawMaxTokens, ok := translatorcommon.ClaudeMaxTokensRaw(ojson.GetBytesNoCopy(rawJSON, "max_tokens")); ok {
_ = outDoc.SetRaw("request.generationConfig.maxOutputTokens", rawMaxTokens)
}
if sequences := translatorcommon.ClaudeStopSequences(ojson.GetBytesNoCopy(rawJSON, "stop_sequences")); len(sequences) > 0 {
_ = outDoc.Set("request.generationConfig.stopSequences", sequences)

View File

@@ -4205,45 +4205,56 @@ func TestConvertClaudeRequestToAntigravity_ToolResultDocumentExtractedToParts(t
}
func TestConvertClaudeRequestToAntigravity_SanitizesGenerationConstraints(t *testing.T) {
t.Run("sanitizes float max_tokens and mixed stop_sequences", func(t *testing.T) {
inputJSON := []byte(`{
"model": "gemini-3.8-flash",
"max_tokens": 1024.9,
"stop_sequences": ["STOP", "\n", " ", "", 42, null],
"messages": [{"role": "user", "content": "hi"}]
}`)
output, errConvert := ConvertClaudeRequestToAntigravity("gemini-3.8-flash", inputJSON, false)
if errConvert != nil {
t.Fatalf("ConvertClaudeRequestToAntigravity() error = %v", errConvert)
}
genConfig := ojson.GetBytesNoCopy(output, "request.generationConfig")
if got := genConfig.Get("maxOutputTokens").Raw; got != "1024" {
t.Fatalf("maxOutputTokens raw = %q, want 1024; output=%s", got, output)
}
stops := genConfig.Get("stopSequences").Array()
wantStops := []string{"STOP", "\n", " "}
if len(stops) != len(wantStops) {
t.Fatalf("stopSequences = %s, want %v", genConfig.Get("stopSequences").Raw, wantStops)
}
for i, want := range wantStops {
if got := stops[i].String(); got != want {
t.Fatalf("stopSequences[%d] = %q, want %q", i, got, want)
}
t.Run("preserves native numeric max_tokens and filters mixed stop_sequences", func(t *testing.T) {
for _, tc := range []struct {
name string
maxTokens string
wantRawMax string
}{
{name: "zero max_tokens preserved", maxTokens: "0", wantRawMax: "0"},
{name: "fractional max_tokens passed verbatim", maxTokens: "1024.9", wantRawMax: "1024.9"},
} {
t.Run(tc.name, func(t *testing.T) {
inputJSON := []byte(`{
"model": "gemini-3.8-flash",
"max_tokens": ` + tc.maxTokens + `,
"stop_sequences": ["STOP", "\n", " ", "", 42, null],
"messages": [{"role": "user", "content": "hi"}]
}`)
output, errConvert := ConvertClaudeRequestToAntigravity("gemini-3.8-flash", inputJSON, false)
if errConvert != nil {
t.Fatalf("ConvertClaudeRequestToAntigravity() error = %v", errConvert)
}
genConfig := ojson.GetBytesNoCopy(output, "request.generationConfig")
if got := genConfig.Get("maxOutputTokens").Raw; got != tc.wantRawMax {
t.Fatalf("maxOutputTokens raw = %q, want %s; output=%s", got, tc.wantRawMax, output)
}
stops := genConfig.Get("stopSequences").Array()
wantStops := []string{"STOP", "\n", " "}
if len(stops) != len(wantStops) {
t.Fatalf("stopSequences = %s, want %v", genConfig.Get("stopSequences").Raw, wantStops)
}
for i, want := range wantStops {
if got := stops[i].String(); got != want {
t.Fatalf("stopSequences[%d] = %q, want %q", i, got, want)
}
}
})
}
})
t.Run("omits non-positive max_tokens, empty stop_sequences, and invalid output_config.format", func(t *testing.T) {
t.Run("omits non-numeric max_tokens, empty stop_sequences, and invalid output_config.format", func(t *testing.T) {
for _, tc := range []struct {
name string
payload string
}{
{
name: "zero max_tokens and empty stop_sequences",
payload: `{"model":"claude-sonnet-5-5-high","max_tokens":0,"stop_sequences":["",false],"output_config":{"effort":"high"},"messages":[{"role":"user","content":"hi"}]}`,
name: "null max_tokens and empty stop_sequences",
payload: `{"model":"claude-sonnet-5-5-high","max_tokens":null,"stop_sequences":["",false],"output_config":{"effort":"high"},"messages":[{"role":"user","content":"hi"}]}`,
},
{
name: "negative max_tokens and json_schema without schema object",
payload: `{"model":"claude-sonnet-5-5-high","max_tokens":-5,"stop_sequences":[],"output_config":{"format":{"type":"json_schema"}},"messages":[{"role":"user","content":"hi"}]}`,
name: "string max_tokens and json_schema without schema object",
payload: `{"model":"claude-sonnet-5-5-high","max_tokens":"256","stop_sequences":[],"output_config":{"format":{"type":"json_schema"}},"messages":[{"role":"user","content":"hi"}]}`,
},
} {
t.Run(tc.name, func(t *testing.T) {

View File

@@ -2,7 +2,6 @@ package common
import (
"crypto/rand"
"math"
"strings"
"github.com/MoeForge/moego/ojson"
@@ -62,21 +61,14 @@ func requestModelName(rawJSON []byte) string {
return ""
}
// ClaudePositiveMaxTokens parses a positive integer max_tokens value from a
// Claude request, clamping huge numbers at math.MaxInt32 to avoid int64 overflow
// differences across architectures before upstream executors enforce model limits.
func ClaudePositiveMaxTokens(v ojson.Result) (int64, bool) {
if !v.Exists() || v.Type != ojson.Number || v.Num < 1 {
return 0, false
// ClaudeMaxTokensRaw returns the raw JSON number token for a Claude max_tokens
// field so translators preserve native values (including 0) without float
// reformatting, silent truncation, or arbitrary clamping.
func ClaudeMaxTokensRaw(v ojson.Result) (string, bool) {
if !v.Exists() || v.Type != ojson.Number || v.Raw == "" {
return "", false
}
if v.Num >= float64(math.MaxInt32) {
return math.MaxInt32, true
}
maxTokens := v.Int()
if maxTokens <= 0 {
return 0, false
}
return maxTokens, true
return v.Raw, true
}
// ClaudeStopSequences extracts non-empty string entries from a Claude stop_sequences array.
@@ -84,13 +76,13 @@ func ClaudeStopSequences(v ojson.Result) []string {
if !v.Exists() || !v.IsArray() {
return nil
}
items := v.Array()
sequences := make([]string, 0, len(items))
for _, item := range items {
var sequences []string
v.ForEach(func(_, item ojson.Result) bool {
if item.Type == ojson.String && item.String() != "" {
sequences = append(sequences, item.String())
}
}
return true
})
if len(sequences) == 0 {
return nil
}

View File

@@ -1,7 +1,6 @@
package common
import (
"math"
"reflect"
"testing"
@@ -41,27 +40,28 @@ func TestGenerateClaudeToolCallID(t *testing.T) {
}
func TestClaudeGenerationConstraintHelpers(t *testing.T) {
t.Run("ClaudePositiveMaxTokens", func(t *testing.T) {
t.Run("ClaudeMaxTokensRaw", func(t *testing.T) {
tests := []struct {
name string
body string
want int64
want string
wantOK bool
}{
{name: "positive integer", body: `{"max_tokens":256}`, want: 256, wantOK: true},
{name: "fractional above one truncates", body: `{"max_tokens":1024.9}`, want: 1024, wantOK: true},
{name: "huge scientific float clamps to MaxInt32", body: `{"max_tokens":1e30}`, want: math.MaxInt32, wantOK: true},
{name: "zero omitted", body: `{"max_tokens":0}`, wantOK: false},
{name: "negative omitted", body: `{"max_tokens":-5}`, wantOK: false},
{name: "fractional below one omitted", body: `{"max_tokens":0.5}`, wantOK: false},
{name: "positive integer", body: `{"max_tokens":256}`, want: "256", wantOK: true},
{name: "zero preserved for cache pre-warm", body: `{"max_tokens":0}`, want: "0", wantOK: true},
{name: "long decode integer preserved verbatim", body: `{"max_tokens":1030323}`, want: "1030323", wantOK: true},
{name: "fractional preserved verbatim for upstream validation", body: `{"max_tokens":1024.9}`, want: "1024.9", wantOK: true},
{name: "negative preserved verbatim for upstream validation", body: `{"max_tokens":-5}`, want: "-5", wantOK: true},
{name: "scientific notation preserved verbatim", body: `{"max_tokens":1e30}`, want: "1e30", wantOK: true},
{name: "string omitted", body: `{"max_tokens":"256"}`, wantOK: false},
{name: "null omitted", body: `{"max_tokens":null}`, wantOK: false},
{name: "missing omitted", body: `{}`, wantOK: false},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got, ok := ClaudePositiveMaxTokens(ojson.Get(tc.body, "max_tokens"))
got, ok := ClaudeMaxTokensRaw(ojson.Get(tc.body, "max_tokens"))
if ok != tc.wantOK || got != tc.want {
t.Fatalf("ClaudePositiveMaxTokens(%s) = (%d, %t), want (%d, %t)", tc.body, got, ok, tc.want, tc.wantOK)
t.Fatalf("ClaudeMaxTokensRaw(%s) = (%q, %t), want (%q, %t)", tc.body, got, ok, tc.want, tc.wantOK)
}
})
}

View File

@@ -424,8 +424,8 @@ func convertClaudeRequestToGemini(modelName string, inputRawJSON []byte, _ bool,
if v := ojson.GetBytesNoCopy(rawJSON, "top_k"); v.Exists() && v.Type == ojson.Number {
_ = outDoc.Set("generationConfig.topK", v.Num)
}
if maxTokens, ok := translatorcommon.ClaudePositiveMaxTokens(ojson.GetBytesNoCopy(rawJSON, "max_tokens")); ok {
_ = outDoc.Set("generationConfig.maxOutputTokens", maxTokens)
if rawMaxTokens, ok := translatorcommon.ClaudeMaxTokensRaw(ojson.GetBytesNoCopy(rawJSON, "max_tokens")); ok {
_ = outDoc.SetRaw("generationConfig.maxOutputTokens", rawMaxTokens)
}
if sequences := translatorcommon.ClaudeStopSequences(ojson.GetBytesNoCopy(rawJSON, "stop_sequences")); len(sequences) > 0 {
_ = outDoc.Set("generationConfig.stopSequences", sequences)

View File

@@ -1163,49 +1163,61 @@ func TestConvertClaudeRequestToGemini_ToolResultDocumentNestedInFunctionResponse
}
func TestConvertClaudeRequestToGemini_SanitizesGenerationConstraints(t *testing.T) {
t.Run("sanitizes float max_tokens and mixed stop_sequences", func(t *testing.T) {
inputJSON := []byte(`{
"model": "gemini-3.5-flash",
"max_tokens": 1024.9,
"stop_sequences": ["END", "\n\n", " ", "", 123, null],
"messages": [{"role": "user", "content": "hi"}]
}`)
output, errConvert := ConvertClaudeRequestToGemini("gemini-3.5-flash", inputJSON, false)
if errConvert != nil {
t.Fatalf("ConvertClaudeRequestToGemini() error = %v", errConvert)
}
genConfig := ojson.GetBytesNoCopy(output, "generationConfig")
if got := genConfig.Get("maxOutputTokens").Raw; got != "1024" {
t.Fatalf("maxOutputTokens raw = %q, want 1024; output=%s", got, output)
}
stops := genConfig.Get("stopSequences").Array()
wantStops := []string{"END", "\n\n", " "}
if len(stops) != len(wantStops) {
t.Fatalf("stopSequences = %s, want %v", genConfig.Get("stopSequences").Raw, wantStops)
}
for i, want := range wantStops {
if got := stops[i].String(); got != want {
t.Fatalf("stopSequences[%d] = %q, want %q", i, got, want)
}
t.Run("preserves native numeric max_tokens and filters mixed stop_sequences", func(t *testing.T) {
for _, tc := range []struct {
name string
maxTokens string
wantRawMax string
}{
{name: "zero max_tokens preserved", maxTokens: "0", wantRawMax: "0"},
{name: "long decode max_tokens preserved", maxTokens: "1030323", wantRawMax: "1030323"},
{name: "fractional max_tokens passed verbatim", maxTokens: "1024.9", wantRawMax: "1024.9"},
} {
t.Run(tc.name, func(t *testing.T) {
inputJSON := []byte(`{
"model": "gemini-3.5-flash",
"max_tokens": ` + tc.maxTokens + `,
"stop_sequences": ["END", "\n\n", " ", "", 123, null],
"messages": [{"role": "user", "content": "hi"}]
}`)
output, errConvert := ConvertClaudeRequestToGemini("gemini-3.5-flash", inputJSON, false)
if errConvert != nil {
t.Fatalf("ConvertClaudeRequestToGemini() error = %v", errConvert)
}
genConfig := ojson.GetBytesNoCopy(output, "generationConfig")
if got := genConfig.Get("maxOutputTokens").Raw; got != tc.wantRawMax {
t.Fatalf("maxOutputTokens raw = %q, want %s; output=%s", got, tc.wantRawMax, output)
}
stops := genConfig.Get("stopSequences").Array()
wantStops := []string{"END", "\n\n", " "}
if len(stops) != len(wantStops) {
t.Fatalf("stopSequences = %s, want %v", genConfig.Get("stopSequences").Raw, wantStops)
}
for i, want := range wantStops {
if got := stops[i].String(); got != want {
t.Fatalf("stopSequences[%d] = %q, want %q", i, got, want)
}
}
})
}
})
t.Run("omits non-positive max_tokens, empty stop_sequences, and invalid output_config.format", func(t *testing.T) {
t.Run("omits non-numeric max_tokens, empty stop_sequences, and invalid output_config.format", func(t *testing.T) {
for _, tc := range []struct {
name string
payload string
}{
{
name: "zero max_tokens and empty stop_sequences",
payload: `{"model":"gemini-3.5-flash","max_tokens":0,"stop_sequences":["",123],"output_config":{"effort":"low"},"messages":[{"role":"user","content":"hi"}]}`,
name: "null max_tokens and empty stop_sequences",
payload: `{"model":"gemini-3.5-flash","max_tokens":null,"stop_sequences":["",123],"output_config":{"effort":"low"},"messages":[{"role":"user","content":"hi"}]}`,
},
{
name: "negative max_tokens and json_schema without schema object",
payload: `{"model":"gemini-3.5-flash","max_tokens":-5,"stop_sequences":[],"output_config":{"format":{"type":"json_schema"}},"messages":[{"role":"user","content":"hi"}]}`,
name: "string max_tokens and json_schema without schema object",
payload: `{"model":"gemini-3.5-flash","max_tokens":"256","stop_sequences":[],"output_config":{"format":{"type":"json_schema"}},"messages":[{"role":"user","content":"hi"}]}`,
},
{
name: "fractional max_tokens below one and unsupported format type",
payload: `{"model":"gemini-3.5-flash","max_tokens":0.5,"output_config":{"format":{"type":"text","schema":{"type":"object"}}},"messages":[{"role":"user","content":"hi"}]}`,
name: "unsupported format type",
payload: `{"model":"gemini-3.5-flash","output_config":{"format":{"type":"text","schema":{"type":"object"}}},"messages":[{"role":"user","content":"hi"}]}`,
},
} {
t.Run(tc.name, func(t *testing.T) {

View File

@@ -57,8 +57,8 @@ func copyClaudeSystemToInteractionsDoc(outDoc *ojson.Doc, root ojson.Result) {
}
func copyClaudeGenerationConfigToInteractionsDoc(outDoc *ojson.Doc, root ojson.Result) {
if maxTokens, ok := translatorcommon.ClaudePositiveMaxTokens(root.Get("max_tokens")); ok {
_ = outDoc.Set("generation_config.max_output_tokens", maxTokens)
if rawMaxTokens, ok := translatorcommon.ClaudeMaxTokensRaw(root.Get("max_tokens")); ok {
_ = outDoc.SetRaw("generation_config.max_output_tokens", rawMaxTokens)
}
copyClaudeJSONFieldDoc(outDoc, root, "temperature", "generation_config.temperature")
copyClaudeJSONFieldDoc(outDoc, root, "top_p", "generation_config.top_p")

View File

@@ -689,7 +689,7 @@ func TestConvertInteractionsResponseToClaude_ResponseFailed(t *testing.T) {
func TestConvertClaudeRequestToInteractions_GenerationConstraintsAndOutputConfigFormat(t *testing.T) {
raw := []byte(`{
"model": "gemini-3.5-flash",
"max_tokens": 512.8,
"max_tokens": 1030323,
"stop_sequences": ["STOP", "\n", "", 123, null],
"output_config": {
"effort": "low",
@@ -709,8 +709,8 @@ func TestConvertClaudeRequestToInteractions_GenerationConstraintsAndOutputConfig
if errConvert != nil {
t.Fatalf("ConvertClaudeRequestToInteractions() error = %v", errConvert)
}
if got := ojson.GetBytesNoCopy(out, "generation_config.max_output_tokens").Raw; got != "512" {
t.Fatalf("max_output_tokens raw = %q, want 512; out=%s", got, out)
if got := ojson.GetBytesNoCopy(out, "generation_config.max_output_tokens").Raw; got != "1030323" {
t.Fatalf("max_output_tokens raw = %q, want 1030323; out=%s", got, out)
}
if got := ojson.GetBytesNoCopy(out, "generation_config.thinking_level").String(); got != "low" {
t.Fatalf("thinking_level = %q, want low; out=%s", got, out)
@@ -729,9 +729,22 @@ func TestConvertClaudeRequestToInteractions_GenerationConstraintsAndOutputConfig
t.Fatalf("response_format.schema.properties.city.type = %q, want string; out=%s", got, out)
}
invalidRaw := []byte(`{
zeroRaw := []byte(`{
"model": "gemini-3.5-flash",
"max_tokens": 0,
"messages": [{"role": "user", "content": "hi"}]
}`)
zeroOut, errZero := ConvertClaudeRequestToInteractions("gemini-3.5-flash", zeroRaw, false)
if errZero != nil {
t.Fatalf("ConvertClaudeRequestToInteractions() zero error = %v", errZero)
}
if got := ojson.GetBytesNoCopy(zeroOut, "generation_config.max_output_tokens").Raw; got != "0" {
t.Fatalf("max_output_tokens raw = %q, want 0; out=%s", got, zeroOut)
}
invalidRaw := []byte(`{
"model": "gemini-3.5-flash",
"max_tokens": null,
"stop_sequences": ["", 123],
"output_config": {"format": {"type": "json_schema"}},
"messages": [{"role": "user", "content": "hi"}]