diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index e7d43118a..649578549 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -74,7 +74,19 @@ model the user just switched from. A call tied to no seen thread whose key's last turn is older than 3s (`codexSideFresh`) waits, up to 5s (`codexSideWait`) or its cancellation, for the next turn and takes its model (`codexLeads.sideOf`, `TestCodexTitleBeforeTheFirstTurnFollowsTheSwitch`); -a later rename suggestion with no turn beside it waits the 5s. A session on Codex's +a later rename suggestion with no turn beside it waits the 5s. Codex +asks a title with no reasoning effort on any model but its own title +model, and its auto-review at a model's default, which it has none of for +magpie's models; a model that needs an effort answered those with 400 +(cybercaius on Discord). A title, description, summary, prediction, +auto-review or memory call on one of magpie's models whose levels are +known, asking no effort or an off one the model hasn't, is asked at its +lowest on level (`codexSideEffort`, `TestCodexSideCallAskedAtAnEffortTheModelTakes`). +Wherever the levels aren't known, serve asks any request again once at +its lowest (low) when the upstream turns no effort or none away as needing +one, matched on the error body (`effortRequired`, on Chat and Responses, +forwarded or translated; `TestEffortRequiredRefusalAskedAgainAtLow`); any +other 400 goes back as it came (`TestOtherBadRequestNotAskedAgainAtLow`). A session on Codex's own model sends them to ChatGPT as Codex sent them, whatever the config says (`TestCodexAppSideTurnsStayWithAnOwnModelSession`); so does a session model magpie can't serve now (turned off, gone, held from the caller's key). Summaries use diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 9b5353e17..736058a04 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -167,6 +167,11 @@ func (s *Server) codexBackend(w http.ResponseWriter, r *http.Request) { writeError(w, provider.Responses, 400, "/responses/compact is not supported for Magpie models; use a compaction_trigger on /responses") return } + if kind == "guardian" || isMemoryKind(kind) { + // an auto-review or a memory call, at an effort the + // model takes (codexSideEffort) + body = codexSideEffort(body, model) + } // a sealed subagent task goes to a ChatGPT account the model // or group has, or is turned away (serve, sealedReader) // a provider set to compact natively is asked Codex's own diff --git a/internal/gateway/codex_side_effort_test.go b/internal/gateway/codex_side_effort_test.go new file mode 100644 index 000000000..87c2c8341 --- /dev/null +++ b/internal/gateway/codex_side_effort_test.go @@ -0,0 +1,186 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// needsEffort is an upstream whose model turns away a request with no +// reasoning effort, or none, as cybercaius's did for Codex's side calls; +// refusal is what it answers then. +type needsEffort struct { + mu sync.Mutex + got []string + refusal string +} + +func (f *needsEffort) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + f.mu.Lock() + f.got = append(f.got, string(b)) + f.mu.Unlock() + if e := f.effortOf(string(b)); e == "" || e == "none" { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + io.WriteString(w, f.refusal) + return + } + w.Header().Set("Content-Type", "text/event-stream") + if strings.HasSuffix(r.URL.Path, "/chat/completions") { + io.WriteString(w, sse(`data: {"id":"c1","choices":[{"index":0,"delta":{"content":"{\"title\":\"Fix the build\"}"}}]}`, + `data: {"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, `data: [DONE]`)) + return + } + io.WriteString(w, sse(`data: {"type":"response.output_text.delta","delta":"{\"title\":\"Fix the build\"}"}`, + `data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"{\"title\":\"Fix the build\"}"}]}]}}`)) +} + +// effortOf is the reasoning effort a Responses or Chat body asks for. +func (f *needsEffort) effortOf(body string) string { + var v struct { + ReasoningEffort string `json:"reasoning_effort"` + Reasoning *struct { + Effort string `json:"effort"` + } `json:"reasoning"` + } + _ = json.Unmarshal([]byte(body), &v) + if v.Reasoning != nil { + return v.Reasoning.Effort + } + return v.ReasoningEffort +} + +func (f *needsEffort) efforts() []string { + f.mu.Lock() + defer f.mu.Unlock() + var out []string + for _, b := range f.got { + out = append(out, f.effortOf(b)) + } + return out +} + +const effortRequiredBody = `{"error":{"message":"Reasoning effort is required for this model","type":"invalid_request_error","param":"reasoning.effort"}}` + +// needsEffortOn is provider id serving m1 through f, on Responses or, +// with chat, on Chat Completions alone. +func needsEffortOn(t *testing.T, id string, chat bool, refusal string) *needsEffort { + t.Helper() + f := &needsEffort{refusal: refusal} + up := httptest.NewServer(f) + t.Cleanup(up.Close) + p := provider.Provider{ID: id, Name: strings.ToUpper(id), Key: "sk-" + id, Models: []string{"m1"}, Responses: up.URL + "/v1"} + if chat { + p.Responses, p.Chat = "", up.URL+"/v1" + } + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + return f +} + +// codexTitleOn is the Codex title Codex asks on model, the conversation's +// own: Codex sends it with no reasoning effort, as it does on any model +// but its own title model. +func codexTitleOn(s *Server, model string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + body := `{"model":"` + model + `","stream":true,"input":[` + leadAsk + `]}` + req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer chatgpt-token") + req.Header.Set("chatgpt-account-id", "acct-1") + req.Header.Set("session_id", "title-thread") + req.Header.Set("x-codex-turn-metadata", `{"thread_source":"thread_title"}`) + s.Handler().ServeHTTP(rec, req) + return rec +} + +// cybercaius on Discord: Codex's side calls went with no effort to a +// model that needs one, which answered 400. With the model's levels known, +// a title is asked at its lowest on level from the start. +func TestCodexSideCallAskedAtAnEffortTheModelTakes(t *testing.T) { + fresh(t) + up := needsEffortOn(t, "fx", false, effortRequiredBody) + if err := provider.SetModelEfforts("fx/m1", []string{"low", "medium", "high"}); err != nil { + t.Fatal(err) + } + s := New() + if rec := codexTitleOn(s, "fx/m1"); rec.Code != 200 { + t.Fatalf("title: %d %s", rec.Code, rec.Body.String()) + } + if got := up.efforts(); len(got) != 1 || got[0] != "low" { + t.Fatalf("the upstream was asked at %q", got) + } + // Codex's auto-review, asked with no effort on a model of magpie's + // whose levels Codex isn't told + if rec := codexAsks(s, "fx/m1", "guardian", leadAsk); rec.Code != 200 { + t.Fatalf("auto-review: %d %s", rec.Code, rec.Body.String()) + } + if got := up.efforts(); len(got) != 2 || got[1] != "low" { + t.Fatalf("the upstream was asked at %q", got) + } +} + +// A model whose levels magpie doesn't know, turning a request with no +// effort away as needing one, is asked again once at low, on Responses +// and on Chat Completions. +func TestEffortRequiredRefusalAskedAgainAtLow(t *testing.T) { + for _, chat := range []bool{false, true} { + fresh(t) + up := needsEffortOn(t, "fx", chat, effortRequiredBody) + s := New() + if rec := codexTitleOn(s, "fx/m1"); rec.Code != 200 { + t.Fatalf("chat %v: title: %d %s", chat, rec.Code, rec.Body.String()) + } + if got := up.efforts(); len(got) != 2 || got[0] != "" || got[1] != "low" { + t.Fatalf("chat %v: the upstream was asked at %q", chat, got) + } + } +} + +// Any other 400 to a request with no effort goes back as it came, asked +// once. +func TestOtherBadRequestNotAskedAgainAtLow(t *testing.T) { + for _, chat := range []bool{false, true} { + fresh(t) + up := needsEffortOn(t, "fx", chat, `{"error":{"message":"max_output_tokens is too large: 999999999","type":"invalid_request_error"}}`) + s := New() + if rec := codexTitleOn(s, "fx/m1"); rec.Code != 400 { + t.Fatalf("chat %v: title: %d %s", chat, rec.Code, rec.Body.String()) + } + if got := up.efforts(); len(got) != 1 { + t.Fatalf("chat %v: the upstream was asked %d times, at %q", chat, len(got), got) + } + } +} + +func TestEffortRequiredWords(t *testing.T) { + for _, m := range []string{ + "Reasoning effort is required for this model", + "Missing required parameter: 'reasoning.effort'.", + "This model requires a reasoning effort", + "reasoning_effort is mandatory", + "Reasoning is mandatory for this endpoint and cannot be disabled.", + "reasoning cannot be disabled for this model", + } { + if !effortRequired.MatchString(m) { + t.Errorf("%q not read as an effort required", m) + } + } + for _, m := range []string{ + "Unsupported parameter: 'reasoning.effort' is not supported with this model.", + "Reasoning effort 'none' is not supported for this model. Supported values are: 'low', 'medium', 'high'.", + "max_output_tokens is too large", + "This model does not support reasoning", + } { + if effortRequired.MatchString(m) { + t.Errorf("%q read as an effort required", m) + } + } +} diff --git a/internal/gateway/codex_titles.go b/internal/gateway/codex_titles.go index eb08cbb14..f97347645 100644 --- a/internal/gateway/codex_titles.go +++ b/internal/gateway/codex_titles.go @@ -6,6 +6,7 @@ import ( "encoding/json" "fmt" "net/http" + "slices" "strings" "time" @@ -159,7 +160,7 @@ func (s *Server) codexTitle(w http.ResponseWriter, r *http.Request, body []byte, // caller's key (#882) ctx = magpieChose(ctx) } - s.serve(rec, r.WithContext(ctx), provider.Responses, withModel(body, to)) + s.serve(rec, r.WithContext(ctx), provider.Responses, codexSideEffort(withModel(body, to), to)) if rec.status >= 400 { for k, vs := range rec.header { w.Header()[k] = vs @@ -227,7 +228,7 @@ func (s *Server) codexShaped(w http.ResponseWriter, r *http.Request, body []byte if chose { ctx = magpieChose(ctx) } - s.serve(rec, r.WithContext(ctx), provider.Responses, withModel(body, to)) + s.serve(rec, r.WithContext(ctx), provider.Responses, codexSideEffort(withModel(body, to), to)) if rec.status >= 400 { for k, vs := range rec.header { w.Header()[k] = vs @@ -280,7 +281,7 @@ func (s *Server) codexPrediction(w http.ResponseWriter, r *http.Request, body [] if to == settings.Load().CodexPredictions { ctx = magpieChose(ctx) } - s.serve(rec, r.WithContext(ctx), provider.Responses, withModel(body, to)) + s.serve(rec, r.WithContext(ctx), provider.Responses, codexSideEffort(withModel(body, to), to)) if rec.status >= 400 { for k, vs := range rec.header { w.Header()[k] = vs @@ -673,3 +674,33 @@ func titleJSON(said string, shape titleShape) string { b, _ := json.Marshal(out) return string(b) } + +// codexSideEffort is a Codex side call's body for to, one of magpie's +// models, asking a reasoning effort to takes. Codex asks low for a title +// only on its own title model, and none (no effort) on any other; its +// auto-review asks low only where the model lists low, else the model's +// default, which Codex has none of for a model of magpie's whose levels +// it isn't told. A model that needs an effort turned those away with 400 +// (cybercaius on Discord). With the model's levels known, a call asking +// no effort, or an off one the model hasn't, is asked at its lowest on +// level, low where it has it; any other effort, a group, or a model whose +// levels aren't known goes as asked (serve's effortRequired retry then +// asks the last at low if it turns the request away). +func codexSideEffort(body []byte, to string) []byte { + if provider.IsGroupRef(to) { + return body + } + e := bodyEffort(provider.Responses, body) + if e != "" && !offEffort(e) { + return body + } + levels := ModelEfforts(to) + if len(levels) == 0 || slices.Contains(levels, e) { + return body + } + p, model, ok := provider.Resolve(to) + if !ok { + return body + } + return withFixedEffort(provider.Responses, body, onEffort(p, model)) +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 2da3861eb..85937d40e 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -4778,6 +4778,7 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. s.markUnfit(p.ID, f, proto) } } + offRetried := false if e := bodyEffort(proto, body); res.StatusCode == http.StatusBadRequest && (e == "none" || e == "minimal" || proto == provider.Chat && hasReasoningDisabled(body)) { // A model can refuse reasoning turned off. If it names its levels, // or Gemini the level it hasn't, try its lowest, and from then on; @@ -4794,17 +4795,37 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. refused = levelRefused(model, e) } s.markUnfit(p.ID, refused, proto) + offRetried = true if res, err = s.forward(r.Context(), p, proto, path, p.Prepare(withBodyEffort(proto, body, onEffort(p, model))), r.Header); err != nil { return writeError(w, proto, 502, p.Name+": "+err.Error()), err.Error(), true } } else if proto == provider.Chat && mandatoryReasoning.Match(b) { if nb, ok := withoutReasoningOff(body); ok { + offRetried = true if res, err = s.forward(r.Context(), p, proto, path, p.Prepare(nb), r.Header); err != nil { return writeError(w, proto, 502, p.Name+": "+err.Error()), err.Error(), true } } } } + if e := bodyEffort(proto, body); res.StatusCode == http.StatusBadRequest && proto != provider.Anthropic && !offRetried && (e == "" || offEffort(e)) { + // no reasoning effort, or none, turned away by a model that needs + // one (a Codex title on a model other than its own asks none, + // cybercaius on Discord): asked again once at its lowest, low + // where its levels aren't known. Only that refusal: any other 400 + // goes back as it came + b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + res.Body.Close() + res.Body = io.NopCloser(bytes.NewReader(b)) + if effortRequired.Match(b) { + if offEffort(e) { + s.markUnfit(p.ID, offRefused(model), proto) + } + if res, err = s.forward(r.Context(), p, proto, path, p.Prepare(withFixedEffort(proto, body, onEffort(p, model))), r.Header); err != nil { + return writeError(w, proto, 502, p.Name+": "+err.Error()), err.Error(), true + } + } + } if proto == provider.Chat && res.StatusCode == http.StatusBadRequest && bodyEffort(proto, body) != "none" { // tools with reasoning refused on chat, and no Responses API to // take them to: asked again without reasoning (#176) @@ -5589,6 +5610,18 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to continue } } + if (req.Effort == "" || offEffort(req.Effort)) && beforeOff == nil && res.StatusCode == http.StatusBadRequest && effortRequired.Match(b) { + // no reasoning effort, or none, turned away by a model that + // needs one (a Codex title on a model other than its own + // asks none, cybercaius on Discord): asked again once at its + // lowest, low where its levels aren't known + if offEffort(req.Effort) { + s.markUnfit(p.ID, offRefused(model), to) + } + r := *req + r.Effort, req = onEffort(p, model), &r + continue + } if req.OwnEffort { if refused, value := ownEffortRefused(res.StatusCode, b, req.Effort); refused { // the effort magpie added for auto mode's classifier @@ -5694,6 +5727,14 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to // reasoning_effort to 'none'."). var toolsWithoutEffort = regexp.MustCompile(`(?is)tools with reasoning_effort are not supported.*reasoning_effort to .?none`) +// effortRequired is an upstream turning a request away for asking no +// reasoning effort, or none, from a model that needs one: "reasoning +// effort is required", "missing required parameter: reasoning.effort", +// "this model requires a reasoning effort", "reasoning cannot be +// disabled". A refusal of a level the model hasn't, or of the field +// itself, is not one. +var effortRequired = regexp.MustCompile(`(?i)reasoning[ _.]?effort\W+(?:is\s+)?(?:required|mandatory|missing)\b|(?:missing|requires?|needs?)\s+(?:a\s+|the\s+)?(?:required\s+)?(?:parameter\W+)?reasoning(?:[ _.]?effort)?\b|reasoning\s+is\s+(?:required|mandatory)\b|reasoning\W+(?:cannot|can't|can not)\s+be\s+(?:disabled|turned off)`) + // OpenRouter rejects an explicit reasoning-off request for some endpoints. var mandatoryReasoning = regexp.MustCompile(`(?i)reasoning is mandatory for this endpoint and cannot be disabled`)