fix(translator,executor): harden Claude generation constraints and Vertex max output token cap

- Centralize Claude max_tokens, stop_sequences, and output_config.format parsing in internal/translator/common/request.go to filter invalid/non-positive values and clamp huge max_tokens deterministically.
- Use the shared helpers in Gemini, Antigravity, and Interactions Claude request translators, adding Interactions response_format mapping and removing dead schema deletes.
- Apply provider output token capping across all Vertex execute/stream paths before the payload config barrier, using float comparison to close fractional and overflow bypasses.
- Add unit and executor regression tests covering translators, Antigravity Claude 5.5 prompt fallback, and Gemini/Vertex API key and service account paths.
This commit is contained in:
sususu98
2026-11-23 23:29:33 +08:00
parent 328423486a
commit ac415c083a
12 changed files with 726 additions and 50 deletions

View File

@@ -0,0 +1,372 @@
package executor
import (
"context"
"io"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"github.com/MoeForge/moego/json"
"github.com/MoeForge/moego/ojson"
"github.com/router-for-me/CLIProxyAPI/v8/internal/config"
cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"
cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor"
sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator"
_ "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator/builtin"
)
func TestAntigravityClaudeFormatOutputConfigAndStopSequences(t *testing.T) {
wantSchema := map[string]any{
"type": "object",
"properties": map[string]any{
"title": map[string]any{"type": "string"},
"count": map[string]any{"type": "integer"},
},
"required": []any{"title", "count"},
"additionalProperties": false,
}
rawClaudePayload := []byte(`{
"model": "claude-sonnet-5-5-high",
"max_tokens": 1024,
"stop_sequences": ["END_MARKER"],
"tools": [{
"name": "get_time",
"description": "Get time",
"input_schema": {
"type": "object",
"properties": {"tz": {"type": "string"}},
"required": ["tz"]
}
}],
"tool_choice": {"type": "auto"},
"output_config": {
"format": {
"type": "json_schema",
"schema": {
"type": "object",
"properties": {
"title": {"type": "string"},
"count": {"type": "integer"}
},
"required": ["title", "count"],
"additionalProperties": false
}
}
},
"messages": [{"role": "user", "content": "hi"}]
}`)
t.Run("claude-5-5 falls back to prompt instruction and preserves stopSequences", func(t *testing.T) {
for _, model := range []string{"claude-opus-5-5-high", "claude-sonnet-5-5-high"} {
t.Run(model, func(t *testing.T) {
translated := sdktranslator.TranslateRequest(sdktranslator.FormatClaude, sdktranslator.FormatAntigravity, model, rawClaudePayload, false)
body := buildRequestBodyFromRawPayload(t, model, translated)
encoded, errMarshal := json.Marshal(body)
if errMarshal != nil {
t.Fatalf("marshal outbound request: %v", errMarshal)
}
request := ojson.GetBytes(encoded, "request")
if got := request.Get("generationConfig.stopSequences.0").String(); got != "END_MARKER" {
t.Fatalf("stopSequences[0] = %q, want END_MARKER; body=%s", got, encoded)
}
if mode := request.Get("toolConfig.functionCallingConfig.mode").String(); mode != "" && mode != "AUTO" {
t.Fatalf("toolConfig mode = %q, want AUTO or omitted for Claude 5.5; body=%s", mode, encoded)
}
for _, field := range []string{"responseSchema", "responseJsonSchema", "responseMimeType"} {
if got := request.Get("generationConfig." + field); got.Exists() {
t.Fatalf("generationConfig.%s = %s, want omitted after Claude 5.5 prompt fallback", field, got.Raw)
}
}
var systemText strings.Builder
for _, part := range request.Get("systemInstruction.parts").Array() {
systemText.WriteString(part.Get("text").String())
systemText.WriteByte('\n')
}
prompt := systemText.String()
foundSchema := false
for offset, ch := range prompt {
if ch != '{' {
continue
}
var decoded map[string]any
if errDecode := json.NewDecoder(strings.NewReader(prompt[offset:])).Decode(&decoded); errDecode == nil && reflect.DeepEqual(decoded, wantSchema) {
foundSchema = true
break
}
}
if !foundSchema {
t.Fatalf("systemInstruction missing structured output schema; prompt=%q", prompt)
}
})
}
})
t.Run("claude-5-5 does not leak responseMimeType when schema is missing", func(t *testing.T) {
model := "claude-sonnet-5-5-high"
invalidFormat := []byte(`{
"model": "claude-sonnet-5-5-high",
"max_tokens": 1024,
"output_config": {"format": {"type": "json_schema"}},
"messages": [{"role": "user", "content": "hi"}]
}`)
translated := sdktranslator.TranslateRequest(sdktranslator.FormatClaude, sdktranslator.FormatAntigravity, model, invalidFormat, false)
body := buildRequestBodyFromRawPayload(t, model, translated)
encoded, errMarshal := json.Marshal(body)
if errMarshal != nil {
t.Fatalf("marshal outbound request: %v", errMarshal)
}
request := ojson.GetBytes(encoded, "request")
for _, field := range []string{"responseSchema", "responseJsonSchema", "responseMimeType"} {
if got := request.Get("generationConfig." + field); got.Exists() {
t.Fatalf("generationConfig.%s = %s, want omitted when schema is absent", field, got.Raw)
}
}
})
t.Run("antigravity gemini preserves cleaned responseSchema and stopSequences", func(t *testing.T) {
model := "gemini-3.8-flash-high"
translated := sdktranslator.TranslateRequest(sdktranslator.FormatClaude, sdktranslator.FormatAntigravity, model, rawClaudePayload, false)
body := buildRequestBodyFromRawPayload(t, model, translated)
encoded, errMarshal := json.Marshal(body)
if errMarshal != nil {
t.Fatalf("marshal outbound request: %v", errMarshal)
}
request := ojson.GetBytes(encoded, "request")
if got := request.Get("generationConfig.stopSequences.0").String(); got != "END_MARKER" {
t.Fatalf("stopSequences[0] = %q, want END_MARKER; body=%s", got, encoded)
}
if got := request.Get("generationConfig.responseMimeType").String(); got != "application/json" {
t.Fatalf("responseMimeType = %q, want application/json; body=%s", got, encoded)
}
if request.Get("generationConfig.responseJsonSchema").Exists() {
t.Fatalf("responseJsonSchema must not be sent to Antigravity; body=%s", encoded)
}
if got := request.Get("generationConfig.responseSchema.properties.title.type").String(); !strings.EqualFold(got, "string") {
t.Fatalf("responseSchema.properties.title.type = %q, want string/STRING; body=%s", got, encoded)
}
})
}
func TestGeminiAndVertexExecutors_ClaudeGenerationConfigAndMaxTokensCap(t *testing.T) {
claudePayload := []byte(`{
"model": "gemini-3.1-pro-preview",
"max_tokens": 500000,
"stop_sequences": ["STOP_NOW"],
"output_config": {
"format": {
"type": "json_schema",
"schema": {
"type": "object",
"properties": {"answer": {"type": "string"}},
"required": ["answer"],
"additionalProperties": false
}
}
},
"messages": [{"role": "user", "content": "hi"}]
}`)
geminiResp := `{"candidates":[{"content":{"role":"model","parts":[{"text":"{\"answer\":\"ok\"}"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":1,"candidatesTokenCount":1,"totalTokenCount":2}}`
if !ojson.Valid(geminiResp) {
t.Fatalf("invalid test fixture geminiResp: %s", geminiResp)
}
assertOutbound := func(t *testing.T, upstreamBody []byte, wantMax int64) {
t.Helper()
genCfg := ojson.GetBytes(upstreamBody, "generationConfig")
if got := genCfg.Get("maxOutputTokens").Int(); got != wantMax {
t.Fatalf("maxOutputTokens = %d, want %d; body=%s", got, wantMax, upstreamBody)
}
if got := genCfg.Get("stopSequences.0").String(); got != "STOP_NOW" {
t.Fatalf("stopSequences[0] = %q, want STOP_NOW; body=%s", got, upstreamBody)
}
if got := genCfg.Get("responseMimeType").String(); got != "application/json" {
t.Fatalf("responseMimeType = %q, want application/json; body=%s", got, upstreamBody)
}
if got := genCfg.Get("responseJsonSchema.properties.answer.type").String(); got != "string" {
t.Fatalf("responseJsonSchema.properties.answer.type = %q, want string; body=%s", got, upstreamBody)
}
}
collectClaudeStreamText := func(t *testing.T, chunks <-chan cliproxyexecutor.StreamChunk) string {
t.Helper()
var text strings.Builder
for chunk := range chunks {
if chunk.Err != nil {
t.Fatalf("stream chunk error = %v", chunk.Err)
}
for _, line := range strings.Split(string(chunk.Payload), "\n") {
if !strings.HasPrefix(line, "data: ") {
continue
}
data := strings.TrimPrefix(line, "data: ")
if ojson.Get(data, "type").String() == "content_block_delta" && ojson.Get(data, "delta.type").String() == "text_delta" {
text.WriteString(ojson.Get(data, "delta.text").String())
}
}
}
return text.String()
}
t.Run("gemini executor maps fields and caps max_tokens", func(t *testing.T) {
for _, stream := range []bool{false, true} {
name := "execute"
if stream {
name = "stream"
}
t.Run(name, func(t *testing.T) {
var upstreamBody []byte
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
}
upstreamBody = append([]byte(nil), body...)
if stream {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte("data: " + geminiResp + "\n\n"))
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(geminiResp))
}))
defer server.Close()
exec := NewGeminiExecutor(&config.Config{})
auth := &cliproxyauth.Auth{Attributes: map[string]string{
"api_key": "test-key",
"base_url": server.URL,
}}
req := cliproxyexecutor.Request{Model: "gemini-3.1-pro-preview", Payload: claudePayload}
opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, ResponseFormat: sdktranslator.FormatClaude, Stream: stream}
if 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)
}
}
assertOutbound(t, upstreamBody, 65536)
})
}
})
t.Run("vertex executor maps fields, caps 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
stream bool
override int64
wantMax int64
}{
{name: "execute_capped", stream: false, wantMax: 65536},
{name: "stream_capped", stream: true, wantMax: 65536},
{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
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/token" {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"access_token":"local-token","token_type":"Bearer","expires_in":3600}`)
return
}
body, errRead := io.ReadAll(r.Body)
if errRead != nil {
t.Errorf("read request body: %v", errRead)
w.WriteHeader(http.StatusInternalServerError)
return
}
upstreamBody = append([]byte(nil), body...)
if tc.stream {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte("data: " + geminiResp + "\n\n"))
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(geminiResp))
}))
defer server.Close()
cfg := &config.Config{}
if tc.override > 0 {
cfg.Payload = config.PayloadConfig{
Override: []config.PayloadRule{{
Models: []config.PayloadModelRule{{Name: "gemini-3.1-pro-preview", Protocol: "gemini"}},
Params: map[string]any{"generationConfig.maxOutputTokens": tc.override},
}},
}
}
exec := NewGeminiVertexExecutor(cfg)
ctx := context.Background()
auth := &cliproxyauth.Auth{ID: t.Name(), Provider: "vertex"}
if authMode == "api_key" {
auth.Attributes = map[string]string{
"api_key": "test-vertex-key",
"base_url": server.URL,
}
} else {
var serviceAccount map[string]any
if errUnmarshal := json.Unmarshal(testVertexServiceAccountJSON(t, server.URL+"/token"), &serviceAccount); errUnmarshal != nil {
t.Fatal(errUnmarshal)
}
auth.Metadata = map[string]any{
"project_id": "proxy-test",
"location": "global",
"service_account": serviceAccount,
}
target, errParse := parseTestURL(t, server.URL)
if errParse != nil {
t.Fatal(errParse)
}
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.Proxy = nil
t.Cleanup(transport.CloseIdleConnections)
ctx = context.WithValue(ctx, "cliproxy.roundtripper", issue6258RedirectTransport{target: target, base: transport})
}
req := cliproxyexecutor.Request{Model: "gemini-3.1-pro-preview", Payload: claudePayload}
opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, ResponseFormat: sdktranslator.FormatClaude, Stream: tc.stream}
if tc.stream {
res, errStream := exec.ExecuteStream(ctx, 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(ctx, 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)
}
}
assertOutbound(t, upstreamBody, tc.wantMax)
})
}
}
})
}

