Files
magpie/internal/gateway/decide_openrouter_variant_test.go
T
yetone 3182a66586 provider, gateway: OpenRouter's decision model picked with a variant (inception/mercury-decide:free) is a decision model, never sent to chat/completions
coeo91 on Discord (2026-10-31): inception/mercury-decide:free, picked by
hand into a group used as smart routing's decision model, failed with
"OpenRouter: inception/mercury-decide:free is a decisions model and
cannot be used with the chat/completions endpoint. Use the
/api/alpha/decisions endpoint instead."

Cause: magpie already reads OpenRouter's decision models from its own
list (/models?output_modalities=decisions: output_modalities
["decisions"], endpoints ["/api/alpha/decisions"]) and asks them at
/api/v1/systemone. That list names each model once, without variants,
so the hand-picked ":free" id was taken for a chat model. Its group was
a chat group and the classifier asked it in words on chat/completions.

Now a variant of a model OpenRouter's decisions list names (base id
before the last ":", OpenRouter providers only; Ollama's :tag stays a
name of its own) is a decision model (openRouterVariant):
- it is kept from agents' model lists, and its group is a decision
  group, asked at /api/v1/systemone (classifier, RouteDecider);
- an agent's chat naming it gets magpie's 400 "only decides", with
  OpenRouter not asked;
- count_tokens naming it, or its decision group, gets the same 400
  (count_tokens had no decision guard and forwarded upstream);
- test-models sends it the System One yes-or-no, and the provider
  editor marks it as a decision model (/api/providers deciders).

Not done: an /api/alpha/decisions client. OpenRouter's /api/v1/systemone
(what magpie uses) answered the same model the same way as the alpha
path in a real probe (200, identical System One shape), so the alpha
endpoint adds nothing but an alpha contract.

