provider, gateway, gui: a model with none of its levels ticked is sent no reasoning field, on every route and in a routing group (yuexian7)

yuexian7 on Discord: models.dev lists their model as reasoning, and the
vendor answers any reasoning parameter with 422 while the same request
without it works. In a routing group they couldn't set an effort per
model, and the model editor refused to untick the last level ("Keep at
least one level"). The learned refusals (bed306ae, #1062) don't cover
this: they learn a refusal of reasoning *off* and of Gemini levels, and
optionalFields holds thinking/enable_thinking, not reasoning_effort.

- settings.ModelReasonless, set by provider.SetModelReasonless (the
  provider editor's Names & levels with every level unticked, saved as
  modelPrefs {reasonless: true}; `magpie model efforts <ref> off`).
  Ticking levels again or Restore default clears it (setModelEfforts);
  setting it drops the model's kept levels.
- entryFor and Efforts/Thinks/Levelless: the model offers no levels and
  is Quiet, so agents are given none for it.
- Gateway: the candidate loop strips the body with withoutAnyReasoning
  in the agent's protocol (Chat/Responses reasoning_effort, reasoning,
  thinking, enable_thinking, include's reasoning.encrypted_content;
  Anthropic thinking of any type and output_config.effort; Gemini
  thinkingConfig). The Anthropic relay doesn't add
  thinking:{type:disabled} for it, and forwardTranslated clears Effort,
  ThinkOff and Thinking for its other callers (continuation, search).