View File

@@ -1296,6 +1296,10 @@ 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
}
@@ -1303,7 +1307,7 @@ func capGeminiMaxOutputTokensDoc(doc *ojson.Doc, modelName string) bool {
if !maxOut.Exists() || maxOut.Type != ojson.Number {
return false
}
modelInfo := registry.LookupModelInfo(modelName, "gemini")
modelInfo := registry.LookupModelInfo(modelName, provider)
if modelInfo == nil {
return false
}
@@ -1311,7 +1315,7 @@ func capGeminiMaxOutputTokensDoc(doc *ojson.Doc, modelName string) bool {
if limit <= 0 {
limit = modelInfo.MaxCompletionTokens
}
if limit <= 0 || maxOut.Int() <= int64(limit) {
if limit <= 0 || maxOut.Num <= float64(limit) {
return false
}
return doc.Set("generationConfig.maxOutputTokens", limit) == nil

View File

@@ -21,15 +21,24 @@ import (
)
func TestCapGeminiMaxOutputTokensUsesOutputTokenLimit(t *testing.T) {
body := []byte(`{"generationConfig":{"maxOutputTokens":500000,"temperature":0.2},"contents":[]}`)
out := capGeminiMaxOutputTokens(body, "gemini-3.1-pro-preview")
if got := ojson.GetBytes(out, "generationConfig.maxOutputTokens").Int(); got != 65536 {
t.Fatalf("maxOutputTokens = %d, want 65536", got)
}
if got := ojson.GetBytes(out, "generationConfig.temperature").Float(); got != 0.2 {
t.Fatalf("temperature = %v, want 0.2", got)
for _, tc := range []struct {
name string
raw string
}{
{name: "integer above limit", raw: "500000"},
{name: "fractional above limit", raw: "65536.5"},
{name: "huge scientific float", raw: "1e30"},
} {
t.Run(tc.name, func(t *testing.T) {
body := []byte(`{"generationConfig":{"maxOutputTokens":` + tc.raw + `,"temperature":0.2},"contents":[]}`)
out := capGeminiMaxOutputTokens(body, "gemini-3.1-pro-preview")
if got := ojson.GetBytes(out, "generationConfig.maxOutputTokens").Raw; got != "65536" {
t.Fatalf("maxOutputTokens raw = %q, want 65536; out=%s", got, out)
}
if got := ojson.GetBytes(out, "generationConfig.temperature").Float(); got != 0.2 {
t.Fatalf("temperature = %v, want 0.2", got)
}
})
}
}

View File

@@ -489,6 +489,7 @@ 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")
@@ -683,6 +684,7 @@ 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")
@@ -866,6 +868,7 @@ 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")
@@ -1285,6 +1288,7 @@ 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,27 +1010,15 @@ 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 v := ojson.GetBytesNoCopy(rawJSON, "max_tokens"); v.Exists() && v.Type == ojson.Number {
_ = outDoc.Set("request.generationConfig.maxOutputTokens", v.Num)
if maxTokens, ok := translatorcommon.ClaudePositiveMaxTokens(ojson.GetBytesNoCopy(rawJSON, "max_tokens")); ok {
_ = outDoc.Set("request.generationConfig.maxOutputTokens", maxTokens)
}
if stopSequences := ojson.GetBytesNoCopy(rawJSON, "stop_sequences"); stopSequences.Exists() && stopSequences.IsArray() {
var sequences []string
stopSequences.ForEach(func(_, sequence ojson.Result) bool {
if sequence.Type == ojson.String && sequence.String() != "" {
sequences = append(sequences, sequence.String())
}
return true
})
if len(sequences) > 0 {
_ = outDoc.Set("request.generationConfig.stopSequences", sequences)
}
if sequences := translatorcommon.ClaudeStopSequences(ojson.GetBytesNoCopy(rawJSON, "stop_sequences")); len(sequences) > 0 {
_ = outDoc.Set("request.generationConfig.stopSequences", sequences)
}
if format := ojson.GetBytesNoCopy(rawJSON, "output_config.format"); format.Exists() && format.IsObject() && strings.EqualFold(strings.TrimSpace(format.Get("type").String()), "json_schema") {
if schema, ok := translatorcommon.ClaudeOutputJSONSchema(ojson.GetBytesNoCopy(rawJSON, "output_config.format")); ok {
_ = outDoc.Set("request.generationConfig.responseMimeType", "application/json")
_ = outDoc.Delete("request.generationConfig.responseJsonSchema")
if schema := format.Get("schema"); schema.Exists() && schema.IsObject() {
_ = outDoc.SetRaw("request.generationConfig.responseSchema", schema.Raw)
}
_ = outDoc.SetRaw("request.generationConfig.responseSchema", schema.Raw)
}
common.AttachDefaultSafetySettingsDoc(outDoc, "request.safetySettings")

View File

@@ -4203,3 +4203,61 @@ 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("omits non-positive 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: "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"}]}`,
},
} {
t.Run(tc.name, func(t *testing.T) {
output, errConvert := ConvertClaudeRequestToAntigravity("claude-sonnet-5-5-high", []byte(tc.payload), false)
if errConvert != nil {
t.Fatalf("ConvertClaudeRequestToAntigravity() error = %v", errConvert)
}
genConfig := ojson.GetBytesNoCopy(output, "request.generationConfig")
for _, key := range []string{"maxOutputTokens", "stopSequences", "responseMimeType", "responseSchema", "responseJsonSchema"} {
if genConfig.Get(key).Exists() {
t.Fatalf("request.generationConfig.%s should be omitted, got %s; output=%s", key, genConfig.Get(key).Raw, output)
}
}
})
}
})
}

View File

@@ -2,6 +2,7 @@ package common
import (
"crypto/rand"
"math"
"strings"
"github.com/MoeForge/moego/ojson"
@@ -60,3 +61,54 @@ 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
}
if v.Num >= float64(math.MaxInt32) {
return math.MaxInt32, true
}
maxTokens := v.Int()
if maxTokens <= 0 {
return 0, false
}
return maxTokens, true
}
// ClaudeStopSequences extracts non-empty string entries from a Claude stop_sequences array.
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 {
if item.Type == ojson.String && item.String() != "" {
sequences = append(sequences, item.String())
}
}
if len(sequences) == 0 {
return nil
}
return sequences
}
// ClaudeOutputJSONSchema returns the schema object when output_config.format
// specifies a valid json_schema format.
func ClaudeOutputJSONSchema(format ojson.Result) (ojson.Result, bool) {
if !format.Exists() || !format.IsObject() {
return ojson.Result{}, false
}
if !strings.EqualFold(strings.TrimSpace(format.Get("type").String()), "json_schema") {
return ojson.Result{}, false
}
schema := format.Get("schema")
if !schema.Exists() || !schema.IsObject() {
return ojson.Result{}, false
}
return schema, true
}

View File

@@ -1,6 +1,12 @@
package common
import "testing"
import (
"math"
"reflect"
"testing"
"github.com/MoeForge/moego/ojson"
)
func TestRequestModelNamePrefersOriginalRequest(t *testing.T) {
original := []byte(`{"model":"original-model"}`)
@@ -33,3 +39,60 @@ func TestGenerateClaudeToolCallID(t *testing.T) {
}
}
}
func TestClaudeGenerationConstraintHelpers(t *testing.T) {
t.Run("ClaudePositiveMaxTokens", func(t *testing.T) {
tests := []struct {
name string
body string
want int64
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: "string omitted", body: `{"max_tokens":"256"}`, wantOK: false},
{name: "null omitted", body: `{"max_tokens":null}`, wantOK: false},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got, ok := ClaudePositiveMaxTokens(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.Run("ClaudeStopSequences", func(t *testing.T) {
got := ClaudeStopSequences(ojson.Get(`{"stop_sequences":["END","\n\n"," ","",123,null]}`, "stop_sequences"))
want := []string{"END", "\n\n", " "}
if !reflect.DeepEqual(got, want) {
t.Fatalf("ClaudeStopSequences() = %#v, want %#v", got, want)
}
for _, body := range []string{`{"stop_sequences":[]}`, `{"stop_sequences":["",123]}`, `{"stop_sequences":"END"}`} {
if seqs := ClaudeStopSequences(ojson.Get(body, "stop_sequences")); len(seqs) != 0 {
t.Fatalf("ClaudeStopSequences(%s) = %#v, want nil", body, seqs)
}
}
})
t.Run("ClaudeOutputJSONSchema", func(t *testing.T) {
schema, ok := ClaudeOutputJSONSchema(ojson.Get(`{"output_config":{"format":{"type":" JSON_SCHEMA ","schema":{"type":"object","additionalProperties":false}}}}`, "output_config.format"))
if !ok || !schema.IsObject() || schema.Get("type").String() != "object" {
t.Fatalf("ClaudeOutputJSONSchema() = (%s, %t), want valid schema object", schema.Raw, ok)
}
for _, body := range []string{
`{"output_config":{"format":{"type":"json_schema"}}}`,
`{"output_config":{"format":{"type":"json_schema","schema":"bad"}}}`,
`{"output_config":{"format":{"type":"text","schema":{"type":"object"}}}}`,
} {
if got, ok := ClaudeOutputJSONSchema(ojson.Get(body, "output_config.format")); ok {
t.Fatalf("ClaudeOutputJSONSchema(%s) = (%s, true), want false", body, got.Raw)
}
}
})
}

View File

@@ -424,27 +424,15 @@ 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 v := ojson.GetBytesNoCopy(rawJSON, "max_tokens"); v.Exists() && v.Type == ojson.Number {
_ = outDoc.Set("generationConfig.maxOutputTokens", v.Num)
if maxTokens, ok := translatorcommon.ClaudePositiveMaxTokens(ojson.GetBytesNoCopy(rawJSON, "max_tokens")); ok {
_ = outDoc.Set("generationConfig.maxOutputTokens", maxTokens)
}
if stopSequences := ojson.GetBytesNoCopy(rawJSON, "stop_sequences"); stopSequences.Exists() && stopSequences.IsArray() {
var sequences []string
stopSequences.ForEach(func(_, sequence ojson.Result) bool {
if sequence.Type == ojson.String && sequence.String() != "" {
sequences = append(sequences, sequence.String())
}
return true
})
if len(sequences) > 0 {
_ = outDoc.Set("generationConfig.stopSequences", sequences)
}
if sequences := translatorcommon.ClaudeStopSequences(ojson.GetBytesNoCopy(rawJSON, "stop_sequences")); len(sequences) > 0 {
_ = outDoc.Set("generationConfig.stopSequences", sequences)
}
if format := ojson.GetBytesNoCopy(rawJSON, "output_config.format"); format.Exists() && format.IsObject() && strings.EqualFold(strings.TrimSpace(format.Get("type").String()), "json_schema") {
if schema, ok := translatorcommon.ClaudeOutputJSONSchema(ojson.GetBytesNoCopy(rawJSON, "output_config.format")); ok {
_ = outDoc.Set("generationConfig.responseMimeType", "application/json")
_ = outDoc.Delete("generationConfig.responseSchema")
if schema := format.Get("schema"); schema.Exists() && schema.IsObject() {
_ = outDoc.SetRaw("generationConfig.responseJsonSchema", schema.Raw)
}
_ = outDoc.SetRaw("generationConfig.responseJsonSchema", schema.Raw)
}
common.AttachDefaultSafetySettingsDoc(outDoc, "safetySettings")

View File

@@ -1161,3 +1161,65 @@ 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("omits non-positive 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: "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: "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"}]}`,
},
} {
t.Run(tc.name, func(t *testing.T) {
output, errConvert := ConvertClaudeRequestToGemini("gemini-3.5-flash", []byte(tc.payload), false)
if errConvert != nil {
t.Fatalf("ConvertClaudeRequestToGemini() error = %v", errConvert)
}
genConfig := ojson.GetBytesNoCopy(output, "generationConfig")
for _, key := range []string{"maxOutputTokens", "stopSequences", "responseMimeType", "responseJsonSchema", "responseSchema"} {
if genConfig.Get(key).Exists() {
t.Fatalf("generationConfig.%s should be omitted, got %s; output=%s", key, genConfig.Get(key).Raw, output)
}
}
})
}
})
}

View File

@@ -32,6 +32,7 @@ func convertClaudeRequestToInteractions(modelName string, inputRawJSON []byte, s
}
copyClaudeSystemToInteractionsDoc(outDoc, root)
copyClaudeGenerationConfigToInteractionsDoc(outDoc, root)
copyClaudeOutputFormatToInteractionsDoc(outDoc, root)
errDrops := appendClaudeMessagesToInteractionsDoc(outDoc, root.Get("messages"), preserveEmptyThinkingBlocks)
copyClaudeToolsToInteractionsDoc(outDoc, root)
return outDoc.Bytes(), errDrops
@@ -56,10 +57,14 @@ func copyClaudeSystemToInteractionsDoc(outDoc *ojson.Doc, root ojson.Result) {
}
func copyClaudeGenerationConfigToInteractionsDoc(outDoc *ojson.Doc, root ojson.Result) {
copyClaudeJSONFieldDoc(outDoc, root, "max_tokens", "generation_config.max_output_tokens")
if maxTokens, ok := translatorcommon.ClaudePositiveMaxTokens(root.Get("max_tokens")); ok {
_ = outDoc.Set("generation_config.max_output_tokens", maxTokens)
}
copyClaudeJSONFieldDoc(outDoc, root, "temperature", "generation_config.temperature")
copyClaudeJSONFieldDoc(outDoc, root, "top_p", "generation_config.top_p")
copyClaudeJSONFieldDoc(outDoc, root, "stop_sequences", "generation_config.stop_sequences")
if sequences := translatorcommon.ClaudeStopSequences(root.Get("stop_sequences")); len(sequences) > 0 {
_ = outDoc.Set("generation_config.stop_sequences", sequences)
}
copyClaudeThinkingToInteractionsDoc(outDoc, root)
copyClaudeToolChoiceToInteractionsDoc(outDoc, root.Get("tool_choice"))
}
@@ -72,6 +77,16 @@ func copyClaudeJSONFieldDoc(outDoc *ojson.Doc, root ojson.Result, from, to strin
_ = outDoc.SetRaw(to, value.Raw)
}
func copyClaudeOutputFormatToInteractionsDoc(outDoc *ojson.Doc, root ojson.Result) {
schema, ok := translatorcommon.ClaudeOutputJSONSchema(root.Get("output_config.format"))
if !ok {
return
}
entryDoc := ojson.NewDocString(`{"type":"text","mime_type":"application/json"}`)
_ = entryDoc.SetRaw("schema", schema.Raw)
_ = outDoc.SetRawBytes("response_format", entryDoc.Bytes())
}
func copyClaudeThinkingToInteractionsDoc(outDoc *ojson.Doc, root ojson.Result) {
thinking := root.Get("thinking")
if thinking.Exists() {

View File

@@ -685,3 +685,64 @@ func TestConvertInteractionsResponseToClaude_ResponseFailed(t *testing.T) {
})
}
}
func TestConvertClaudeRequestToInteractions_GenerationConstraintsAndOutputConfigFormat(t *testing.T) {
raw := []byte(`{
"model": "gemini-3.5-flash",
"max_tokens": 512.8,
"stop_sequences": ["STOP", "\n", "", 123, null],
"output_config": {
"effort": "low",
"format": {
"type": "json_schema",
"schema": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
"additionalProperties": false
}
}
},
"messages": [{"role": "user", "content": "hi"}]
}`)
out, errConvert := ConvertClaudeRequestToInteractions("gemini-3.5-flash", raw, false)
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.thinking_level").String(); got != "low" {
t.Fatalf("thinking_level = %q, want low; out=%s", got, out)
}
stops := ojson.GetBytesNoCopy(out, "generation_config.stop_sequences").Array()
if len(stops) != 2 || stops[0].String() != "STOP" || stops[1].String() != "\n" {
t.Fatalf("stop_sequences = %s, want [STOP \\n]; out=%s", ojson.GetBytesNoCopy(out, "generation_config.stop_sequences").Raw, out)
}
if got := ojson.GetBytesNoCopy(out, "response_format.type").String(); got != "text" {
t.Fatalf("response_format.type = %q, want text; out=%s", got, out)
}
if got := ojson.GetBytesNoCopy(out, "response_format.mime_type").String(); got != "application/json" {
t.Fatalf("response_format.mime_type = %q, want application/json; out=%s", got, out)
}
if got := ojson.GetBytesNoCopy(out, "response_format.schema.properties.city.type").String(); got != "string" {
t.Fatalf("response_format.schema.properties.city.type = %q, want string; out=%s", got, out)
}
invalidRaw := []byte(`{
"model": "gemini-3.5-flash",
"max_tokens": 0,
"stop_sequences": ["", 123],
"output_config": {"format": {"type": "json_schema"}},
"messages": [{"role": "user", "content": "hi"}]
}`)
invalidOut, errInvalid := ConvertClaudeRequestToInteractions("gemini-3.5-flash", invalidRaw, false)
if errInvalid != nil {
t.Fatalf("ConvertClaudeRequestToInteractions() invalid error = %v", errInvalid)
}
for _, path := range []string{"generation_config.max_output_tokens", "generation_config.stop_sequences", "response_format"} {
if ojson.GetBytesNoCopy(invalidOut, path).Exists() {
t.Fatalf("%s should be omitted for invalid input; out=%s", path, invalidOut)
}
}
}