gateway: Gemini 4 and later are told a thinking level, at the level asked (#2083)

Gemini 4 Argon turns every thinkingBudget away with a 400 ("Thinking
budget is not supported for this model. Use thinking level instead."),
and magpie sent it one: thinkingConfig gave a level only to ids starting
gemini-3 (and gemini-pro-agent), so a gemini-4-* id on a provider that
speaks Gemini's own API (the reporter's google-vertex catalog, a custom
gemini= base) got a budget on every request.

geminiGeneration reads the generation from the id (gemini-N, after a
models/ prefix too); 3 and later are told a level. Medium goes as medium
on a later generation as it does on Flash: Argon lists low, medium and
high, and the effort is already fitted to the model's levels (fitFor). An
id naming no generation (gemini-flash-latest, an alias) is 0 and keeps
its budget, as before. The Chat path (aiStudioThinking) already gave a
budget only to gemini-2, and Vertex's vertexThinking is unchanged.

Run:
- TestGeminiLaterGenerationsToldALevel: a fake Gemini upstream that
  answers a budget on gemini-4* with the reporter's literal 400; Argon
  low/medium/high on /v1/chat/completions and /v1/responses, 3.8 Flash,
  3 Pro medium (high, as before), 2.5 Flash (budget 24000). FAILs on the
  old code with Argon's 400 on both routes; FAILs with "thinkingLevel
  high, want medium" when only the medium case is reverted.
- TestGeminiGeneration (id table).
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows on
  internal/gateway; go test -tags nogui ./internal/gateway/.

Not tried: a real Gemini 4 Argon request (no AI Studio or Vertex key on
this machine). A magpie alias that names no generation but is wired to a
Gemini 4 model still gets a budget.
This commit is contained in:
yetone
2026-10-14 15:34:16 +08:00
parent f5083e8041
commit 52be997b39
2 changed files with 142 additions and 9 deletions
+31 -9
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"net/http"
"regexp"
"strconv"
"strings"
"github.com/yetone/magpie/internal/catalog"
@@ -477,17 +478,19 @@ func pairFunctionTurns(contents []map[string]any, ag, agClaude bool) []map[strin
}
// thinkingConfig says how hard the model should think: a level for
// Gemini 3, a budget for the rest. A model that doesn't think gets none,
// and one whose id already says its level, at (Antigravity's
// gemini-3.7-flash-low), is told that level and no other — the effort
// asked for picked that id. Told no level, Antigravity's variants all but
// Gemini 3 and later (geminiGeneration), a budget for the rest. A model
// that doesn't think gets none, and one whose id already says its level,
// at (Antigravity's gemini-3.7-flash-low), is told that level and no
// other — the effort asked for picked that id. Told no level, Antigravity's variants all but
// stop thinking once the request has tools, and give none of it back
// (#636); Antigravity's own tiered ids, sent a level, don't.
//
// Gemini 3's levels: medium goes as medium to Flash, and up to high to
// Pro, which took low and high only (3 Pro). Minimal goes only to a Flash
// variant at minimal: 3.7 and 3.8 Flash have none (AI Studio answers 3.8's
// with a 400), and the id here doesn't say which Flash serves it (Gemini
// Pro, which took low and high only (3 Pro). A later Gemini is sent the
// medium it was asked, already fitted to its own levels (fitFor):
// gemini-4-argon has low, medium and high (#2083). Minimal goes only to a
// Flash variant at minimal: 3.7 and 3.8 Flash have none (AI Studio
// answers 3.8's with a 400), and the id here doesn't say which Flash serves it (Gemini
// CLI's 3.5 Flash goes out as 3.8 Flash where that is rolled out).
// Reasoning off otherwise (the auto mode classifier's least level) goes at
// low, which every Gemini 3 text model takes; an image model may have no
@@ -504,7 +507,7 @@ func thinkingConfig(r *Request, model string, claude bool, at string) map[string
}
}
tc := map[string]any{"includeThoughts": true}
if strings.HasPrefix(m, "gemini-3") || strings.HasPrefix(m, "gemini-pro-agent") {
if gen := geminiGeneration(m); gen >= 3 || strings.HasPrefix(m, "gemini-pro-agent") {
effort := r.Effort
if at != "" {
effort = at
@@ -518,7 +521,7 @@ func thinkingConfig(r *Request, model string, claude bool, at string) map[string
level = "minimal"
case offEffort(effort) && !catalog.DrawsID(m):
level = "low"
case effort == "medium" && strings.Contains(m, "flash"):
case effort == "medium" && (strings.Contains(m, "flash") || gen > 3):
level = "medium"
}
tc["thinkingLevel"] = level
@@ -536,6 +539,25 @@ func thinkingConfig(r *Request, model string, claude bool, at string) map[string
return tc
}
// geminiVersion is the major version in a Gemini model's id, as the id
// names it: gemini-4-argon, models/gemini-3.8-flash, gemini-2.5-pro.
var geminiVersion = regexp.MustCompile(`(?:^|/)gemini-(\d+)`)
// geminiGeneration is the generation of Gemini model names, 0 for an id
// that names none (a non-Gemini model, or an alias such as
// gemini-flash-latest, which may still be a 2.5). From Gemini 3 a model is
// told a thinking level; Gemini 4 turns a budget away with "Thinking
// budget is not supported for this model. Use thinking level instead."
// (#2083), so a new generation isn't sent one either.
func geminiGeneration(model string) int {
m := geminiVersion.FindStringSubmatch(model)
if m == nil {
return 0
}
n, _ := strconv.Atoi(m[1])
return n
}
// plainSchema is a JSON schema cut down to what Antigravity's function
// declarations take: an OpenAPI-style subset with no references, unions
// or keywords outside it.
+111
View File
@@ -0,0 +1,111 @@
package gateway
import (
"encoding/json"
"io"
"maps"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
)
// argonBudgetRefused is Gemini 4 Argon's answer to a thinkingBudget, as
// #2083 quotes it.
const argonBudgetRefused = `{"error":{"code":400,"message":"Thinking budget is not supported for this model. Use thinking level instead. See https://ai.google.dev/gemini-api/docs/thinking for details.","status":"INVALID_ARGUMENT"}}`
// #2083: a provider the user added that speaks Gemini's API, its models
// from models.dev's google-vertex, as the reporter set it up. Gemini 4
// Argon is told a thinking level, and medium as medium, the levels it has:
// it turns every budget away with a 400. Gemini 3.8 Flash is told its level
// as before, Gemini 2.5 still a budget, and a Gemini 3 Pro medium as high.
func TestGeminiLaterGenerationsToldALevel(t *testing.T) {
fresh(t)
os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755)
os.WriteFile(catalog.CachePath(), []byte(`{"google-vertex":{"models":{
"gemini-4-argon":{"id":"gemini-4-argon","reasoning_options":[{"type":"effort","values":["low","medium","high"]}]},
"gemini-3.8-flash":{"id":"gemini-3.8-flash","reasoning_options":[{"type":"effort","values":["low","medium","high"]}]},
"gemini-2.5-flash":{"id":"gemini-2.5-flash","reasoning_options":[{"type":"effort","values":["low","medium","high"]}]}}}}`), 0o644)
catalog.Reset()
t.Cleanup(catalog.Reset)
var mu sync.Mutex
asked := map[string]map[string]any{}
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
var body map[string]any
json.Unmarshal(b, &body)
model := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/v1beta/models/"), ":streamGenerateContent")
gen, _ := body["generationConfig"].(map[string]any)
tc, _ := gen["thinkingConfig"].(map[string]any)
mu.Lock()
asked[model] = tc
mu.Unlock()
if _, budget := tc["thinkingBudget"]; budget && strings.HasPrefix(model, "gemini-4") {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
io.WriteString(w, argonBudgetRefused)
return
}
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, vertexPong)
}))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "gv", Name: "Google", Key: "k", Catalog: "google-vertex",
Gemini: up.URL + "/v1beta", Models: []string{"gemini-4-argon", "gemini-3.8-flash", "gemini-2.5-flash", "gemini-3-pro-preview"}}); err != nil {
t.Fatal(err)
}
s := New()
level := func(l string) map[string]any { return map[string]any{"thinkingLevel": l, "includeThoughts": true} }
budget := func(n float64) map[string]any { return map[string]any{"thinkingBudget": n, "includeThoughts": true} }
for _, c := range []struct {
path, model, effort string
want map[string]any
}{
{"/v1/chat/completions", "gemini-4-argon", "low", level("low")},
{"/v1/chat/completions", "gemini-4-argon", "medium", level("medium")},
{"/v1/chat/completions", "gemini-4-argon", "high", level("high")},
{"/v1/responses", "gemini-4-argon", "high", level("high")},
{"/v1/chat/completions", "gemini-3.8-flash", "low", level("low")},
{"/v1/chat/completions", "gemini-3.8-flash", "medium", level("medium")},
{"/v1/chat/completions", "gemini-3.8-flash", "high", level("high")},
{"/v1/chat/completions", "gemini-3-pro-preview", "medium", level("high")},
{"/v1/chat/completions", "gemini-2.5-flash", "high", budget(24000)},
} {
body := `{"model":"gv/` + c.model + `","stream":true,"reasoning_effort":"` + c.effort + `","messages":[{"role":"user","content":"hi"}]}`
if c.path == "/v1/responses" {
body = `{"model":"gv/` + c.model + `","stream":true,"reasoning":{"effort":"` + c.effort + `"},"input":"hi"}`
}
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", c.path, strings.NewReader(body)))
if rec.Code != http.StatusOK {
t.Errorf("%s %s at %s: status %d: %s", c.path, c.model, c.effort, rec.Code, rec.Body.String())
continue
}
mu.Lock()
got := asked[c.model]
mu.Unlock()
if !maps.Equal(got, c.want) {
t.Errorf("%s %s at %s: thinkingConfig %v, want %v", c.path, c.model, c.effort, got, c.want)
}
}
}
// geminiGeneration reads the generation from the id however it is
// written; an id that names none, an alias among them, is 0 and keeps its
// budget.
func TestGeminiGeneration(t *testing.T) {
for id, want := range map[string]int{
"gemini-4-argon": 4, "models/gemini-4-argon": 4, "gemini-3.8-flash": 3, "gemini-2.5-pro": 2,
"gemini-10-pro": 10, "gemini-flash-latest": 0, "argon-gemini-3": 0, "gemma-3-27b-it": 0, "claude-sonnet-4-5": 0,
} {
if got := geminiGeneration(id); got != want {
t.Errorf("%s: %d, want %d", id, got, want)
}
}
}