From d6784bd1147be944dce2d91809fd3ae55bc38ff2 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 25 Sep 2026 14:54:21 +0800 Subject: [PATCH] =?UTF-8?q?codex:=20a=20model=20a=20custom=20provider=20se?= =?UTF-8?q?rves=20takes=20the=20reasoning=20levels=20models.dev=20gives=20?= =?UTF-8?q?it=20from=20the=20others=20serving=20it,=20so=20the=20Codex=20a?= =?UTF-8?q?pp=20offers=20an=20effort=20for=20it=20(a=20Volcengine=20endpoi?= =?UTF-8?q?nt's=20glm-5.3-flash=20showed=20=E4=B8=AD=20with=20nothing=20to?= =?UTF-8?q?=20pick,=20and=20magpie's=20effort=20control=20a=20"none"=20Cod?= =?UTF-8?q?ex=20never=20used)=20=E2=80=94=20levels=20were=20only=20taken?= =?UTF-8?q?=20from=20models.dev's=20entry=20for=20the=20vendor=20itself,?= =?UTF-8?q?=20and=20a=20vendor=20it=20doesn't=20list=20(a=20custom=20provi?= =?UTF-8?q?der,=20a=20proxy)=20had=20none,=20so=20Codex's=20catalog=20carr?= =?UTF-8?q?ied=20no=20supported=5Freasoning=5Flevels;=20a=20model=20models?= =?UTF-8?q?.dev=20doesn't=20list=20for=20its=20vendor=20now=20takes,=20by?= =?UTF-8?q?=20bare=20id=20as=20the=20context=20window=20is=20found,=20the?= =?UTF-8?q?=20levels=20most=20of=20the=20providers=20giving=20any=20give?= =?UTF-8?q?=20it=20(glm-5.3-flash:=20low,=20high,=20max,=20default=20high)?= =?UTF-8?q?,=20one=20no=20one=20gives=20levels=20for=20keeps=20none.=20Cod?= =?UTF-8?q?ex's=20effort=20is=20settled=20on=20one=20the=20model=20takes?= =?UTF-8?q?=20when=20a=20model=20is=20picked=20and=20when=20the=20catalog?= =?UTF-8?q?=20is=20synced,=20magpie=20shows=20the=20catalog's=20default=20?= =?UTF-8?q?where=20none=20is=20set,=20and=20the=20gateway=20sends=20a=20Ch?= =?UTF-8?q?at=20vendor=20reasoning=5Feffort=20at=20the=20model's=20nearest?= =?UTF-8?q?=20level=20(Codex's=20medium=20goes=20to=20glm-5.3-flash=20as?= =?UTF-8?q?=20high),=20as=20asked=20where=20the=20model's=20are=20not=20kn?= =?UTF-8?q?own?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/agent/codex.go | 32 ++++++++-- internal/agent/codex_effort_test.go | 97 +++++++++++++++++++++++++++++ internal/catalog/catalog.go | 69 ++++++++++++++++++-- internal/catalog/catalog_test.go | 28 +++++++++ internal/gateway/effort_test.go | 69 ++++++++++++++++++++ internal/gateway/gateway.go | 6 ++ internal/gateway/ir.go | 34 ++++++++++ internal/provider/models.go | 24 ++++++- 8 files changed, 347 insertions(+), 12 deletions(-) create mode 100644 internal/agent/codex_effort_test.go create mode 100644 internal/gateway/effort_test.go diff --git a/internal/agent/codex.go b/internal/agent/codex.go index 326b54bac..2168d8e33 100644 --- a/internal/agent/codex.go +++ b/internal/agent/codex.go @@ -203,12 +203,22 @@ func codex(home string) *Agent { switch { case asProvider() && get("model_catalog_json") == catalogPath: b := codexcat.Catalog(magpieModels()) - if cur, _ := edit.Read(catalogPath); string(cur) == string(b) { - return nil + if cur, _ := edit.Read(catalogPath); string(cur) != string(b) { + if err := edit.WriteAtomic(catalogPath, b); err != nil { + return err + } } - return edit.WriteAtomic(catalogPath, b) case viaBase(): - return codexStaleCache(filepath.Join(dir, "models_cache.json"), codexcat.Tag(provider.CodexListed())) + if err := codexStaleCache(filepath.Join(dir, "models_cache.json"), codexcat.Tag(provider.CodexListed())); err != nil { + return err + } + default: + return nil + } + // a model that now has levels it had none of before (models.dev + // synced, a vendor's list fetched) keeps an effort it takes + if isMagpie(get("model")) { + return settle() } return nil }, @@ -229,7 +239,19 @@ func codex(home string) *Agent { }, { Key: "effort", Label: "effort", - Get: func() string { return get("model_reasoning_effort") }, + // unset, Codex takes the model's default, as the catalog + // magpie wrote says it — shown as such rather than as none + Get: func() string { + if e := get("model_reasoning_effort"); e != "" { + return e + } + if m := get("model"); isMagpie(m) { + if e := catalog.Efforts(models(), m); len(e) > 0 { + return codexcat.DefaultEffort(e) + } + } + return "" + }, Set: func(v string) error { if v == "" { return edit.DelTOMLTop(path, "model_reasoning_effort") diff --git a/internal/agent/codex_effort_test.go b/internal/agent/codex_effort_test.go new file mode 100644 index 000000000..2cfeca912 --- /dev/null +++ b/internal/agent/codex_effort_test.go @@ -0,0 +1,97 @@ +package agent + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +// A custom provider serving a model models.dev knows from others (a +// Volcengine endpoint's glm-5.3-flash) hands Codex the reasoning levels +// those give it: the catalog entry had none, so the Codex app offered no +// effort and magpie's own control showed a level Codex never used. +func TestCodexCustomProviderModelHasEfforts(t *testing.T) { + home, read := codexHome(t, "", "model_reasoning_effort = \"none\"\n") + os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755) + os.WriteFile(catalog.CachePath(), []byte(`{ + "zai":{"models":{"glm-5.3-flash":{"id":"glm-5.3-flash","reasoning_options":[{"type":"effort","values":["low","high","max"]}]}, + "glm-4.5-air":{"id":"glm-4.5-air"}}}}`), 0o644) + catalog.Reset() + t.Cleanup(catalog.Reset) + if err := provider.Save(provider.Provider{ID: "volc", Name: "Volc", Key: "k", Chat: "http://127.0.0.1:1/api/v3", + Models: []string{"glm-5.3-flash", "glm-4.5-air"}}); err != nil { + t.Fatal(err) + } + cx := codex(home) + if err := cx.Fields[0].Set("volc/glm-5.3-flash"); err != nil { + t.Fatal(err) + } + if cfg := read(); !strings.Contains(cfg, `model_reasoning_effort = "high"`) { + t.Fatalf("effort not settled on the model's default:\n%s", cfg) + } + b, _ := os.ReadFile(filepath.Join(home, ".codex", "magpie-models.json")) + var cat struct { + Models []struct { + Slug string `json:"slug"` + Default *string `json:"default_reasoning_level"` + Levels []struct { + Effort string `json:"effort"` + } `json:"supported_reasoning_levels"` + } `json:"models"` + } + if err := json.Unmarshal(b, &cat); err != nil { + t.Fatal(err) + } + got := map[string]string{} + for _, m := range cat.Models { + var ls []string + for _, l := range m.Levels { + ls = append(ls, l.Effort) + } + d := "" + if m.Default != nil { + d = *m.Default + } + got[m.Slug] = strings.Join(ls, ",") + " / " + d + } + if got["volc/glm-5.3-flash"] != "low,high,max / high" { + t.Errorf("glm-5.3-flash: %q", got["volc/glm-5.3-flash"]) + } + // a model no one says reasons keeps none + if got["volc/glm-4.5-air"] != " / " { + t.Errorf("glm-4.5-air: %q", got["volc/glm-4.5-air"]) + } + effort := cx.Fields[1] + var opts []string + for _, o := range effort.Options(map[string]string{"model": "volc/glm-5.3-flash"}) { + opts = append(opts, o.Value) + } + if strings.Join(opts, ",") != "low,high,max" { + t.Errorf("effort options: %v", opts) + } + + // unset, the control shows what Codex takes: the catalog's default + if err := effort.Set(""); err != nil { + t.Fatal(err) + } + if v := effort.Get(); v != "high" { + t.Errorf("unset effort shows %q", v) + } + + // a level the model doesn't take, left from before, is settled when + // the catalog is synced + if err := effort.Set("none"); err != nil { + t.Fatal(err) + } + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + if cfg := read(); !strings.Contains(cfg, `model_reasoning_effort = "high"`) { + t.Errorf("sync left the effort:\n%s", cfg) + } +} diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go index 33387882c..29ea35774 100644 --- a/internal/catalog/catalog.go +++ b/internal/catalog/catalog.go @@ -82,6 +82,17 @@ type mdModel struct { } `json:"limit"` } +// efforts are the reasoning levels models.dev says the model takes. +func (m mdModel) efforts() []string { + var out []string + for _, r := range m.Reasoning { + if r.Type == "effort" { + out = r.Values + } + } + return out +} + // window is the tokens a prompt to m may hold: the input limit where // models.dev gives one (gpt-5's 272K of its 400K), else the whole context. func (m mdModel) window() int { @@ -102,6 +113,9 @@ var ( // windows are the models' context windows, by bare id, as most of the // providers serving them give it windows map[string]int + // efforts are the models' reasoning levels, by bare id, as most of the + // providers that give any for them give them + efforts map[string][]string syncMu sync.Mutex ) @@ -142,8 +156,15 @@ func load() map[string]mdProvider { mdev = m votes := map[string]int{} sizes := map[string]map[int]int{} + levels := map[string]map[string]int{} for _, p := range m { for id, x := range p.Models { + if e := x.efforts(); len(e) > 0 { + if levels[bareID(id)] == nil { + levels[bareID(id)] = map[string]int{} + } + levels[bareID(id)][strings.Join(e, ",")]++ + } if slices.Contains(x.Modalities.Input, "image") { votes[bareID(id)]++ } else { @@ -161,6 +182,10 @@ func load() map[string]mdProvider { for id, by := range sizes { windows[id] = mostGiven(by) } + efforts = map[string][]string{} + for id, by := range levels { + efforts[id] = strings.Split(mostListed(by), ",") + } images = map[string]bool{} for id, v := range votes { if v > 0 { @@ -177,7 +202,7 @@ func load() map[string]mdProvider { // Reset forgets the loaded catalog so the next call re-reads the cache. func Reset() { once = sync.Once{} - mdev, images, windows = nil, nil, nil + mdev, images, windows, efforts = nil, nil, nil, nil } // Sync downloads the models.dev catalog into CachePath. It serializes with @@ -272,11 +297,7 @@ func Provider(id string) []Model { } mm := Model{ID: m.ID, Name: m.Name, Provider: id, Released: m.ReleaseDate, Price: m.Cost, Temperature: m.Temperature, Images: slices.Contains(m.Modalities.Input, "image"), Context: m.window()} - for _, r := range m.Reasoning { - if r.Type == "effort" { - mm.Efforts = r.Values - } - } + mm.Efforts = m.efforts() out = append(out, mm) } sort.SliceStable(out, func(i, j int) bool { @@ -327,6 +348,42 @@ func ContextOf(id string) int { return 0 } +// EffortsOf is the reasoning levels models.dev gives a model of this id, as +// most of the providers giving any for it do, or nil when none does. Like +// ContextOf it reaches a vendor models.dev doesn't list: a custom provider +// serving "glm-5.3-flash" takes the levels Z.ai and the others serving it +// say it does, where it would otherwise be taken for a model that doesn't +// reason, and an agent offer no levels for it. +func EffortsOf(id string) []string { + load() + b := bareID(id) + if e, ok := efforts[b]; ok { + return slices.Clone(e) + } + if i := strings.IndexByte(b, '('); i > 0 && strings.HasSuffix(b, ")") { + b = b[:i] + if e, ok := efforts[b]; ok { + return slices.Clone(e) + } + } + if i := strings.IndexByte(b, ':'); i > 0 { // ":free", ":thinking" + return slices.Clone(efforts[b[:i]]) + } + return nil +} + +// mostListed is the list most providers give; a tie goes to the shorter, +// then the first in order, so the answer doesn't change from run to run. +func mostListed(by map[string]int) string { + best, n := "", 0 + for l, c := range by { + if c > n || c == n && (strings.Count(l, ",") < strings.Count(best, ",") || strings.Count(l, ",") == strings.Count(best, ",") && l < best) { + best, n = l, c + } + } + return best +} + // mostGiven is the size most providers give; a tie goes to the smaller, // which a prompt fits either way. func mostGiven(by map[int]int) int { diff --git a/internal/catalog/catalog_test.go b/internal/catalog/catalog_test.go index c80c0179f..1a96ac0b6 100644 --- a/internal/catalog/catalog_test.go +++ b/internal/catalog/catalog_test.go @@ -3,6 +3,7 @@ package catalog import ( "os" "path/filepath" + "strings" "testing" ) @@ -125,3 +126,30 @@ func TestContextOf(t *testing.T) { t.Errorf("Decorate: %+v", out[0]) } } + +// A vendor models.dev doesn't list takes the levels the providers serving +// the model give; one that gives none (a toggle, nothing) doesn't vote. +func TestEffortsOf(t *testing.T) { + writeCatalog(t, `{ + "zai": {"models": {"glm-5.3-flash": {"id":"glm-5.3-flash","reasoning_options":[{"type":"effort","values":["low","high","max"]}]}}}, + "a": {"models": {"z-ai/glm-5.3-flash": {"id":"z-ai/glm-5.3-flash","reasoning_options":[{"type":"effort","values":["low","high","max"]}]}}}, + "b": {"models": {"glm-5.3-flash": {"id":"glm-5.3-flash","reasoning_options":[{"type":"effort","values":["none","low","medium","high"]}]}, + "glm-5": {"id":"glm-5","reasoning_options":[{"type":"toggle"}]}, + "deepseek-chat": {"id":"deepseek-chat"}}}, + "c": {"models": {"glm-5.3-flash": {"id":"glm-5.3-flash","reasoning_options":[{"type":"toggle"}]}}} + }`) + for id, want := range map[string]string{ + "glm-5.3-flash": "low,high,max", + "GLM-5.3-Flash": "low,high,max", + "volc/glm-5.3-flash": "low,high,max", + "glm-5.3-flash:free": "low,high,max", + "glm-5.3-flash(high)": "low,high,max", + "glm-5": "", + "deepseek-chat": "", + "unknown-model": "", + } { + if got := strings.Join(EffortsOf(id), ","); got != want { + t.Errorf("EffortsOf(%q) = %q, want %q", id, got, want) + } + } +} diff --git a/internal/gateway/effort_test.go b/internal/gateway/effort_test.go new file mode 100644 index 000000000..f944289cf --- /dev/null +++ b/internal/gateway/effort_test.go @@ -0,0 +1,69 @@ +package gateway + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/provider" +) + +func TestFitEffort(t *testing.T) { + glm := []string{"low", "high", "max"} + for _, c := range []struct { + want string + levels []string + got string + }{ + {"medium", glm, "high"}, // a tie goes up + {"low", glm, "low"}, + {"xhigh", glm, "max"}, + {"max", []string{"low", "medium", "high"}, "high"}, + {"low", []string{"none", "minimal", "medium"}, "medium"}, + {"medium", nil, "medium"}, // levels not known: as asked + {"medium", []string{"none"}, "medium"}, + } { + if got := fitEffort(c.want, c.levels); got != c.got { + t.Errorf("fitEffort(%q, %v) = %q, want %q", c.want, c.levels, got, c.got) + } + } +} + +// Codex's effort reaches a custom OpenAI-compatible provider as +// reasoning_effort, at a level the model takes: glm-5.3-flash takes low, +// high and max, as models.dev has it from those serving it, so Codex's +// "medium" goes as "high"; a model no one gives levels for gets what was +// asked. +func TestResponsesEffortReachesChatVendor(t *testing.T) { + f := &fake{t: t, reply: sse( + `data: {"id":"c1","model":"glm-5.3-flash","choices":[{"delta":{"role":"assistant","content":"hi"}}]}`, + `data: {"id":"c1","choices":[{"delta":{},"finish_reason":"stop"}]}`, + `data: [DONE]`)} + up := setup(t, provider.Chat, f) + os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755) + os.WriteFile(catalog.CachePath(), []byte(`{"zai":{"models":{"glm-5.3-flash":{"id":"glm-5.3-flash","reasoning_options":[{"type":"effort","values":["low","high","max"]}]}}}}`), 0o644) + catalog.Reset() + t.Cleanup(catalog.Reset) + if err := provider.Save(provider.Provider{ID: "volc", Name: "Volc", Key: "k", Chat: up.URL + "/v1", Models: []string{"glm-5.3-flash", "other"}}); err != nil { + t.Fatal(err) + } + for _, c := range []struct{ model, effort, sent string }{ + {"volc/glm-5.3-flash", "medium", "high"}, + {"volc/glm-5.3-flash", "max", "max"}, + {"volc/glm-5.3-flash", "low", "low"}, + {"volc/other", "medium", "medium"}, + } { + code, body := post(t, "/v1/responses", `{"model":"`+c.model+`","stream":true,"input":"hi","reasoning":{"effort":"`+c.effort+`"}}`) + if code != 200 { + t.Fatalf("status %d: %s", code, body) + } + var got map[string]any + json.Unmarshal(f.got, &got) + if got["reasoning_effort"] != c.sent || !strings.HasSuffix(f.path, "/chat/completions") { + t.Errorf("%s at %s: sent %s", c.model, c.effort, f.got) + } + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 2d2dd91d3..41ae6dc3a 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -688,6 +688,12 @@ func responsesFirst(p provider.Provider, model string) bool { // served on this one, the request is built again for the next endpoint it // speaks, and the model is remembered there. func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to provider.Protocol, req *Request, model string, in http.Header) (*http.Response, provider.Protocol, error) { + if req.Effort != "" { + if e := fitEffort(req.Effort, p.Efforts(model)); e != req.Effort { + r := *req + r.Effort, req = e, &r + } + } for { body := build(to, req, model, p.Host(), p.RejectsTemperature(model)) res, err := s.forward(ctx, p, to, pathOf(to), p.Prepare(body), in) diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go index ab4e05e09..a0c4ad8c2 100644 --- a/internal/gateway/ir.go +++ b/internal/gateway/ir.go @@ -7,6 +7,7 @@ package gateway import ( "encoding/json" + "slices" "strings" ) @@ -307,6 +308,39 @@ func effortOf(s string) string { return "" } +// effortRank orders the reasoning levels agents and vendors name. +var effortRank = []string{"none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"} + +// fitEffort is the level of the model's own nearest the one asked for — a +// tie goes up — or the one asked for when the model's aren't known. Codex +// asks "medium" of a model it was given no levels for, and an agent's +// setting can outlive the model it was picked for; GLM-5.3 takes low, high +// and max only. +func fitEffort(want string, levels []string) string { + if len(levels) == 0 || slices.Contains(levels, want) { + return want + } + at := slices.Index(effortRank, want) + if at < 0 { + return want + } + best, dist := want, len(effortRank) + for _, l := range levels { + i := slices.Index(effortRank, l) + if i < 0 || l == "none" { + continue + } + d := i - at + if d < 0 { + d = -d + } + if d < dist || d == dist && i > at { + best, dist = l, d + } + } + return best +} + // budgetOf is the Anthropic thinking budget for an effort level. func budgetOf(effort string) int { switch effort { diff --git a/internal/provider/models.go b/internal/provider/models.go index 5b3d70a9e..58370f1d3 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -214,6 +214,28 @@ func (p Provider) RejectsTemperature(model string) bool { return false } +// Efforts are the reasoning levels the model takes, when known. +func (p Provider) Efforts(model string) []string { + for _, m := range p.Available() { + if m.ID == model { + return effortsOf(m) + } + } + return catalog.EffortsOf(model) +} + +// effortsOf is a model's reasoning levels: its vendor's, as models.dev +// lists them, or — for a vendor models.dev doesn't list the model under (a +// custom provider, a proxy) — the ones the others serving it give. A model +// models.dev lists for this vendor without levels takes none: the vendor +// says it has none to pick from. +func effortsOf(m catalog.Model) []string { + if len(m.Efforts) > 0 || m.Provider != "" { + return m.Efforts + } + return catalog.EffortsOf(m.ID) +} + // Chosen reports whether a model is exposed. func (p Provider) Chosen(id string) bool { for _, m := range p.Exposed() { @@ -266,7 +288,7 @@ func providerEntries() []Entry { if ctx == 0 { ctx = catalog.ContextOf(m.ID) } - out = append(out, Entry{ID: p.ID + "/" + m.ID, Model: m.ID, Name: m.Name, Efforts: m.Efforts, Provider: p, + out = append(out, Entry{ID: p.ID + "/" + m.ID, Model: m.ID, Name: m.Name, Efforts: effortsOf(m), Provider: p, Images: m.Images || catalog.SeesImages(m.ID), Context: ctx}) } }