Real probe (owner's OpenRouter key, 2026-11-01): chat/completions with
inception/mercury-decide:free gives the reporter's 400 word for word;
/api/v1/systemone and /api/alpha/decisions give 200 for
inception/mercury-decide and 404 for :free ("This model is unavailable
for free... use this slug instead: inception/mercury-decide"). So
after this change the reporter's group is asked the right way, and
OpenRouter's own 404 says to pick the paid slug.

Tests (fixtures are OpenRouter's real list and answer bytes):
TestOpenRouterDecisionModelVariant (provider),
TestOpenRouterDecisionVariantNeverChats (gateway: classifier group asked
at /systemone, chat and count_tokens refused, OpenRouter asked once),
TestOpenRouterDecisionVariantPicker (gui). Each is red on the old code
(provider: "taken for a chat model"; gateway: the reporter's 400 as the
classifier's error; gui: deciders without the variant), checked at
0565c0bba and again after the rebase. With only gateway.go reverted,
count_tokens answered 200 {"input_tokens":0}.

Run:
- full `go test -tags nogui ./... -timeout 45m` on mote at 970931203
  (this change on 0565c0bba), log kept: every package ok except three
  reds that fail the same at 0565c0bba without this change or pass
  alone, each filed: TestBrowserExtensionOnlyFromItsOrigin (#4631),
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514), TestColdTurnsTaken
  under the full run (#4510).
- gofmt -l, go vet, GOOS=linux go vet -tags nogui ./..., GOOS=windows
  go vet ./... at 970931203.
- after rebasing on f9ca3dd44: gofmt, GOOS=linux and GOOS=windows go vet
  ./internal/..., and go test ./internal/provider ./internal/gateway
  ./internal/gui ./internal/catalog -count=1 at 182d84f2b on mote:
  provider and catalog ok; gateway and gui red only in
  TestBrowserExtensionOnlyFromItsOrigin (#4631) and
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514), as on main.
- An earlier WSL full run wedged in go test with no child for 30
  minutes beside two other sessions' GUI suites and was stopped; its
  internal/agent reds are WSL's binfmt (#4033, #3548).

GUI: app.js is unchanged; only /api/providers' deciders list gains a
hand-picked variant, which app.js already reads. The GUI suite was not
run; its decision tests run on fixtures.

Not covered: a custom (non-preset) provider at openrouter.ai has no
Decide base, so its decision models still go to chat/completions
(#4614): filling Decide by host could override a value the user cleared.

Not tried: the whole magpie path end to end with a real OpenRouter key
(the probe called OpenRouter directly).
2026-11-01 03:07:06 +08:00

117 lines
4.7 KiB
Go

package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
)
// openRouterUp stands in for openrouter.ai, in process: /api/v1/systemone
// answers Mercury Decide's way (the wrapper as OpenRouter served it on
// 2026-11-01), and anything else gets the 400 coeo91 saw. Requests for any
// other host go to the test's own servers.
type openRouterUp struct {
mu sync.Mutex
asked []string // path and model of each request to openrouter.ai
next http.RoundTripper
}
func (u *openRouterUp) RoundTrip(r *http.Request) (*http.Response, error) {
if r.URL.Hostname() != "openrouter.ai" {
return u.next.RoundTrip(r)
}
b, _ := io.ReadAll(r.Body)
var q struct{ Model string }
json.Unmarshal(b, &q)
u.mu.Lock()
u.asked = append(u.asked, r.URL.Path+" "+q.Model)
u.mu.Unlock()
code, body := 400, `{"error":{"message":"`+q.Model+` is a decisions model and cannot be used with the chat/completions endpoint. Use the /api/alpha/decisions endpoint instead.","code":400}}`
if r.URL.Path == "/api/v1/systemone" {
code, body = 200, `{"model":"inception/mercury-decide-20260930","answers":{"intent":{"type":"choice","choice":"debugging","confidence":0.9}},"usage":{"input_tokens":72,"output_tokens":1,"cost":0.00000144},"id":"gen-dec-1793467694-KCls8tvRNbusIJmB9FhD","provider":"Inception"}`
}
return &http.Response{StatusCode: code, Header: http.Header{"Content-Type": {"application/json"}},
Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
}
func (u *openRouterUp) got() []string {
u.mu.Lock()
defer u.mu.Unlock()
return slices.Clone(u.asked)
}
// coeo91 on Discord: OpenRouter's inception/mercury-decide:free, picked by
// hand into a group used as smart routing's decision model, was sent to
// chat/completions and refused 400 ("is a decisions model"). The variant of
// a model OpenRouter lists as a decision model is one too: the group of it
// is asked at /api/v1/systemone, and a chat or count_tokens request naming
// it is refused here, before OpenRouter is asked.
func TestOpenRouterDecisionVariantNeverChats(t *testing.T) {
_, _, _ = ruled(t)
const variant = "inception/mercury-decide:free"
const base = "https://openrouter.ai/api/v1"
if err := provider.Save(provider.Provider{ID: "openrouter", Name: "OpenRouter", Preset: "openrouter", Key: "kor",
Chat: base, Models: []string{"openai/gpt-5", variant}}); err != nil {
t.Fatal(err)
}
// OpenRouter's two lists: the decisions list names the model once,
// without :free
if err := catalog.SaveLive("openrouter", base, []catalog.Model{{ID: "openai/gpt-5", Context: 400000}}); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive("openrouter.decisions", base, []catalog.Model{{ID: "inception/mercury-decide", Context: 65536}}); err != nil {
t.Fatal(err)
}
if err := provider.SaveGroup(provider.Group{Name: "Decide", Members: []string{"openrouter/" + variant}}); err != nil {
t.Fatal(err)
}
g, _, _ := provider.FindGroup("group/r")
g.Rules, g.Classifier = []provider.Rule{{Use: "b/big", Intent: "debugging"}}, "group/decide"
if err := provider.SaveGroup(g); err != nil {
t.Fatal(err)
}
up := &openRouterUp{next: http.DefaultTransport}
old := http.DefaultClient.Transport
http.DefaultClient.Transport = up
t.Cleanup(func() { http.DefaultClient.Transport = old })
s := New()
s.client = &http.Client{Transport: up}
// the classifier asks the group at /systemone, and the turn goes where
// its answer says
out, r := postOK(t, s, "or1", chat("why does this crash?", nil, 0, ""))
if !strings.Contains(out, "from kb") || r.Rule.Classified.Intent != "debugging" || r.Rule.Classified.Error != "" {
t.Fatalf("classified: %s %+v", out, r.Rule.Classified)
}
if got := up.got(); !slices.Equal(got, []string{"/api/v1/systemone " + variant}) {
t.Fatalf("OpenRouter asked: %v", got)
}
// an agent's chat naming it is refused here
code, out := postAs(t, s, "or2", `{"model":"openrouter/`+variant+`","messages":[{"role":"user","content":"hi"}]}`)
if code != 400 || !strings.Contains(out, "only decides") {
t.Fatalf("chat: %d %s", code, out)
}
// and so is counting its tokens, for the model and for its group
for _, m := range []string{"openrouter/" + variant, "group/decide"} {
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/messages/count_tokens", strings.NewReader(
`{"model":"`+m+`","messages":[{"role":"user","content":"hi"}]}`))
s.Handler().ServeHTTP(rec, req)
if rec.Code != 400 || !strings.Contains(rec.Body.String(), "only decides") {
t.Fatalf("count_tokens %s: %d %s", m, rec.Code, rec.Body.String())
}
}
if got := up.got(); len(got) != 1 {
t.Fatalf("OpenRouter asked: %v", got)
}
}