- A routing group with it as a member keeps the other members' levels
  (it `continue`s like a member whose levels are unknown, #597), and the
  member that reasons is still sent the effort asked.
- GUI: none ticked shows "No reasoning field sent" beside the levels, in
  zh, zh-TW, ja and de too; a model with one known level now shows its
  picker so it can be unticked. A model whose levels aren't known
  (m.given) keeps none ticked meaning no levels known.

Run (worktree on origin/main 82f3befd2, sandbox HOME, private GOCACHE):
gofmt -l clean; with set -o pipefail go vet ./..., GOOS=linux go vet
-tags nogui ./..., GOOS=windows go vet ./... all clean; node --check
app.js. go test -count=1 ./internal/provider ./internal/gateway
./internal/settings ./internal/cli: ok. ./internal/gui: ok except
TestMainWindowCorners/macOS_15_SDK killed at its 40s deadline under
load (AppKit window measurement, untouched here; #1936, noted there).
The run caught TestSettingsSaveKeepsWhatItDoesNotSend (ModelReasonless
added to it) and the CLI usage alignment tests (fixed).
New tests and what breaking the change does: TestReasonlessModelSentNoReasoning
(Chat, Chat+enable_thinking, Responses with include, Anthropic->Chat
translated; by name and through group/mix) and TestReasonlessAnthropicRelay
fail with gateway.go/quiet.go reverted; TestGroupReasonlessMemberKeepsLevels
fails with group.go's reasonless branch disabled; TestModelReasonless
needs the new API. model-reasonless.test.cjs in chromium and webkit, at
1100 and 420, in en, zh, zh-TW, ja, de: 20/20; on the old assets all
fail. Related GUI tests 418/418 (one model-copy-id failure on a first
run under load, passed alone; #2066).
Not tried against the reporter's real vendor: the 422 is taken from
their report.
This commit is contained in:
yetone
2026-10-14 09:38:12 +08:00
parent 2971e1518f
commit f074996d93
15 changed files with 587 additions and 56 deletions
+1
View File
@@ -132,6 +132,7 @@ recorded as a prediction failure (`noPrediction`).
- A Claude that thinks only adaptively (`adaptiveOnly` in [`anthropic.go`](../../internal/gateway/anthropic.go): Opus, Sonnet and Haiku from 4.6 on, Fable and Mythos 5 and 5.1, read by `claudeVersion` however a relay spells them) is never sent a thinking budget, which they answer with 400. magpie's own request from a Chat or Responses client (`buildAnthropic`) goes as `thinking: {type: "adaptive", display: "summarized"}` with the effort in `output_config.effort`, so the client sees the reasoning Opus 4.7 and later otherwise leave out (display `omitted` by default), and a relay that refuses `display` is asked again without it (`refuseShapes`), as is one that refuses auto mode's `safeguards` (Copilot's Messages API: 400 "safeguards: Extra inputs are not permitted" on claude-opus-5.5, #1756; `shapeSafeguards`, `TestSafeguardsRefusedLeftOut`), and neither is sent it again while magpie runs; a client's `thinking: {type: "enabled", budget_tokens}` is turned into the same in `forwardOnce` (`adaptiveThinking`), the budget as its nearest effort, above `high` as `max`, and `display: "summarized"` unless the client named its own display, so the thinking that enabled shows stays shown (the refused shapes are taken out after it, and `refuseShapes` reads the display as it is sent); and Pi, dsh and omp are written to ask it adaptively (`AdaptiveThinking`: `forceAdaptiveThinking`, omp's `anthropic-adaptive`; #1470). A client's `xhigh` goes as `xhigh`, except to Opus and Sonnet 4.6, which have no `xhigh` and are asked `max` (`noXhigh`, #1471).
- A request to an Anthropic endpoint that turns thinking off is sent as the model takes it (`thinkingOffAsTaken`, in `forwardOnce`, so relayed requests, count_tokens, magpie's own thinking-off and retries all get it; the model is read as the vendor names it, from the body, or from the path for Bedrock and Vertex). Claude Sonnet 5.5 refuses `thinking: {type: "disabled"}` and is sent `{type: "between_tools"}` alone, at effort `high` at most. Opus 5.5, Fable 5 and Mythos 5 refuse it at every effort and are sent no thinking, at effort `low` unless one was asked, with `classifierRoom` added to a reply limit below it, as Claude Code does. Opus 5 and Haiku 5.5 take it only up to `high`, so `xhigh` and `max` are asked as `high`. `between_tools` sent to any other Claude goes as `disabled`, or as none where that is refused too. Other vendors' models, older Claudes and later lines than these go as they came (#1454). A Sonnet 5.5 by a name these rules can't read, answering 400 that asks for `between_tools` (`asksBetweenTools`), is asked again with it, once; a refusal of `disabled` at any effort (`thinkingOffRefused`) is asked again with thinking left to the model, as `alwaysThinks` is. So is a relay that reads `disabled` as reasoning effort `none` and turns that level away naming the ones it takes (Sub2API's gpt-6.1-sol, "does not support reasoning effort \"none\"; use low, medium, high, xhigh or max", #1465); `refusesThinkingOff` is the one list of these refusals for both routes. A relayed request refused so marks the model (`markUnfit(offRefused)`), and its later requests go with thinking left to the model at once until magpie restarts, as auto mode's classifier asks on every action.
- A Chat or Responses client's reasoning turned off (`none`, `ThinkOff`), translated to an Anthropic endpoint (`buildAnthropic`), goes as `thinking: {type: "disabled"}`; it went as thinking at a 4096-token budget before (#1636). A model that refuses it (`refusesThinkingOff`: `alwaysThinks`, `mandatoryReasoning`, `thinkingOffRefused`, or `none` turned away naming the levels taken) is asked again at its least (`thinkingBackOn`), and `markUnfit(offRefused)` sends it so at once until magpie restarts. A translated request's level can differ from the one asked: `none` and `minimal` go as `low` where the model's levels don't say it stops (`effortOf`). The route keeps the level asked; the try, the usage log and Routing's "went" say the one built (`noteWireEffort`, `wireEffort` in [`wire_effort.go`](../../internal/gateway/wire_effort.go)). Gemini's builders say theirs their own way and are logged as asked.
- A model the user ticked no levels of (`ModelReasonless` in [settings](../../internal/settings/settings.go), `SetModelReasonless`; the provider editor's Names & levels, or `magpie model efforts <provider/model> off`) is sent no reasoning field on any route, whatever the agent asks: the candidate loop strips the body with `withoutAnyReasoning` ([`quiet.go`](../../internal/gateway/quiet.go): Chat's `reasoning_effort`, `reasoning`, `thinking`, `enable_thinking` and `include`'s `reasoning.encrypted_content`, Responses' `reasoning`, Anthropic's `thinking` of any type and `output_config.effort`, Gemini's `thinkingConfig`), the Anthropic relay doesn't add `thinking:{type:disabled}` for it, and `forwardTranslated` clears `Effort`, `ThinkOff` and `Thinking` for its other callers. It offers no levels (`Efforts`, `entryFor`), is `Quiet`, and as a routing-group member doesn't take the group's levels away. The learned refusals above cover only reasoning *off* and Gemini levels; a vendor that answers a plain `reasoning_effort` with 422 (yuexian7 on Discord) is not learned, so this is the user's switch. `TestReasonlessModelSentNoReasoning`, `TestReasonlessAnthropicRelay`, `TestGroupReasonlessMemberKeepsLevels`, `model-reasonless.test.cjs`.
- A request to an Anthropic endpoint with `temperature`, `top_p` or `top_k` reaches a model that refuses them without them (`samplingAsTaken`, beside `thinkingOffAsTaken` in `forwardOnce`): Opus 4.7, 4.8, 5 and 5.5, Fable 5, Mythos 5, Sonnet 5 and 5.5, and Haiku 5.5, whose 400 is "`temperature` is deprecated for this model" (Claude Code's auto mode classifier and magpie's own classifiers ask at temperature 0). Older Claudes, Haiku 4.5 among them, other vendors' models and later lines go as they came (#1454). A Claude by a name these rules can't read, answering that a sampling parameter is deprecated (`samplingDeprecated`), is asked again without them, once — a Chat or Responses client's request translated to Messages (`forwardTranslated`) as much as a relayed one.
- Claude Code's auto mode asks the API to review each action ([`automode.go`](../../internal/gateway/automode.go), Anthropic's [auto-mode-classifier-billing](https://code.claude.com/docs/en/auto-mode-classifier-billing)): the `dangerous-tool-use-…` beta, a `safeguards` field, and `safeguard_results` in the reply (a stream's in its `message_delta`). Only Anthropic runs that classifier, so they reach only a route it answers on (`AutoModeReviewed`): the Claude subscription (the bridge hands them to Claude Code's own binary), a Claude model under any vendor's spelling (Anthropic's API, a relay, Bedrock, Vertex), and anything on `api.anthropic.com`. There the beta, `safeguards` and the results pass as sent, a whole reply's results moved into a stream's `message_delta` (`anthropicWholeEvents`), tool-use ids unchanged. To any other model they are taken off (`serverReview`; a translation never carries them), and magpie never answers a result on Anthropic's behalf. Claude Code then classifies locally and names the gateway in a notice; the wiring turns the review off in its settings while no model it can reach through magpie is reviewed (`claudeReviewEnv`, [agent wiring](agent-wiring.md)), which is the page's remedy for a gateway that can't run the checks (1EFLOPS on X: Codex's model behind magpie).
- Claude Code's billing line (`x-anthropic-billing-header: cc_version=…; cc_entrypoint=…; cch=…;`, its own first system block, `cch` changing every turn) goes on only to a Claude model asked on Anthropic's Messages API (`keepsBillingLine` in [`billing_line.go`](../../internal/gateway/billing_line.go): Anthropic's, a relay's, Bedrock's), as Claude Code sent it. Anywhere else it is left out, the rest of the system as sent (`withoutBillingLine`): a vendor's model relayed on Messages (`passthrough`), every translation to Chat, Responses or Gemini (`forwardTranslated`, Claude models too), and the subscriptions asked through their own clients' APIs (Cursor, Devin, Kiro, Qoder, Zed, Command Code's Go plan, in `attempt`). Kept, a vendor read it as the prompt's first words and its prefix cache missed from byte 0 every turn (#1600, justrun1983: 4% read from DeepSeek's cache behind Command Code's plan). The Claude subscription's run sends its own (`withoutBillingHeader`), another magpie decides for the provider it picks, and Code Assist (Antigravity, Gemini CLI) is sent it as before, which `antigravityTurnsAway` reads (#666).
+33 -3
View File
@@ -22,6 +22,7 @@ const modelUsage = `usage:
magpie model efforts <provider/model> the reasoning levels it offers, and those it has
magpie model efforts <provider/model> <l>,<l> offer only these of them, e.g. low,medium,high
magpie model efforts <provider/model> --reset offer every level it has again
magpie model efforts <provider/model> off send it no reasoning field at all
magpie model price <provider/model> what the model costs you, and what you said it costs
magpie model price <provider/model> <in>,<out>,<cache read>,<cache write>
say what it costs, in USD per million tokens, all four parts as
@@ -211,7 +212,20 @@ func modelEfforts(args []string) error {
all := p.Efforts(model)
rest := args[1:]
given := len(p.Known(model)) == 0 // levels aren't known: those it has are the user's
if len(rest) == 1 && slices.Contains([]string{"off", "--off"}, rest[0]) {
// no reasoning field at all, for a vendor that turns one away
// though its list says the model reasons (yuexian7 on Discord)
if err := provider.SetModelReasonless(id, true); err != nil {
return err
}
fmt.Println(green.Render("✓"), id, muted.Render("is sent no reasoning field"), faint.Render("· --reset offers its levels again"))
return nil
}
if len(rest) == 0 {
if provider.Reasonless(p.ID, model) {
fmt.Println(muted.Render(id+" is sent no reasoning field"), faint.Render("· --reset offers its levels again"))
return nil
}
if len(all) == 0 {
fmt.Println(muted.Render(id+" has no reasoning levels known"), faint.Render("· give it some of "+strings.Join(provider.Levels, ", ")))
return nil
@@ -677,9 +691,11 @@ func modelCompact(args []string) error {
func modelNames() error {
s := settings.Load()
keys := slices.Sorted(maps.Keys(s.ModelNames))
for k := range s.ModelEfforts {
if !slices.Contains(keys, k) {
keys = append(keys, k)
for _, m := range []map[string][]string{s.ModelEfforts, reasonlessLevels(s.ModelReasonless)} {
for k := range m {
if !slices.Contains(keys, k) {
keys = append(keys, k)
}
}
}
slices.Sort(keys)
@@ -699,11 +715,25 @@ func modelNames() error {
if es := s.ModelEfforts[k]; len(es) > 0 {
line += " " + muted.Render(strings.Join(es, "/"))
}
if s.ModelReasonless[k] {
line += " " + muted.Render("no reasoning field")
}
fmt.Println(line)
}
return nil
}
// reasonlessLevels are the models sent no reasoning field, as keys.
func reasonlessLevels(m map[string]bool) map[string][]string {
out := map[string][]string{}
for k, on := range m {
if on {
out[k] = nil
}
}
return out
}
// modelWires lists the names the user gave the vendors their models are asked
// for, and which provider and model each is for. It is `magpie model prices`
// for the wire names: those are what a provider is asked for, and no other
+15 -2
View File
@@ -2189,7 +2189,14 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// user saying this model does think, over a catalog that may be
// wrong about it (the Trae plugin's own model, #950)
quiet := isGroup && c.effort == "" && quietTo(c.p.ID, c.model)
if quiet {
if provider.Reasonless(c.p.ID, c.model) {
// a model the user said takes no reasoning ask is sent none,
// in a group or not, at a fixed effort or not: not even
// reasoning turned off (yuexian7 on Discord: its vendor
// answers reasoning_effort with 422)
quiet = true
attemptBody, picked = withoutAnyReasoning(from, attemptBody), false
} else if quiet {
attemptBody, picked = withoutReasoningAsk(from, attemptBody), false
}
// the reasoning the model is asked for, whoever chose it
@@ -3675,7 +3682,7 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
// turns the whole request away for (#1611)
body = withThinkingOnToolTurns(body)
}
if !anthropicModel.MatchString(model) {
if !anthropicModel.MatchString(model) && !provider.Reasonless(p.ID, model) {
body = thinkingOffUnlessAsked(body)
// Claude Code's auto mode classifier, on a vendor's model that
// may think whatever it is told (#250); a Claude model's request
@@ -4242,6 +4249,12 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to
r := *req
r.Effort, req = "none", &r
}
if provider.Reasonless(p.ID, model) {
// the user said it takes no reasoning ask: built with none, not
// even reasoning turned off (yuexian7 on Discord)
r := *req
r.Effort, r.ThinkOff, r.Thinking, req = "", false, false, &r
}
if req.Effort != "" {
if e := fitFor(p, model, req.Effort); e != req.Effort {
r := *req
+37 -6
View File
@@ -43,6 +43,23 @@ func quietTo(pid, model string) bool {
// output_config kept, and Gemini's generationConfig.thinkingConfig when it
// asks to think. The body goes as it is when it asked for nothing.
func withoutReasoningAsk(proto provider.Protocol, body []byte) []byte {
return withoutReasoningFields(proto, body, false)
}
// withoutAnyReasoning removes every field about reasoning, in the agent's own
// protocol: withoutReasoningAsk's, and those turning it off as well —
// Anthropic's thinking of any type, Gemini's thinkingConfig whatever it
// says, and Chat's thinking switches (Kimi's thinking, Qwen's
// enable_thinking), and the sealed reasoning Responses' include asks
// for, which OpenAI refuses of a model that doesn't reason. It is what a
// model the user said takes no reasoning ask is sent
// (provider.SetModelReasonless; yuexian7 on Discord: the vendor answers
// reasoning_effort with 422, and the request without it works).
func withoutAnyReasoning(proto provider.Protocol, body []byte) []byte {
return withoutReasoningFields(proto, body, true)
}
func withoutReasoningFields(proto provider.Protocol, body []byte, all bool) []byte {
dec := json.NewDecoder(bytes.NewReader(body))
dec.UseNumber()
var m map[string]any
@@ -57,17 +74,31 @@ func withoutReasoningAsk(proto provider.Protocol, body []byte) []byte {
}
}
switch proto {
case provider.Chat:
case provider.Chat, provider.Responses:
drop("reasoning_effort")
drop("reasoning")
case provider.Responses:
drop("reasoning")
drop("reasoning_effort")
if all {
drop("thinking")
drop("enable_thinking")
if inc, ok := m["include"].([]any); ok {
kept := inc[:0:0]
for _, v := range inc {
if v != "reasoning.encrypted_content" {
kept = append(kept, v)
}
}
if len(kept) < len(inc) {
m["include"], changed = kept, true
}
}
}
case provider.Anthropic:
if t, ok := m["thinking"].(map[string]any); ok {
if s, _ := t["type"].(string); s == "enabled" || s == "adaptive" {
if s, _ := t["type"].(string); all || s == "enabled" || s == "adaptive" {
drop("thinking")
}
} else if all {
drop("thinking")
}
if oc, ok := m["output_config"].(map[string]any); ok {
if _, ok := oc["effort"]; ok {
@@ -86,7 +117,7 @@ func withoutReasoningAsk(proto provider.Protocol, body []byte) []byte {
if gc, ok := m["generationConfig"].(map[string]any); ok {
if raw, err := json.Marshal(gc["thinkingConfig"]); err == nil {
var tc gThinking
if json.Unmarshal(raw, &tc) == nil && tc.effort() != "" {
if _, has := gc["thinkingConfig"]; has && all || json.Unmarshal(raw, &tc) == nil && tc.effort() != "" {
delete(gc, "thinkingConfig")
changed = true
if len(gc) == 0 {
+143
View File
@@ -0,0 +1,143 @@
package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
)
// reasoningLeft says what of a sent body still asks the model to reason.
func reasoningLeft(sent map[string]any) string {
for _, k := range []string{"reasoning_effort", "reasoning", "thinking", "enable_thinking", "output_config"} {
if sent[k] != nil {
return k
}
}
return ""
}
// A model the user ticked no levels for is sent no reasoning field at all,
// whatever the agent asks: yuexian7's vendor lists the model as reasoning
// on models.dev and answers 422 to any reasoning parameter. It holds on
// every route — a Chat and a Responses request relayed as they are, an
// Anthropic request translated to Chat — asked of the model by name and
// through a group, and a group with it as a member keeps the other
// member's levels and still sends that member the effort asked.
func TestReasonlessModelSentNoReasoning(t *testing.T) {
fresh(t)
thinks, quiet, reset := quietGroup(t)
if err := provider.SetModelReasonless("thinks/levelled", true); err != nil {
t.Fatal(err)
}
s := New()
post := func(path, body string) string {
t.Helper()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", path, strings.NewReader(body))
req.Header.Set("x-session-id", "r1")
s.Handler().ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("%s %s: %d %s", path, body, rec.Code, rec.Body)
}
return rec.Body.String()
}
for _, model := range []string{"thinks/levelled", "group/mix"} {
for _, c := range []struct{ path, body string }{
{"/v1/chat/completions", `{"model":"` + model + `","reasoning_effort":"high","messages":[{"role":"user","content":"hi"}]}`},
{"/v1/chat/completions", `{"model":"` + model + `","reasoning_effort":"high","enable_thinking":true,"messages":[{"role":"user","content":"hi"}]}`},
{"/v1/responses", `{"model":"` + model + `","input":"hi","reasoning":{"effort":"high","summary":"auto"},"include":["reasoning.encrypted_content"]}`},
{"/v1/messages", `{"model":"` + model + `","max_tokens":2000,"thinking":{"type":"enabled","budget_tokens":1024},"output_config":{"effort":"high"},"messages":[{"role":"user","content":"hi"}]}`},
} {
reset(0)
if out := post(c.path, c.body); !strings.Contains(out, "from kt") {
t.Fatalf("%s %s: %s", model, c.path, out)
}
sent := thinks.sent()
if k := reasoningLeft(sent); k != "" {
t.Fatalf("%s %s: the reasonless model was sent %s: %v", model, c.path, k, sent)
}
if inc, _ := json.Marshal(sent["include"]); strings.Contains(string(inc), "reasoning") {
t.Fatalf("%s %s: sent include %s", model, c.path, inc)
}
}
}
// a group with a reasonless member keeps the levels its other members
// take, and a member that reasons is still sent the effort asked
if err := provider.SaveGroup(provider.Group{Name: "Two", Members: []string{"thinks/levelled", "quiet/plain:high"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
reset(500)
if out := post("/v1/chat/completions", `{"model":"group/two","reasoning_effort":"high","messages":[{"role":"user","content":"hi"}]}`); !strings.Contains(out, "from kq") {
t.Fatalf("two: %s", out)
}
if sent := quiet.sent(); sent["reasoning_effort"] != "high" {
t.Fatalf("the member that reasons was sent %v", sent)
}
// ticking a level again sends reasoning as before
if err := provider.SetModelEfforts("thinks/levelled", []string{"low", "high"}); err != nil {
t.Fatal(err)
}
reset(0)
post("/v1/chat/completions", `{"model":"thinks/levelled","reasoning_effort":"high","messages":[{"role":"user","content":"hi"}]}`)
if sent := thinks.sent(); sent["reasoning_effort"] != "high" {
t.Fatalf("ticked again, it was sent %v", sent)
}
}
// anthUp is an Anthropic vendor that keeps what it was sent.
type anthUp struct {
mu sync.Mutex
last string
}
func (u *anthUp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
u.mu.Lock()
u.last = string(b)
u.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"id":"m1","type":"message","role":"assistant","model":"glm","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":3,"output_tokens":1}}`)
}
// Relayed to an Anthropic vendor as it came, a reasonless model is sent
// neither the agent's thinking nor the thinking:{type:disabled} magpie
// adds for a model that isn't Claude: that is a reasoning field too.
func TestReasonlessAnthropicRelay(t *testing.T) {
fresh(t)
catalog.Reset()
t.Cleanup(catalog.Reset)
up := &anthUp{}
srv := httptest.NewServer(up)
t.Cleanup(srv.Close)
if err := provider.Save(provider.Provider{ID: "anth", Name: "Anth", Key: "k", Models: []string{"glm"}, Anthropic: srv.URL}); err != nil {
t.Fatal(err)
}
if err := provider.SetModelReasonless("anth/glm", true); err != nil {
t.Fatal(err)
}
s := New()
for _, body := range []string{
`{"model":"anth/glm","max_tokens":2000,"thinking":{"type":"enabled","budget_tokens":1024},"output_config":{"effort":"high"},"messages":[{"role":"user","content":"hi"}]}`,
`{"model":"anth/glm","max_tokens":2000,"messages":[{"role":"user","content":"hi"}]}`,
} {
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)))
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
up.mu.Lock()
var sent map[string]any
json.Unmarshal([]byte(up.last), &sent)
up.mu.Unlock()
if k := reasoningLeft(sent); k != "" {
t.Fatalf("%s: sent %s: %v", body, k, sent)
}
}
}
+28 -6
View File
@@ -10408,7 +10408,11 @@ function renderModels(p) {
const levels = m.efforts || [];
const savedKept = m.kept?.length || m.given ? m.kept || [] : levels;
const nameNow = () => prefs[id]?.name ?? savedName;
const keptNow = () => prefs[id]?.efforts ? (prefs[id].efforts.length || m.given ? prefs[id].efforts : levels) : savedKept;
// none of its levels kept: it is sent no reasoning field at all
// (yuexian7 on Discord: a model models.dev says reasons answered
// reasoning_effort with 422, and worked without it)
const noneNow = () => prefs[id]?.reasonless ?? !!m.reasonless;
const keptNow = () => noneNow() ? [] : prefs[id]?.efforts ? (prefs[id].efforts.length || m.given ? prefs[id].efforts : levels) : savedKept;
const imagesNow = () => prefs[id]?.ownImages ? !!m.ownImages : prefs[id]?.images ?? !!m.images;
const row = el("div", "mname");
const name = input(nameNow(), own);
@@ -10601,25 +10605,41 @@ function renderModels(p) {
row.append(apiSeg);
}
// a model whose levels aren't known (m.given) can be given any
// of them, and none again
// of them, and none again;
// one whose levels are known can keep none of them: it is then
// sent no reasoning field, in a routing group too
const boxes = [];
if (levels.length > 1) {
const noneSaid = el("span", "hint mnone", t("No reasoning field sent"));
noneSaid.title = t("None ticked: magpie sends {id} no reasoning field, whatever effort the agent asks, as for a model that doesn't reason", { id: m.id });
const drawNone = () => { noneSaid.hidden = !noneNow(); };
if (levels.length > 1 || levels.length && !m.given) {
const lv = el("div", "mlevels");
lv.title = t(m.given ? "Its reasoning levels aren't known: tick the ones it takes" : "Reasoning levels agents are offered");
lv.title = t(m.given ? "Its reasoning levels aren't known: tick the ones it takes" : "Reasoning levels agents are offered; none ticked: it is sent no reasoning field");
for (const l of levels) {
const [tk, cb] = tick(t(l), keptNow().includes(l));
cb.onchange = () => {
const kept = keptNow();
const next = levels.filter((x) => x === l ? cb.checked : kept.includes(x));
if (!next.length && !m.given) { cb.checked = true; status(t("Keep at least one level"), "err"); return; }
if (!next.length && !m.given) {
// none kept: no reasoning field
delete pref().efforts;
if (m.reasonless) delete pref().reasonless; else pref().reasonless = true;
drawNone();
drawReset();
return;
}
if (m.reasonless) pref().reasonless = false; else delete pref().reasonless;
const all = next.length === levels.length && !m.given;
if (all ? !m.kept?.length : next.join() === savedKept.join()) delete pref().efforts;
else pref().efforts = all ? [] : next;
drawNone();
drawReset();
};
boxes.push([l, cb]);
lv.append(tk);
}
lv.append(noneSaid);
drawNone();
row.append(lv);
}
// what the Save will make of it differs from what it is: said beside
@@ -10633,10 +10653,12 @@ function renderModels(p) {
if (draft.priceTyped) delete draft.priceTyped[id];
if (m.default) prefs[id].name = "";
if (m.kept?.length) prefs[id].efforts = [];
if (m.reasonless) prefs[id].reasonless = false;
if (m.imageSet) prefs[id].ownImages = true;
name.value = nameNow();
imgCb.checked = imagesNow();
for (const [l, cb] of boxes) cb.checked = keptNow().includes(l);
drawNone();
if (m.api) prefs[id].api = "";
if (m.same) prefs[id].same = "";
same.value = sameNow();
@@ -10651,7 +10673,7 @@ function renderModels(p) {
unsaved.hidden = !prefs[id] && !draft.priceTyped?.[id];
// staged back to its own already, there is nothing to restore
const images = prefs[id]?.ownImages ? false : prefs[id]?.images !== undefined ? prefs[id].images !== !!m.ownImages : !!m.imageSet;
const custom = nameNow() !== "" || (prefs[id]?.efforts ? prefs[id].efforts.length > 0 : !!m.kept?.length) || images || apiNow() !== "" || sameNow() !== "" || priceNow() !== null || !!draft.priceTyped?.[id];
const custom = nameNow() !== "" || noneNow() || (prefs[id]?.efforts ? prefs[id].efforts.length > 0 : !!m.kept?.length) || images || apiNow() !== "" || sameNow() !== "" || priceNow() !== null || !!draft.priceTyped?.[id];
reset.hidden = !custom;
};
row.append(unsaved, reset);
+12 -4
View File
@@ -2068,8 +2068,10 @@ const I18N = {
"{id} accepts images": "{id} 支持图片输入",
"{id} does not accept images": "{id} 不支持图片输入",
"Reasoning levels agents are offered": "提供给 Agent 的推理档位",
"Reasoning levels agents are offered; none ticked: it is sent no reasoning field": "提供给 Agent 的推理档位;全不勾选则不发送任何推理参数",
"No reasoning field sent": "不发送推理参数",
"None ticked: magpie sends {id} no reasoning field, whatever effort the agent asks, as for a model that doesn't reason": "全不勾选:无论 Agent 要求什么推理强度,magpie 都不给 {id} 发送推理参数,与不推理的模型一样",
"Its reasoning levels aren't known: tick the ones it takes": "推理档位未知:勾选它支持的档位",
"Keep at least one level": "至少保留一个档位",
"{id}: {levels}": "{id}:{levels}",
"Restore default": "恢复默认",
"Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, and its list price": "恢复默认名称、全部推理档位、是否支持图片、请求所用的协议、它等同的模型,以及官方价格",
@@ -6172,8 +6174,10 @@ const I18N = {
"{id} accepts images": "{id} 支援圖片輸入",
"{id} does not accept images": "{id} 不支援圖片輸入",
"Reasoning levels agents are offered": "提供給 Agent 的推理檔位",
"Reasoning levels agents are offered; none ticked: it is sent no reasoning field": "提供給 Agent 的推理檔位;全不勾選則不傳送任何推理參數",
"No reasoning field sent": "不傳送推理參數",
"None ticked: magpie sends {id} no reasoning field, whatever effort the agent asks, as for a model that doesn't reason": "全不勾選:無論 Agent 要求什麼推理強度,magpie 都不給 {id} 傳送推理參數,與不推理的模型一樣",
"Its reasoning levels aren't known: tick the ones it takes": "推理檔位未知:勾選它支援的檔位",
"Keep at least one level": "至少保留一個檔位",
"{id}: {levels}": "{id}:{levels}",
"Restore default": "恢復預設",
"Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, and its list price": "恢復預設名稱、全部推理檔位、是否支援圖片、請求所用的協議、它等同的模型,以及官方價格",
@@ -10299,8 +10303,10 @@ const I18N = {
"{id} accepts images": "{id} は画像入力に対応しています",
"{id} does not accept images": "{id} は画像入力に対応していません",
"Reasoning levels agents are offered": "エージェントに提供する推論レベル",
"Reasoning levels agents are offered; none ticked: it is sent no reasoning field": "エージェントに提供する推論レベル。すべて外すと推論パラメータを送りません",
"No reasoning field sent": "推論パラメータを送信しない",
"None ticked: magpie sends {id} no reasoning field, whatever effort the agent asks, as for a model that doesn't reason": "すべて外すと、エージェントがどの推論レベルを求めても magpie は {id} に推論パラメータを送りません(推論しないモデルと同じ扱い)",
"Its reasoning levels aren't known: tick the ones it takes": "推論レベルが不明です。対応するものにチェックを入れてください",
"Keep at least one level": "少なくとも1つのレベルを残してください",
"{id}: {levels}": "{id}:{levels}",
"Restore default": "デフォルトに戻す",
"Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, and its list price": "元の名前、すべての推論レベル、画像対応の有無、リクエストに使う API、同じモデルの指定、公式価格",
@@ -14423,8 +14429,10 @@ const I18N = {
"{id} accepts images": "{id} akzeptiert Bilder",
"{id} does not accept images": "{id} akzeptiert keine Bilder",
"Reasoning levels agents are offered": "Reasoning-Stufen, die Agenten angeboten werden",
"Reasoning levels agents are offered; none ticked: it is sent no reasoning field": "Reasoning-Stufen, die Agenten angeboten werden; keine angehakt: es wird kein Reasoning-Feld gesendet",
"No reasoning field sent": "Kein Reasoning-Feld gesendet",
"None ticked: magpie sends {id} no reasoning field, whatever effort the agent asks, as for a model that doesn't reason": "Keine angehakt: magpie sendet {id} kein Reasoning-Feld, egal welche Stufe der Agent verlangt, wie bei einem Modell ohne Reasoning",
"Its reasoning levels aren't known: tick the ones it takes": "Seine Reasoning-Stufen sind unbekannt: Kreuzen Sie die unterstützten an",
"Keep at least one level": "Mindestens eine Stufe behalten",
"{id}: {levels}": "{id}: {levels}",
"Restore default": "Standard wiederherstellen",
"Its own name, every reasoning level it has, whether it sees images, the API it is asked on, the model it is the same as, and its list price": "Eigener Name, alle Reasoning-Stufen, Bildunterstützung, die angefragte API, das Modell, dem es entspricht, und der Listenpreis",
+30 -23
View File
@@ -27,29 +27,32 @@ import (
// with one key, the gateway that fronts them, and who is routed where.
type modelJSON struct {
ID string `json:"id"`
Name string `json:"name"` // the user's name for it, if they gave one
Default string `json:"default,omitempty"` // its own name, when the user gave it another
Plain string `json:"plain,omitempty"` // a remote magpie's model's name there alone, when Name has its provider there after it (catalog.Model's)
Kept []string `json:"kept,omitempty"` // the reasoning levels the user keeps of Efforts, when not all
Efforts []string `json:"efforts,omitempty"`
Given bool `json:"given,omitempty"` // its levels aren't known: Efforts are those it can be given, Kept those it was
Images bool `json:"images"` // agents are told it can see images
ImageSet bool `json:"imageSet,omitempty"` // the user said so, rather than its vendor
Own bool `json:"ownImages,omitempty"` // its vendor's answer, which a staged Restore default shows
On bool `json:"on"` // exposed to agents
Context int `json:"context,omitempty"` // the window agents are told: the user's, else Listed
Output int `json:"output,omitempty"` // the reply limit agents are told: provider.ReplyLimit within Context (provider.OutputWithin)
Listed int `json:"listed,omitempty"` // its window before the user's: its vendor's list's, else models.dev's
Max int `json:"max,omitempty"` // the most its context may be set to, above Listed
Free bool `json:"free,omitempty"` // costs the subscription nothing
Rate float64 `json:"rate,omitempty"` // the credits a request costs the subscription, as a multiple
RateWas float64 `json:"rateWas,omitempty"` // the rate before a discount running now
API string `json:"api,omitempty"` // the one API the user said it is asked on
Auto []string `json:"auto,omitempty"` // the APIs its vendor's list says it is served on, what Auto asks it on
Same string `json:"same,omitempty"` // the model the user said it is the same as, for the groups magpie finds (#583)
Merge string `json:"merge,omitempty"` // what those groups merge it by when the user says nothing
Kind string `json:"kind,omitempty"` // what the user said it makes: image or video (#1399)
ID string `json:"id"`
Name string `json:"name"` // the user's name for it, if they gave one
Default string `json:"default,omitempty"` // its own name, when the user gave it another
Plain string `json:"plain,omitempty"` // a remote magpie's model's name there alone, when Name has its provider there after it (catalog.Model's)
Kept []string `json:"kept,omitempty"` // the reasoning levels the user keeps of Efforts, when not all
Efforts []string `json:"efforts,omitempty"`
Given bool `json:"given,omitempty"` // its levels aren't known: Efforts are those it can be given, Kept those it was
// Reasonless: the user said it takes no reasoning ask
// (provider.SetModelReasonless): none of Efforts is kept, and none is sent
Reasonless bool `json:"reasonless,omitempty"`
Images bool `json:"images"` // agents are told it can see images
ImageSet bool `json:"imageSet,omitempty"` // the user said so, rather than its vendor
Own bool `json:"ownImages,omitempty"` // its vendor's answer, which a staged Restore default shows
On bool `json:"on"` // exposed to agents
Context int `json:"context,omitempty"` // the window agents are told: the user's, else Listed
Output int `json:"output,omitempty"` // the reply limit agents are told: provider.ReplyLimit within Context (provider.OutputWithin)
Listed int `json:"listed,omitempty"` // its window before the user's: its vendor's list's, else models.dev's
Max int `json:"max,omitempty"` // the most its context may be set to, above Listed
Free bool `json:"free,omitempty"` // costs the subscription nothing
Rate float64 `json:"rate,omitempty"` // the credits a request costs the subscription, as a multiple
RateWas float64 `json:"rateWas,omitempty"` // the rate before a discount running now
API string `json:"api,omitempty"` // the one API the user said it is asked on
Auto []string `json:"auto,omitempty"` // the APIs its vendor's list says it is served on, what Auto asks it on
Same string `json:"same,omitempty"` // the model the user said it is the same as, for the groups magpie finds (#583)
Merge string `json:"merge,omitempty"` // what those groups merge it by when the user says nothing
Kind string `json:"kind,omitempty"` // what the user said it makes: image or video (#1399)
// what it costs, USD per million tokens (#819): the price the user set
// for it, and its list price, its vendor's else its maker's, before the
// provider's price rate
@@ -701,6 +704,10 @@ func providerInfo(p provider.Provider, agents []agentUse) providerJSON {
if k, ok := kept[m.ID]; ok {
j.Kept = slices.DeleteFunc(slices.Clone(j.Efforts), func(e string) bool { return !slices.Contains(k, e) })
}
if provider.Reasonless(p.ID, m.ID) {
// none of its levels is kept: each is there to tick again
j.Reasonless, j.Kept = true, nil
}
return j
}
for _, m := range p.Available() {
+1
View File
@@ -123,6 +123,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {
CheckinOff: []string{"workbuddy|u1"},
ModelNames: map[string]string{"p/m": "Mine"},
ModelEfforts: map[string][]string{"p/m": {"low"}},
ModelReasonless: map[string]bool{"p/n": true},
ModelImages: map[string]bool{"p/m": true},
ModelOutputs: map[string]int{"p/m": 131072},
ModelCompacts: map[string]int{"p/*": 500000},
@@ -0,0 +1,121 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// yuexian7 on Discord: models.dev lists their model as reasoning, and the
// vendor answers any reasoning parameter with 422 while the request
// without it works. In the provider editor's Names & levels, a model's
// levels can all be unticked: magpie then sends it no reasoning field, said
// beside the levels, and the Save sends {reasonless: true}. A model saved
// so shows none ticked, and ticking one takes it back. Every language,
// at a wide and a narrow window.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
function serve(lang, posts) {
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
const models = [
{ id: "model-1", name: "Model 1", on: true, efforts: ["low", "high"], images: false },
// saved with none kept: the backend says so, and gives no kept levels
{ id: "model-2", name: "Model 2", on: true, efforts: ["low", "high"], images: false, reasonless: true },
// levels not known: none ticked is what it was, no levels known
{ id: "model-3", name: "Model 3", on: true, efforts: ["low", "high"], given: true, images: false },
];
const provider = { id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example/v1", responses: "", anthropic: "", models, agents: [], key: { set: true, masked: "sk-…1234" }, ready: true };
const providers = { providers: [provider], presets: [], excluded: [], gateway: { running: true, window: true } };
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:${JSON.stringify(lang)},theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/providers") return json(providers);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname.startsWith("/api/provider/")) {
posts.push({ path: url.pathname, body: route.request().postDataJSON() });
return json(providers);
}
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
await route.fulfill({ body: await fs.readFile(file), contentType: { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)] });
};
}
const keys = [
"No reasoning field sent",
"Reasoning levels agents are offered; none ticked: it is sent no reasoning field",
"None ticked: magpie sends {id} no reasoning field, whatever effort the agent asks, as for a model that doesn't reason",
];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const width of [1100, 420]) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
test(`${engine} ${width} ${lang}: a model's levels all unticked sends it no reasoning field`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" }));
const page = await (await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" })).newPage();
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${width}-${lang}-model-reasonless.png`) });
}
await browser.close();
});
page.setDefaultTimeout(5000);
const errors = [], posts = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, posts));
await page.goto("http://magpie.test/?view=providers");
const tr = (k, v = {}) => page.evaluate(([k, v]) => t(k, v), [k, v]);
await page.locator(".row.provider").click();
if (!(await page.locator(".mnames:not([hidden])").count())) await page.getByRole("button", { name: await tr("Names & levels"), exact: true }).click();
const row = (id) => page.locator(".mname", { has: page.locator("code", { hasText: id }) });
const boxes = (id) => row(id).locator(".mlevels input[type=checkbox]");
const hint = (id) => row(id).locator(".mlevels .mnone");
const ticked = (id) => boxes(id).evaluateAll((bs) => bs.map((b) => b.checked));
const none = await tr("No reasoning field sent");
assert.equal(await row("model-1").locator(".mlevels").getAttribute("title"), await tr(keys[1]));
// model-1: both unticked, no error, the hint shows
assert.deepEqual(await ticked("model-1"), [true, true]);
assert(!(await hint("model-1").isVisible()));
await boxes("model-1").nth(0).click();
await boxes("model-1").nth(1).click();
assert.deepEqual(await ticked("model-1"), [false, false], "the last level unticks");
assert(await hint("model-1").isVisible());
assert.equal(await hint("model-1").textContent(), none);
assert.equal(await hint("model-1").getAttribute("title"), await tr(keys[2], { id: "model-1" }));
assert.equal(await page.locator("#status.err").count(), 0, "no error for none kept");
// its Restore default shows, and puts the levels back
assert(await row("model-1").getByRole("button", { name: await tr("Restore default") }).isVisible());
// model-2, saved so: none ticked, said; ticking one takes it back
assert.deepEqual(await ticked("model-2"), [false, false]);
assert(await hint("model-2").isVisible());
await boxes("model-2").nth(1).click();
assert.deepEqual(await ticked("model-2"), [false, true]);
assert(!(await hint("model-2").isVisible()));
// model-3, levels not known: none ticked is as it was, no hint
assert(!(await hint("model-3").isVisible()));
const rect = await row("model-1").locator(".mlevels").boundingBox();
assert(rect.x >= 0 && rect.x + rect.width <= width, `levels in the window: ${JSON.stringify(rect)}`);
assert.deepEqual(posts, [], "nothing is sent before the Save");
await page.getByRole("button", { name: await tr("Save"), exact: true }).click();
await page.waitForFunction(() => !document.querySelector(".mnames"));
const save = posts.find((p) => p.path === "/api/provider/save");
assert(save, JSON.stringify(posts));
assert.deepEqual(save.body.modelPrefs, {
"model-1": { reasonless: true },
"model-2": { reasonless: false, efforts: ["high"] },
});
const missing = await page.evaluate((keys) => keys.filter((k) => ["zh", "zh-TW", "ja", "de"].some((l) => !I18N[l][k])), keys);
assert.deepEqual(missing, []);
assert.deepEqual(errors, []);
});
}
}
}
+9 -3
View File
@@ -782,11 +782,11 @@ func groupEntries(entries []Entry) []Entry {
var efforts []string
images, thinks, ctx, output := false, false, 0, 0
var imageInput *bool
unknown := false
unknown, reasonless := false, false
for _, x := range entries {
if x.Provider.ID == m.Provider.ID && x.Model == m.Model {
efforts, images, thinks, ctx, output, imageInput = x.Efforts, x.Images, x.Reasoning, x.Context, x.Output, x.ImageInput
unknown = levelsUnknown(x)
unknown, reasonless = levelsUnknown(x), x.Reasonless
}
}
// it reasons when a member does: the gateway sends the
@@ -835,6 +835,12 @@ func groupEntries(entries []Entry) []Entry {
// its models (the outermost that does)
if i := slices.IndexFunc(m.Via, func(v Group) bool { return len(v.Levels) > 0 }); i >= 0 {
efforts = m.Via[i].Levels
} else if reasonless {
// the user said it takes no reasoning ask: the gateway sends
// it none, whatever the agent asks, so it doesn't take the
// others' levels away (yuexian7 on Discord: a group of
// Opus and a model that answers reasoning_effort with 422)
continue
} else if m.Effort != "" {
if !slices.Contains(fixed, m.Effort) {
fixed = append(fixed, m.Effort)
@@ -923,7 +929,7 @@ func levelsUnknown(x Entry) bool {
// but for one the user fixed at an effort (Group's member syntax, #189):
// the gateway leaves that alone, the user's word over magpie's.
func (e Entry) Quiet() bool {
return !e.Reasoning && len(e.Efforts) == 0 && !levelsUnknown(e)
return e.Reasonless || !e.Reasoning && len(e.Efforts) == 0 && !levelsUnknown(e)
}
// SaveGroup adds or replaces a group of the user's. Changing one magpie
+65 -9
View File
@@ -270,7 +270,11 @@ func setModelEfforts(ref string, efforts []string) (bool, error) {
}
s := settings.Load()
key := p.ID + "/" + model
if slices.Equal(s.ModelEfforts[key], keep) {
// levels given, or all of them again, take back a word that it takes
// no reasoning ask (SetModelReasonless)
reasonless := s.ModelReasonless[key]
delete(s.ModelReasonless, key)
if slices.Equal(s.ModelEfforts[key], keep) && !reasonless {
return false, nil
}
if len(keep) == 0 {
@@ -287,6 +291,50 @@ func setModelEfforts(ref string, efforts []string) (bool, error) {
return true, nil
}
// SetModelReasonless says whether a provider's model, spelt
// "provider/model", takes no reasoning ask, whatever its list says: on,
// it offers no levels (Efforts, the agents' lists, a group's) and the
// gateway sends it no reasoning field on any API — Chat's
// reasoning_effort, Responses' reasoning, Anthropic's thinking and
// output_config effort — as it does a model known not to think
// (yuexian7 on Discord: models.dev lists a model with reasoning, and the
// vendor answers reasoning_effort with 422 while the request without it
// works). Off gives it the levels it had again.
func SetModelReasonless(ref string, on bool) error {
return touchedIf(setModelReasonless(ref, on))
}
func setModelReasonless(ref string, on bool) (bool, error) {
p, model, err := splitRef(ref)
if err != nil {
return false, err
}
s := settings.Load()
key := p.ID + "/" + model
if s.ModelReasonless[key] == on {
return false, nil
}
if on {
if s.ModelReasonless == nil {
s.ModelReasonless = map[string]bool{}
}
s.ModelReasonless[key] = true
delete(s.ModelEfforts, key) // none kept of none offered
} else {
delete(s.ModelReasonless, key)
}
if err := settings.Save(s); err != nil {
return false, err
}
return true, nil
}
// Reasonless reports whether the user said pid's model takes no reasoning
// ask (SetModelReasonless).
func Reasonless(pid, model string) bool {
return heldSettings().ModelReasonless[pid+"/"+model]
}
// ModelEfforts are the reasoning levels the user kept of the provider's
// models, by model id.
func (p Provider) ModelEfforts() map[string][]string {
@@ -437,14 +485,17 @@ func modelAPI(proto Protocol) bool {
// place of Price, what the user said it costs (SetModelPrice, #819), and
// Kind "" what its vendor's list says it makes (SetModelKind, #1399).
type ModelPref struct {
Name *string `json:"name,omitempty"`
Efforts *[]string `json:"efforts,omitempty"`
Images *bool `json:"images,omitempty"`
OwnImages bool `json:"ownImages,omitempty"`
API *string `json:"api,omitempty"`
Same *string `json:"same,omitempty"`
Price *catalog.Price `json:"price,omitempty"`
OwnPrice bool `json:"ownPrice,omitempty"`
Name *string `json:"name,omitempty"`
Efforts *[]string `json:"efforts,omitempty"`
// Reasonless, set, is SetModelReasonless's word: true for no
// reasoning ask, false to take that back
Reasonless *bool `json:"reasonless,omitempty"`
Images *bool `json:"images,omitempty"`
OwnImages bool `json:"ownImages,omitempty"`
API *string `json:"api,omitempty"`
Same *string `json:"same,omitempty"`
Price *catalog.Price `json:"price,omitempty"`
OwnPrice bool `json:"ownPrice,omitempty"`
// Kind is what the model makes, as SetModelKind takes it: "image",
// "video", or "" for what its vendor's list and name say (#1399)
Kind *string `json:"kind,omitempty"`
@@ -474,6 +525,11 @@ func SetModelPrefs(pid string, prefs map[string]ModelPref) error {
return err
}
}
if m.Reasonless != nil {
if err := set(setModelReasonless(ref, *m.Reasonless)); err != nil {
return err
}
}
if m.Images != nil || m.OwnImages {
images := m.Images
if m.OwnImages {
+18
View File
@@ -1444,6 +1444,9 @@ func (p Provider) RejectsTemperature(model string) bool {
// Efforts are the reasoning levels the model takes, when known: its own,
// or those the user gave it when it has none known.
func (p Provider) Efforts(model string) []string {
if Reasonless(p.ID, model) {
return nil
}
if all := p.Known(model); len(all) > 0 {
return all
}
@@ -1454,6 +1457,9 @@ func (p Provider) Efforts(model string) []string {
// it thinks, or models.dev says most of those serving it do (Entry's
// Reasoning).
func (p Provider) Thinks(model string) bool {
if Reasonless(p.ID, model) {
return false
}
if len(p.Efforts(model)) > 0 {
return true
}
@@ -1514,6 +1520,9 @@ func (p Provider) knownElsewhere(model string) []string {
// lists it with a thinking switch alone, or nothing (Xiaomi's
// mimo-v2.6-flash), and the user gave it none.
func (p Provider) Levelless(model string) bool {
if Reasonless(p.ID, model) {
return true
}
if len(p.Efforts(model)) > 0 {
return false
}
@@ -1988,6 +1997,10 @@ type Entry struct {
// thinking switch alone has it and no Efforts (a group's: a member
// thinks).
Reasoning bool `json:"reasoning,omitempty"`
// Reasonless is set on a model the user said takes no reasoning ask
// (SetModelReasonless): it is sent none, and as a group's member it
// leaves the group the levels the others have
Reasonless bool `json:"-"`
// AgentsV2 is set on a model offering Codex's Ultra that no ChatGPT
// account answers for (a group's: none of its members): Codex is told
// multi-agent V2 for it, so Ultra hands work to its agents, whose
@@ -2130,6 +2143,11 @@ func entryFor(p Provider, m catalog.Model, s settings.Settings) Entry {
e.Efforts = withUltra(m.ID, e.Efforts)
e.AgentsV2 = slices.Contains(e.Efforts, "ultra")
}
// one the user said takes no reasoning ask offers none and is sent
// none (SetModelReasonless), whatever its list says
if s.ModelReasonless[e.ID] {
e.Efforts, e.Reasoning, e.AgentsV2, e.Reasonless = nil, false, false, true
}
return e
}
+67
View File
@@ -0,0 +1,67 @@
package provider
import (
"slices"
"testing"
)
// Ticking no level of a model whose levels are known says it takes no
// reasoning field at all (yuexian7: a model models.dev lists as reasoning
// that answers any reasoning parameter with 422). Ticking levels again, or
// Restore default, takes that back; the two settings never both hold.
func TestModelReasonless(t *testing.T) {
effortHome(t)
if err := SetModelEfforts("a/m", []string{"high"}); err != nil {
t.Fatal(err)
}
if err := SetModelReasonless("a/m", true); err != nil {
t.Fatal(err)
}
if !Reasonless("a", "m") || Reasonless("a", "n") {
t.Fatal("reasonless not kept for a/m alone")
}
if got := (Provider{ID: "a"}).ModelEfforts()["m"]; got != nil {
t.Fatalf("its kept levels stayed: %v", got)
}
if err := SetModelEfforts("a/m", []string{"low", "high"}); err != nil {
t.Fatal(err)
}
if Reasonless("a", "m") {
t.Fatal("ticking levels left it reasonless")
}
if err := SetModelReasonless("a/m", true); err != nil {
t.Fatal(err)
}
if err := SetModelEfforts("a/m", nil); err != nil { // Restore default
t.Fatal(err)
}
if Reasonless("a", "m") {
t.Fatal("Restore default left it reasonless")
}
}
// A reasonless member is sent no reasoning, so it doesn't take the group's
// levels away (as a member whose levels nothing knows doesn't, #597), and
// the group is quiet to it alone.
func TestGroupReasonlessMemberKeepsLevels(t *testing.T) {
groupReasoningHome(t)
// as entryFor leaves it: no levels, no reasoning, on a provider whose
// list is known (not #597's unknown, which keeps the levels anyway)
off := quietMember()
off.Reasonless = true
if !off.Quiet() {
t.Fatal("a reasonless member isn't quiet")
}
for name, in := range map[string][]Entry{
"off last": {thinksMember(), off},
"off first": {off, thinksMember()},
} {
g := groupEntries(in)
if len(g) != 1 {
t.Fatalf("%s: groups %+v", name, g)
}
if !g[0].Reasoning || !slices.Equal(g[0].Efforts, levels) {
t.Errorf("%s: reasoning %v, levels %v, want %v", name, g[0].Reasoning, g[0].Efforts, levels)
}
}
}
+7
View File
@@ -532,6 +532,13 @@ type Settings struct {
// by "<provider id>/<model id>": the lists magpie hands out offer only
// those (see provider.SetModelEfforts).
ModelEfforts map[string][]string `json:"modelEfforts,omitempty"`
// ModelReasonless are the models the user said take no reasoning ask,
// by "<provider id>/<model id>": magpie offers them no levels and
// sends them no reasoning field, on any API, though their list says
// they think (see provider.SetModelReasonless; yuexian7 on Discord: a
// model models.dev lists with reasoning answered reasoning_effort
// with 422).
ModelReasonless map[string]bool `json:"modelReasonless,omitempty"`
// ModelImages is whether the user said a model takes images, by
// "<provider id>/<model id>". Absent leaves it to the vendor's list.
ModelImages map[string]bool `json:"modelImages,omitempty"`