gateway: models of one API other than chat are grouped by id on their route (#5339)

XYenon (Discord) has the same embedding model at several providers and
asked why it isn't grouped the way chat models are. It wasn't even
listed: a fetched list dropped every embedding, rerank, speech and
transcription model, so "embed-1" on /v1/embeddings was a 404 unless a
hand-made group named it.

- catalog: a fetched list keeps those models, tagged with their API
  (Model.Serves, read from the id by ServesOf: rerank, embed/bge-,
  whisper/transcribe, tts-/-tts). Chat() and Live() leave them out, so
  agents' model lists, gateway keys and Routing's chat pickers never
  see them; LiveServing(id, kind) reads them. The live file says
  "kinded": true; a list fetched before this is fetched again once a
  run (autolist), with no schedule needed.
- provider: KindGroup(kind, ref) is made per request, never stored, so
  it is in neither Groups() nor Catalog(). Its id is
  auto-<kind>:<model> ("group/auto-embedding:embed-1"); its members are
  the providers that serve exactly that id for that API, in the order
  they were added, none off, decide-only, serving none, or with the
  model disabled.
- gateway: embeddings, rerank, speech, transcriptions and videos pick
  the group by route (mediaMembers): a bare id is a kind group when
  more than one provider serves it, the group's own id always; a
  hand-made group still works through offChatList. A group is of its
  own API: an embedding model's id on /v1/rerank is a 404.

Run at bd0f33828 + this change, on WSL magpie-desktop (mote was
running another session's full suite):
- go test -tags nogui -count=1 -timeout 45m ./internal/catalog
  ./internal/provider ./internal/gateway: ok, ok, ok (594s). The first
  run was red in three tests that held a fetched list to leaving its
  embedding model out (TestFetchArkMarksVideoModels,
  TestNvidiaModelScopeLiveList, TestTencentTokenHubList); they now hold
  it kept, tagged embedding, and out of catalog.Chat.
- 22 GUI files over the model lists and Routing pickers, both engines,
  every language (group-pick-drawers image-models-hide video-models-hide
  model-kind routing-kind agent-models agent-models-picker
  agent-model-groups agent-models-only-picked gateway-key-models
  gateway-key-groups group-from-model-add unlisted-models
  models-select-all-api provider-add-models provider-detect-models
  routing-rule-models panel-routing-pick fallback-group group-unlists
  settings-groups i18n-keys): 229 of 244 pass. The 15 reds are in six
  files that a control run of those six at bd0f33828 has red the same
  (14 of 56): #4389, #4964, #5332, #4616 and, new, #5357
  (routing-rule-models webkit 390). agent-models webkit zh's opacity
  0.998 was red here only, a fixed 250ms wait: #5358. No GUI asset is
  changed here; the GUI tests stub /api.
- on mote: TestProviderListBeforeSave (internal/gui; the add form's
  list keeps an embedding model out) and
  TestPiModelsAskedOnTheirNativeAPI (internal/agent), ok.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet of catalog,
  provider and gateway on mote at this head, ok.

Rebased then on origin/main d620ff6b5 (one commit, internal/agent and
internal/sessions only), and b63b28958 (one mover min line) after; at
d620ff6b5 + this on mote: go build ./..., go vet
of catalog, provider, gateway, agent and sessions, go test
./internal/catalog and -run 'Kind|Fetch|Nvidia|Tencent|Serving' of
provider and gateway: ok.

Red on the old code: TestKindGroupsServeEachAPIByRoute (embed-1 404)
and TestVideoKindGroupByTheModelsID (404).
Broken by hand, each red, then restored:
- the fetch dropping serves != "" again: TestFetchKeepsModelsOfOtherAPIs;
- the once-a-run refetch forced off: TestKindlessListFetchedOnce;
- KindGroup's disabled-model check removed:
  TestKindGroupHoldsTheExactModel;
- LiveServing asked with "" (any kind): the rerank-by-embedding-id
  check gets 200 instead of 404.

Known gaps, not done here:
- The Routing group editor still offers only chat and image models, so
  a new hand-made group of different ids (bge-m3 / BAAI/bge-m3) can't
  pick kind models: #5352.
- A bare id whose every member is disabled is a 404, not a 403.
- Rerank, Qwen3-Embedding and bge models that sat among a provider's
  chat models before (textModel's words missed them) leave agents'
  lists now. A hand-made group naming one keeps serving.
- /v1/models lists no kind model; the Routing live view may show the
  raw kind id.
Not tried: real vendors' lists and routes; the full ./... suite at this
head (queued on mote after another session's run; reds get issues).
This commit is contained in:
yetone
2026-11-05 16:22:31 +08:00
parent b63b289589
commit a732f3c493
16 changed files with 691 additions and 42 deletions
File diff suppressed because one or more lines are too long
+37
View File
@@ -126,6 +126,12 @@ type Model struct {
// with (a Remote magpie's Grok Imagine Video): kept with the list for
// its videos API, never offered as a model to talk to or draw with.
Films bool `json:",omitempty"`
// Serves is set on a vendor-listed model made for an API other than
// chat, images or video (ServesEmbedding, ServesRerank, ServesSpeech,
// ServesTranscription): kept with the list for that API's routes and
// their groups of one kind (provider.KindGroup), never offered to
// agents as a model to talk to (#5339, XYenon on Discord).
Serves string `json:",omitempty"`
// Decides marks a decision model another magpie explicitly lists,
// including models whose ids don't name Jev.
Decides bool `json:",omitempty"`
@@ -1928,6 +1934,37 @@ func unprofiled(b string) (string, bool) {
return "", false
}
// The APIs a model Serves is made for.
const (
ServesEmbedding = "embedding"
ServesRerank = "rerank"
ServesSpeech = "speech"
ServesTranscription = "transcription"
)
// ServesOf is the API a model's id says it is made for, other than chat,
// images or video: "" for any other model. Read from the id alone, as
// vendors' OpenAI-style lists say no more (text-embedding-3-small,
// bge-reranker-v2-m3, tts-1, gpt-4o-mini-tts, whisper-1,
// gpt-4o-transcribe).
func ServesOf(id string) string {
id = strings.ToLower(id)
if i := strings.LastIndex(id, "/"); i >= 0 {
id = id[i+1:]
}
switch {
case strings.Contains(id, "rerank"):
return ServesRerank
case strings.Contains(id, "embed") || strings.HasPrefix(id, "bge-"):
return ServesEmbedding
case strings.Contains(id, "whisper") || strings.Contains(id, "transcribe"):
return ServesTranscription
case strings.HasPrefix(id, "tts-") || strings.Contains(id, "-tts"):
return ServesSpeech
}
return ""
}
func textModel(m mdModel) bool {
if len(m.Modalities.Output) > 0 {
text := false
+42 -5
View File
@@ -39,6 +39,9 @@ type liveFile struct {
// merged into Models. A base that can't be asked keeps its own part
// from the list saved before (#904).
Sides map[string][]Model `json:"sides,omitempty"`
// Kinded is set on a list saved since lists keep the models made for
// another API, tagged (Model.Serves): LiveKinded.
Kinded bool `json:"kinded,omitempty"`
// byID is the chat models by their id, in the list's order, made
// once a read: asked for every model of a list, a copy and a scan of
// the list each time cost 2,500 models' /v1/models seconds (K.Liu on
@@ -182,11 +185,37 @@ func LiveVideomakers(provider string) []Model {
return out
}
// Chat is ms without the models that draw or make videos.
// LiveServing are the models in the provider's fetched list made for the
// API serves names (Model.Serves), in the list's order; "" is every such
// model, whatever its API.
func LiveServing(provider, serves string) []Model {
f, err := readLive(provider)
if err != nil {
return nil
}
var out []Model
for _, m := range f.Models {
if m.Serves != "" && (serves == "" || m.Serves == serves) {
out = append(out, m)
}
}
return out
}
// LiveKinded is whether the provider's fetched list was saved since lists
// keep the models made for other APIs (Model.Serves): one saved before
// left them out, and is fetched again once to have them (#5339).
func LiveKinded(provider string) bool {
f, err := readLive(provider)
return err == nil && f.Kinded
}
// Chat is ms without the models that draw, make videos or are made for
// another API (Model.Serves).
func Chat(ms []Model) []Model {
out := make([]Model, 0, len(ms))
for _, m := range ms {
if !m.Draws && !m.Films {
if !m.Draws && !m.Films && m.Serves == "" {
out = append(out, m)
}
}
@@ -217,7 +246,7 @@ func SaveLiveSides(provider, base string, models []Model, sides map[string][]Mod
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
return err
}
b, _ := json.MarshalIndent(liveFile{Fetched: time.Now(), Base: base, Models: models, Sides: sides}, "", " ")
b, _ := json.MarshalIndent(liveFile{Fetched: time.Now(), Base: base, Models: models, Sides: sides, Kinded: true}, "", " ")
if err := os.WriteFile(p, b, 0o644); err != nil {
return err
}
@@ -658,7 +687,15 @@ func fetchPage(ctx context.Context, url, key string, anthropic bool, headers map
// and none the list says answers without text (Ark's 3D models)
md := mdModel{ID: id}
md.Modalities.Output = outs
if !drawer && !films && !decision && headers["X-Magpie-Drawers"] == "" && !textModel(md) {
// one made for another API (embeddings, rerank, speech,
// transcriptions) is kept, said so, for that API's routes and
// groups (#5339); another magpie's list keeps them as it lists
// them
serves := ""
if !drawer && !films && !decision && headers["X-Magpie-Drawers"] == "" {
serves = ServesOf(id)
}
if !drawer && !films && !decision && serves == "" && headers["X-Magpie-Drawers"] == "" && !textModel(md) {
continue
}
name, plain := r.DisplayName, ""
@@ -684,7 +721,7 @@ func fetchPage(ctx context.Context, url, key string, anthropic bool, headers map
if len(apis) == 0 {
apis = targetAPIs(r.TypeTarget)
}
m := Model{ID: id, Name: name, Plain: plain, ImageInput: input, APIs: apis, Draws: drawer, Films: films, Decides: decision,
m := Model{ID: id, Name: name, Plain: plain, ImageInput: input, APIs: apis, Draws: drawer, Films: films, Decides: decision, Serves: serves,
InputModalities: ins, OutputModalities: outs}
if n, ok := r.ContextLength.(float64); ok && n > 0 {
m.Context = int(n)
+8 -2
View File
@@ -16,7 +16,8 @@ import (
// list and in LiveVideomakers (axelburks on Discord: Ark's Seedance sat
// among the chat models, and the editor had no Video models to tick);
// Seedream draws, the one listed with no modalities too; a 3D model
// (output three_d) is no chat model; the text models stay.
// (output three_d) is no chat model; the embedding model is kept for
// /v1/embeddings, out of the chat models (#5339); the text models stay.
func TestFetchArkMarksVideoModels(t *testing.T) {
body, err := os.ReadFile("testdata/volcengine-ark-models-2026-11-03.json")
if err != nil {
@@ -30,9 +31,11 @@ func TestFetchArkMarksVideoModels(t *testing.T) {
if err != nil {
t.Fatal(err)
}
var films, draws, chat []string
var films, draws, chat, serves []string
for _, m := range ms {
switch {
case m.Serves != "":
serves = append(serves, m.ID+" "+m.Serves)
case m.Films:
films = append(films, m.ID)
case m.Draws:
@@ -50,6 +53,9 @@ func TestFetchArkMarksVideoModels(t *testing.T) {
if want := []string{"doubao-seedream-5-0-flash-260915", "doubao-seedream-5-0-pro-260628"}; !slices.Equal(draws, want) {
t.Errorf("image models %v, want %v", draws, want)
}
if want := []string{"doubao-embedding-vision-251215 embedding"}; !slices.Equal(serves, want) {
t.Errorf("models of other APIs %v, want %v", serves, want)
}
if want := []string{"doubao-seed-2-1-pro-260915", "doubao-seed-translation-250915", "kimi-k3-1-pro-261024"}; !slices.Equal(chat, want) {
t.Errorf("chat models %v, want %v", chat, want)
}
+86
View File
@@ -0,0 +1,86 @@
package catalog
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// A vendor's list keeps its models made for another API, each marked with
// the API (#5339): an embedding, a rerank, a speech and a transcription
// model. They were dropped before, so no route could find them under a
// group. They stay out of the chat models (Chat), and a moderation model,
// which no route of magpie's serves, is still dropped.
func TestFetchKeepsModelsOfOtherAPIs(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
rw.Write([]byte(`{"object":"list","data":[{"id":"chat-model"},{"id":"text-embedding-3-small"},{"id":"BAAI/bge-reranker-v2-m3"},{"id":"tts-1"},{"id":"whisper-1"},{"id":"omni-moderation-latest"}]}`))
}))
defer srv.Close()
ms, _, err := FetchAt(context.Background(), srv.URL+"/v1", "k", false, nil)
if err != nil {
t.Fatal(err)
}
got := map[string]string{}
for _, m := range ms {
got[m.ID] = m.Serves
}
want := map[string]string{
"chat-model": "",
"text-embedding-3-small": ServesEmbedding,
"BAAI/bge-reranker-v2-m3": ServesRerank,
"tts-1": ServesSpeech,
"whisper-1": ServesTranscription,
}
if len(got) != len(want) {
t.Fatalf("kept %v, want %v", got, want)
}
for id, s := range want {
if v, ok := got[id]; !ok || v != s {
t.Errorf("%s: %q %v, want %q", id, v, ok, s)
}
}
if c := Chat(ms); len(c) != 1 || c[0].ID != "chat-model" {
t.Errorf("Chat %v", c)
}
}
// A saved list's models of other APIs are found by API, and the list says
// it kept them, so a list saved before they were kept is known by it.
func TestLiveServingByAPI(t *testing.T) {
ms := []Model{{ID: "chat-model"}, {ID: "embed-1", Serves: ServesEmbedding}, {ID: "tts-1", Serves: ServesSpeech}}
if err := SaveLive("kinds-kp", "http://x/v1", ms); err != nil {
t.Fatal(err)
}
if !LiveKinded("kinds-kp") || LiveKinded("none") {
t.Fatal("LiveKinded")
}
var all []string
for _, m := range LiveServing("kinds-kp", "") {
all = append(all, m.ID)
}
if strings.Join(all, ",") != "embed-1,tts-1" {
t.Fatalf("LiveServing any: %v", all)
}
if e := LiveServing("kinds-kp", ServesEmbedding); len(e) != 1 || e[0].ID != "embed-1" {
t.Fatalf("LiveServing embedding: %v", e)
}
if live, _, _ := Live("kinds-kp"); len(Chat(live)) != 1 {
t.Fatalf("Chat of the saved list: %v", Chat(live))
}
}
func TestServesOf(t *testing.T) {
for id, want := range map[string]string{
"text-embedding-3-large": ServesEmbedding, "BAAI/bge-m3": ServesEmbedding, "Qwen/Qwen3-Embedding-8B": ServesEmbedding,
"bge-reranker-v2-m3": ServesRerank, "jina-reranker-m0": ServesRerank,
"tts-1-hd": ServesSpeech, "gpt-4o-mini-tts": ServesSpeech,
"whisper-1": ServesTranscription, "gpt-4o-transcribe": ServesTranscription,
"gpt-5.5": "", "claude-sonnet-5": "", "embedder-chat": ServesEmbedding,
} {
if got := ServesOf(id); got != want {
t.Errorf("ServesOf(%q) = %q, want %q", id, got, want)
}
}
}
+6 -5
View File
@@ -97,8 +97,9 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
s.record(call)
return
}
p, model, ok := resolveRetrievalModel(asked)
if _, _, isGroup := mediaMembers(asked); ok && !isGroup {
kind := retrievalKind(operation)
p, model, ok := resolveRetrievalModel(asked, kind)
if _, _, isGroup := mediaMembers(asked, kind); ok && !isGroup {
if msg, off := modelOff(p, model, asked); off {
call.Status, call.Error = 403, msg
writeError(w, provider.Chat, 403, msg)
@@ -116,7 +117,7 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
s.record(call)
return
}
g, ms, isGroup := mediaMembers(asked)
g, ms, isGroup := mediaMembers(asked, kind)
if isGroup {
r = heldByGroup(r, g) // held to the group's accounts, if it is
}
@@ -322,8 +323,8 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
// resolveRetrievalModel also finds a preset plan's embedding model by its
// bare id. Such models stay out of agents' chat-model lists, so the general
// resolver does not otherwise see them there.
func resolveRetrievalModel(id string) (provider.Provider, string, bool) {
if p, model, ok := mediaGroupFirst(id); ok {
func resolveRetrievalModel(id, kind string) (provider.Provider, string, bool) {
if p, model, ok := mediaGroupFirst(id, kind); ok {
return p, model, true
}
if p, model, ok := provider.Resolve(id); ok {
+2 -1
View File
@@ -11,6 +11,7 @@ import (
"testing"
"time"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/usage"
@@ -155,7 +156,7 @@ func TestPresetPlanEmbeddingResolvesOutsideChatModels(t *testing.T) {
t.Fatalf("embedding model exposed for chat: %+v", m)
}
}
got, model, ok := resolveRetrievalModel(embed[0].ID)
got, model, ok := resolveRetrievalModel(embed[0].ID, catalog.ServesEmbedding)
if !ok || got.ID != p.ID || model != embed[0].ID {
t.Fatalf("bare embedding resolved to %q/%q, %v", got.ID, model, ok)
}
+160
View File
@@ -0,0 +1,160 @@
package gateway
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// kindVendor is an OpenAI-style vendor whose list has a chat model and one
// model of each other API, and that serves each of those APIs; busy
// answers every one of them 429, out of quota. It counts what it is asked.
type kindVendor struct {
*httptest.Server
busy bool
mu sync.Mutex
asked []string
}
func newKindVendor(t *testing.T, busy bool) *kindVendor {
t.Helper()
v := &kindVendor{busy: busy}
v.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
v.mu.Lock()
v.asked = append(v.asked, r.Method+" "+r.URL.Path)
v.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
if r.Method == "GET" && r.URL.Path == "/v1/models" {
io.WriteString(w, `{"object":"list","data":[`+
`{"id":"chat-model","object":"model"},`+
`{"id":"embed-1","object":"model"},`+
`{"id":"bge-reranker-1","object":"model"},`+
`{"id":"tts-1","object":"model"},`+
`{"id":"whisper-1","object":"model"},`+
`{"id":"omni-moderation-latest","object":"model"}]}`)
return
}
if v.busy {
w.WriteHeader(429)
io.WriteString(w, `{"error":{"message":"quota exceeded"}}`)
return
}
switch r.URL.Path {
case "/v1/embeddings":
io.WriteString(w, `{"object":"list","data":[{"object":"embedding","index":0,"embedding":[0.5,0.25]}],"model":"embed-1","usage":{"prompt_tokens":1,"total_tokens":1}}`)
case "/v1/rerank":
io.WriteString(w, `{"results":[{"index":1,"relevance_score":0.75}]}`)
case "/v1/audio/speech":
w.Header().Set("Content-Type", "audio/mpeg")
w.Write([]byte("ID3 kind speech"))
case "/v1/audio/transcriptions":
io.WriteString(w, `{"text":"heard by kind"}`)
default:
w.WriteHeader(404)
io.WriteString(w, `{"error":{"message":"no route `+r.URL.Path+` `+string(b)+`"}}`)
}
}))
t.Cleanup(v.Close)
return v
}
func (v *kindVendor) log() []string {
v.mu.Lock()
defer v.mu.Unlock()
return append([]string(nil), v.asked...)
}
// #5339 (XYenon on Discord): a model of an API other than chat that two
// providers serve under one id is a group, found as a chat model's is,
// asked for by its id on its API's route or by the group's own id: the
// first provider out of quota passes the request to the next. The models
// come from the providers' fetched lists, which kept them apart from the
// chat models (an embedding model was dropped from the list before, so
// "embed-1" was a 404). None of it is offered to agents: /v1/models and
// the groups list have neither the models nor their groups. A group is of
// its own API: an embedding model's id on /v1/rerank is no reranker.
func TestKindGroupsServeEachAPIByRoute(t *testing.T) {
fresh(t)
busy, free := newKindVendor(t, true), newKindVendor(t, false)
// both have their chat model picked, as most providers do
saveFetched(t, provider.Provider{ID: "busy", Name: "Busy", Chat: busy.URL + "/v1", Key: "k", Models: []string{"chat-model"}})
saveFetched(t, provider.Provider{ID: "free", Name: "Free", Chat: free.URL + "/v1", Key: "k", Models: []string{"chat-model"}})
s := New()
if code, raw := postRetrieval(t, s, "/v1/embeddings", `{"model":"embed-1","input":"hi"}`); code != 200 || !strings.Contains(raw, `[0.5,0.25]`) {
t.Fatalf("embeddings by the model's id: %d %s", code, raw)
}
if code, raw := postRetrieval(t, s, "/v1/embeddings", `{"model":"group/auto-embedding:embed-1","input":"hi"}`); code != 200 || !strings.Contains(raw, `[0.5,0.25]`) {
t.Fatalf("embeddings by the group's id: %d %s", code, raw)
}
if code, raw := postRetrieval(t, s, "/v1/rerank", `{"model":"bge-reranker-1","query":"q","documents":["a","b"]}`); code != 200 || !strings.Contains(raw, `"relevance_score":0.75`) {
t.Fatalf("rerank: %d %s", code, raw)
}
if code, _, raw := postSpeech(t, s, "/v1/audio/speech", `{"model":"tts-1","input":"hello","voice":"alloy"}`); code != 200 || string(raw) != "ID3 kind speech" {
t.Fatalf("speech: %d %.200s", code, raw)
}
body, ctype := audioFormBody(t, "model", "whisper-1")
if code, _, raw := postAudio(t, s, "/v1/audio/transcriptions", ctype, body); code != 200 || !strings.Contains(raw, "heard by kind") {
t.Fatalf("transcription: %d %s", code, raw)
}
want := "GET /v1/models,POST /v1/embeddings,POST /v1/embeddings,POST /v1/rerank,POST /v1/audio/speech,POST /v1/audio/transcriptions"
if got := strings.Join(busy.log(), ","); got != want {
t.Fatalf("the busy provider was asked %s, want %s", got, want)
}
// a group is of its own API's route alone
for _, c := range []struct{ path, body string }{
{"/v1/rerank", `{"model":"embed-1","query":"q","documents":["a"]}`},
{"/v1/rerank", `{"model":"group/auto-embedding:embed-1","query":"q","documents":["a"]}`},
{"/v1/embeddings", `{"model":"tts-1","input":"hi"}`},
} {
if code, raw := postRetrieval(t, s, c.path, c.body); code != 404 {
t.Fatalf("%s %s: %d %s, want 404", c.path, c.body, code, raw)
}
}
// none of it is offered as a model to talk to
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("GET", "/v1/models", nil))
for _, id := range []string{"embed-1", "bge-reranker-1", "tts-1", "whisper-1", "auto-embedding", "moderation"} {
if strings.Contains(rec.Body.String(), id) {
t.Fatalf("/v1/models lists %s: %s", id, rec.Body.String())
}
}
for _, g := range provider.Groups() {
if strings.Contains(g.ID, ":") || strings.Contains(g.ID, "embed") || strings.Contains(g.ID, "tts") {
t.Fatalf("the groups list has %s", g.ID)
}
}
for _, e := range provider.Catalog() {
for _, id := range []string{"embed", "rerank", "tts", "whisper", "moderation"} {
if strings.Contains(e.ID, id) || strings.Contains(e.Model, id) {
t.Fatalf("agents are offered %s (%s)", e.ID, e.Model)
}
}
}
}
// A video model two providers list under one id is a group by that id on
// /v1/videos: the first that can't make it passes it to the next. Before,
// the bare id went to the first provider listing it and ended there.
func TestVideoKindGroupByTheModelsID(t *testing.T) {
fresh(t)
a, b := newOpenAIVideos(t), newOpenAIVideos(t)
a.lacks = "sk-a"
saveFetched(t, provider.Provider{ID: "a", Name: "A", Chat: a.URL + "/v1", Key: "sk-a", Models: []string{"gpt-5.5"}})
saveFetched(t, provider.Provider{ID: "b", Name: "B", Chat: b.URL + "/v1", Key: "sk-b", Models: []string{"gpt-5.5"}})
code, obj, raw := asKey(t, New().Handler(), "", "POST", "/v1/videos", `{"model":"vid-1","prompt":"a cat on a fence"}`)
if code != 200 || obj["model"] != "b/vid-1" {
t.Fatalf("video: %d %s", code, raw)
}
if got := strings.Join(a.log(), ","); !strings.Contains(got, "POST /v1/videos sk-a") {
t.Fatalf("the first provider was never asked: %v", a.log())
}
}
+95 -17
View File
@@ -2,23 +2,93 @@ package gateway
import (
"slices"
"strings"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
)
// mediaMembers is the routing group ref with its members ready now for
// an API that is no chat: embeddings, rerank, speech, transcriptions and
// videos. A provider's picks are of its chat models, and these models are
// in no chat list (catalog's textModel and pluginTalks leave embeddings,
// rerankers and speech models out when a list is fetched; videos are
// apart), so a member of a provider with picks was dropped as unpicked
// and a group of them was a 404 (XYenon on Discord). Such a member is
// kept, as a drawing's image models are (FindDrawingGroup, jzw690 on X).
// A chat model the user unticked (#3911) is on its provider's list and
// still stays out.
func mediaMembers(ref string) (provider.Group, []provider.Member, bool) {
return provider.FindGroupAlso(ref, offChatList)
// an API that is no chat, kind's (catalog.Serves*, provider.KindVideo):
// embeddings, rerank, speech, transcriptions and videos.
//
// A group the user made: a provider's picks are of its chat models, and
// these models are in no chat list (a fetched list keeps them apart,
// catalog.Model's Serves, Draws and Films), so a member of a provider
// with picks was dropped as unpicked and a group of them was a 404
// (XYenon on Discord). Such a member is kept, as a drawing's image models
// are (FindDrawingGroup, jzw690 on X). A chat model the user unticked
// (#3911) is on its provider's list and still stays out.
//
// A group magpie finds (#5339): the providers that serve a model of kind
// under exactly the same id, asked for by the group's id
// ("group/auto-embedding:embed-1") or by the model's own on its API's
// route ("embed-1" on /v1/embeddings) when more than one provider serves
// it (provider.KindGroup). It is in no list of groups, so agents, keys
// and Routing never see it.
func mediaMembers(ref, kind string) (provider.Group, []provider.Member, bool) {
if provider.IsGroupRef(ref) {
if g, ms, ok := provider.KindGroup(kind, ref, servesKind(kind)); ok {
return g, ms, true
}
return provider.FindGroupAlso(ref, offChatList)
}
if !bareRef(ref) {
return provider.Group{}, nil, false
}
if g, ms, ok := provider.KindGroup(kind, ref, servesKind(kind)); ok && len(ms) > 1 {
return g, ms, true
}
return provider.Group{}, nil, false
}
// bareRef is whether ref names no provider: "embed-1", or a vendor's id
// with a slash of its own ("BAAI/bge-m3") where no provider has the part
// before it as its id.
func bareRef(ref string) bool {
pid, _, ok := strings.Cut(strings.TrimSpace(ref), "/")
if !ok {
return true
}
_, err := provider.Find(pid)
return err != nil
}
// servesKind says whether a provider serves a model of kind's under that
// id: its fetched list says so (catalog.LiveServing; Videomakers for
// videos), its chat list has an id that says so (another magpie's list,
// which keeps them as it lists them), or, for embeddings, its plan names
// it (PlanEmbeddings).
func servesKind(kind string) func(p provider.Provider, model string) bool {
is := func(m catalog.Model, model string) bool { return m.ID == model }
if kind == provider.KindVideo {
return func(p provider.Provider, model string) bool {
return slices.ContainsFunc(Videomakers(p), func(m catalog.Model) bool { return is(m, model) })
}
}
return func(p provider.Provider, model string) bool {
if slices.ContainsFunc(catalog.LiveServing(p.ID, kind), func(m catalog.Model) bool { return is(m, model) }) {
return true
}
if catalog.ServesOf(model) == kind && slices.ContainsFunc(provider.KeptListing(p).Available, func(m catalog.Model) bool { return is(m, model) }) {
return true
}
return kind == catalog.ServesEmbedding && slices.ContainsFunc(p.PlanEmbeddings(), func(m catalog.Model) bool { return is(m, model) })
}
}
// retrievalKind is the kind of model an operation of serveRetrieval's is
// asked of.
func retrievalKind(operation string) string {
switch operation {
case "rerank":
return catalog.ServesRerank
case "speech":
return catalog.ServesSpeech
case "transcriptions", "translations":
return catalog.ServesTranscription
}
return catalog.ServesEmbedding
}
// offChatList is whether p's list of models to chat with lacks model:
@@ -27,14 +97,22 @@ func offChatList(p provider.Provider, model string) bool {
return !slices.ContainsFunc(provider.KeptListing(p).Available, func(m catalog.Model) bool { return m.ID == model })
}
// mediaGroupFirst is the first member of the group ref for an API that is
// no chat (mediaMembers): such a group is no model agents are offered, so
// Resolve, which reads their catalog, doesn't take it.
func mediaGroupFirst(ref string) (provider.Provider, string, bool) {
if !provider.IsGroupRef(ref) {
// mediaGroupFirst is the model ref names for an API that is no chat,
// kind's: a group's first member (mediaMembers), or the one provider that
// serves a bare id of that kind (provider.KindGroup). Such a group or
// model is none agents are offered, so Resolve, which reads their
// catalog, doesn't take it.
func mediaGroupFirst(ref, kind string) (provider.Provider, string, bool) {
if !provider.IsGroupRef(ref) && !bareRef(ref) {
return provider.Provider{}, "", false
}
if _, ms, ok := mediaMembers(ref); ok && len(ms) > 0 {
if _, ms, ok := mediaMembers(ref, kind); ok && len(ms) > 0 {
return ms[0].Provider, ms[0].Model, true
}
if provider.IsGroupRef(ref) {
return provider.Provider{}, "", false
}
if _, ms, ok := provider.KindGroup(kind, ref, servesKind(kind)); ok {
return ms[0].Provider, ms[0].Model, true
}
return provider.Provider{}, "", false
+7 -2
View File
@@ -1024,7 +1024,7 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) {
}
f.Model, call.Model = m, m
}
p, model, ok := mediaGroupFirst(f.Model)
p, model, ok := mediaGroupFirst(f.Model, provider.KindVideo)
if !ok {
p, model, ok = provider.Resolve(f.Model)
}
@@ -1039,7 +1039,12 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) {
fail(404, fmt.Sprintf("magpie knows no model %q to make videos with", f.Model))
return
}
g, ms, isGroup := groupToMake(f.Model, p, model, mediaMembers)
g, ms, isGroup := mediaMembers(f.Model, provider.KindVideo)
if !isGroup {
g, ms, isGroup = groupToMake(f.Model, p, model, func(ref string) (provider.Group, []provider.Member, bool) {
return mediaMembers(ref, provider.KindVideo)
})
}
if isGroup {
r = heldByGroup(r, g) // held to the group's accounts, if it is
}
+19 -4
View File
@@ -34,6 +34,7 @@ import (
"time"
"github.com/yetone/magpie/internal/beat"
"github.com/yetone/magpie/internal/catalog"
)
// MinRefreshEvery is the shortest RefreshEvery: a vendor's list changes
@@ -295,17 +296,27 @@ func refreshDueLists(ctx context.Context, now time.Time) []string {
own, _ := ownOf(f)
for _, p := range ordered(own, f.Order) {
every := p.RefreshInterval()
// a list saved before lists kept the models made for other APIs
// (embeddings, rerank, speech, transcriptions) is fetched again
// once, schedule or none, so their routes and groups have them
// without the user's Refresh (#5339); tried once a run, so one
// that fails waits for its schedule, the next start or a Refresh
listsTried.Lock()
_, triedOnce := listsTried.m[p.ID]
listsTried.Unlock()
_, fetched := p.Fetched()
once := !triedOnce && fetched && !catalog.LiveKinded(p.ID)
// one that lists nothing (Preset.NoList) has no list to keep fresh
if every == 0 || p.Off || !p.lists() {
if every == 0 && !once || p.Off || !p.lists() {
continue
}
if at, ok := p.Fetched(); ok && now.Sub(at) < every {
if at, ok := p.Fetched(); ok && !once && now.Sub(at) < every {
continue
}
listsTried.Lock()
tried, ok := listsTried.m[p.ID]
retry := min(every, listRetry)
if ok && now.Sub(tried) < retry {
if !once && ok && now.Sub(tried) < retry {
listsTried.Unlock()
continue
}
@@ -320,7 +331,11 @@ func refreshDueLists(ctx context.Context, now time.Time) []string {
cancel()
switch {
case err != nil && !errors.Is(err, context.Canceled):
log.Printf("%s: its scheduled list fetch failed: %s (tried again in %s)", p.ID, err, retry)
again := "tried again in " + retry.String()
if every == 0 {
again = "tried again on the next start or Refresh"
}
log.Printf("%s: its scheduled list fetch failed: %s (%s)", p.ID, err, again)
case err == nil:
log.Printf("%s: fetched its list on schedule, %d models%s%s", p.ID, len(ms), listNote(" taken by rule: ", taken), listNote(" no longer listed: ", dropped))
}
+61
View File
@@ -0,0 +1,61 @@
package provider
import "strings"
// A group of one kind is the models of one API other than chat (an
// embedding, rerank, speech, transcription or video model) that more than
// one provider serves under exactly the same id (#5339, XYenon on
// Discord). Unlike a chat model's found group (autoGroups) it is in no
// list of groups: agents, gateway keys and Routing offer chat models, and
// these are none. It is made when its API's route is asked for one, by its
// id there (KindGroup).
// kindPrefix starts a group of one kind's id: "auto-embedding:<model>".
// A chat model's found group is "auto-" and a slug, which has no ":", so
// the two never name the same group.
const kindPrefix = "auto-"
// KindGroupID is the id of the group of the API kind's model: its exact
// id, as the providers list it.
func KindGroupID(kind, model string) string {
return kindPrefix + kind + ":" + model
}
// kindModelOf is the model a group of kind's ref names: "group/" and
// KindGroupID's id, or the model's own id. ok is false for a group ref of
// another kind or of no kind.
func kindModelOf(kind, ref string) (string, bool) {
ref = strings.TrimSpace(ref)
gid, isGroup := GroupIDOf(ref)
if !isGroup {
return ref, ref != ""
}
model, ok := strings.CutPrefix(gid, kindPrefix+kind+":")
return model, ok && model != ""
}
// KindGroup is the group of the API kind's model ref names, with its
// members ready now: each provider has serves say serves the model under
// exactly that id, in the order the providers were added, none switched
// off and none the user disabled the model on (#1867). ref is the group's
// id ("group/auto-embedding:embed-1") or the model's own ("embed-1", which
// the route asks for: GroupFor by route). ok is false when no provider
// serves it; a group of one member is the model of that one.
func KindGroup(kind, ref string, serves func(p Provider, model string) bool) (Group, []Member, bool) {
model, ok := kindModelOf(kind, ref)
if !ok {
return Group{}, nil, false
}
off := disabledNow()
g := Group{ID: KindGroupID(kind, model), Name: model, Auto: true}
var ms []Member
for _, p := range All() {
if !p.On() || p.DecideOnly() || p.ServesNone() || off(p.ID, model) || !serves(p, model) {
continue
}
id := p.ID + "/" + model
g.Members = append(g.Members, id)
ms = append(ms, Member{ID: id, Path: []string{id}, Provider: p, Model: model})
}
return g, ms, len(ms) > 0
}
+153
View File
@@ -0,0 +1,153 @@
package provider
import (
"context"
"encoding/json"
"os"
"slices"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/catalog"
)
func memberIDs(ms []Member) []string {
var out []string
for _, m := range ms {
out = append(out, m.ID)
}
return out
}
// A group of one kind (#5339) has the providers that serve its model under
// exactly its id, in the order they were added, none switched off and none
// the model is disabled on; a model of another name, or of another case,
// is no member. It is in no list of groups and offered to no agent.
func TestKindGroupHoldsTheExactModel(t *testing.T) {
autolistHome(t)
lists := map[string][]string{
"one": {"chat-x", "embed-1"},
"two": {"chat-x", "Embed-1", "embed-1-v2"},
"three": {"chat-x", "embed-1"},
"four": {"chat-x", "embed-1"},
"five": {"chat-x", "embed-1"},
}
for _, id := range []string{"one", "two", "three", "four", "five"} {
r := newRelayList(t, lists[id]...)
p := Provider{ID: id, Name: id, Chat: r.srv.URL + "/v1", Key: "k", Models: []string{"chat-x"}}
if id == "four" {
p.Off = true
}
if err := Save(p); err != nil {
t.Fatal(err)
}
found, err := Find(id)
if err != nil {
t.Fatal(err)
}
if _, err := found.Fetch(context.Background()); err != nil {
t.Fatal(err)
}
}
if err := DisableModels("five/embed-1"); err != nil {
t.Fatal(err)
}
serves := func(p Provider, model string) bool {
for _, m := range catalog.LiveServing(p.ID, catalog.ServesEmbedding) {
if m.ID == model {
return true
}
}
return false
}
for _, ref := range []string{"embed-1", "group/" + KindGroupID(catalog.ServesEmbedding, "embed-1")} {
g, ms, ok := KindGroup(catalog.ServesEmbedding, ref, serves)
if !ok || g.ID != "auto-embedding:embed-1" || !g.Auto || !slices.Equal(memberIDs(ms), []string{"one/embed-1", "three/embed-1"}) || !slices.Equal(g.Members, memberIDs(ms)) {
t.Fatalf("%s: %v %v %v", ref, ok, g, memberIDs(ms))
}
}
// a group of another kind's id is not this kind's
if _, _, ok := KindGroup(catalog.ServesRerank, "group/auto-embedding:embed-1", serves); ok {
t.Fatal("an embedding group's id made a rerank group")
}
if _, ms, ok := KindGroup(catalog.ServesEmbedding, "embed-2", serves); ok {
t.Fatalf("a model no one serves made a group of %v", memberIDs(ms))
}
for _, g := range Groups() {
if strings.Contains(g.ID, "embed") || strings.Contains(g.ID, ":") {
t.Fatalf("Groups has %s", g.ID)
}
}
for _, e := range Catalog() {
if strings.Contains(strings.ToLower(e.ID+e.Model), "embed") {
t.Fatalf("agents are offered %s", e.ID)
}
}
}
// A list saved before its models made for other APIs were kept is fetched
// again once a run, with no schedule set, so embeddings and the rest find
// them without the user pressing Refresh (#5339); a list saved with them,
// and a provider never fetched, are left alone.
func TestKindlessListFetchedOnce(t *testing.T) {
autolistHome(t)
t.Cleanup(func() {
listsTried.Lock()
clear(listsTried.m)
listsTried.Unlock()
})
old := newRelayList(t, "chat-x", "embed-1")
kinded := newRelayList(t, "chat-x", "embed-1")
never := newRelayList(t, "chat-x")
for id, r := range map[string]*relayList{"old": old, "kinded": kinded, "never": never} {
if err := Save(Provider{ID: id, Name: id, Chat: r.srv.URL + "/v1", Key: "k", Models: []string{"chat-x"}}); err != nil {
t.Fatal(err)
}
if id == "never" {
continue
}
found, _ := Find(id)
if _, err := found.Fetch(context.Background()); err != nil {
t.Fatal(err)
}
}
// "old"'s list as a magpie before this one saved it: no kinded mark,
// embed-1 dropped
path := catalog.LivePath("old")
b, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
var f map[string]any
json.Unmarshal(b, &f)
delete(f, "kinded")
var kept []any
for _, m := range f["models"].([]any) {
if m.(map[string]any)["ID"] != "embed-1" {
kept = append(kept, m)
}
}
f["models"] = kept
b, _ = json.Marshal(f)
if err := os.WriteFile(path, b, 0o644); err != nil {
t.Fatal(err)
}
if catalog.LiveKinded("old") || !catalog.LiveKinded("kinded") || len(catalog.LiveServing("old", "")) != 0 {
t.Fatal("the old list's setup")
}
o, k, n := old.asked.Load(), kinded.asked.Load(), never.asked.Load()
now := time.Now()
if got := refreshDueLists(context.Background(), now); !slices.Equal(got, []string{"old"}) {
t.Fatalf("asked %v, want [old]", got)
}
if old.asked.Load() != o+1 || kinded.asked.Load() != k || never.asked.Load() != n {
t.Fatalf("lists asked: old %d, kinded %d, never %d", old.asked.Load()-o, kinded.asked.Load()-k, never.asked.Load()-n)
}
if ms := catalog.LiveServing("old", catalog.ServesEmbedding); len(ms) != 1 || ms[0].ID != "embed-1" || !catalog.LiveKinded("old") {
t.Fatalf("after the fetch: %v", ms)
}
if got := refreshDueLists(context.Background(), now.Add(time.Hour)); len(got) != 0 {
t.Fatalf("asked %v again", got)
}
}
+1
View File
@@ -1311,6 +1311,7 @@ func (p Provider) fetchPerKey(ctx context.Context, keys []KeyAccount) ([]catalog
old, _, _ := catalog.Live(p.ID)
old = append(old, catalog.LiveDrawers(p.ID)...)
old = append(old, catalog.LiveVideomakers(p.ID)...)
old = append(old, catalog.LiveServing(p.ID, "")...)
oldSides, _, _ := catalog.LiveSplit(p.ID)
var out []catalog.Model
var from [][]string // the bases that listed each model of out
+7 -3
View File
@@ -43,8 +43,9 @@ func TestNvidiaModelScopePresets(t *testing.T) {
}
}
// Their /v1/models, as each answers it: NVIDIA's embedding models are left
// out, ModelScope's rows (object "") are kept.
// Their /v1/models, as each answers it: NVIDIA's embedding models are kept
// for /v1/embeddings, out of the chat models (#5339); ModelScope's rows
// (object "") are kept.
func TestNvidiaModelScopeLiveList(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/models" || r.Header.Get("Authorization") != "Bearer k" {
@@ -61,7 +62,10 @@ func TestNvidiaModelScopeLiveList(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if len(ms) != 2 || ms[0].ID != "deepseek-ai/deepseek-v4-pro" || ms[1].ID != "ZhipuAI/GLM-5.2" {
if chat := catalog.Chat(ms); len(chat) != 2 || chat[0].ID != "deepseek-ai/deepseek-v4-pro" || chat[1].ID != "ZhipuAI/GLM-5.2" {
t.Fatalf("%+v", ms)
}
if len(ms) != 3 || ms[1].ID != "nvidia/nemotron-3-embed-1b" || ms[1].Serves != catalog.ServesEmbedding {
t.Fatalf("the embedding model: %+v", ms)
}
}
+6 -2
View File
@@ -302,7 +302,8 @@ func TestTencentCloudOldPresetsKeepWorking(t *testing.T) {
}
// TokenHub's /v1/models, as its docs show it, asked with the key as a
// Bearer: its language models are kept, the embedding one left out.
// Bearer: its language models are kept, the embedding one kept for
// /v1/embeddings, out of the chat models (#5339).
func TestTencentTokenHubList(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/models" || r.Header.Get("Authorization") != "Bearer sk-test" {
@@ -319,9 +320,12 @@ func TestTencentTokenHubList(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if len(ms) != 2 || ms[0].ID != "hy3" || ms[1].ID != "deepseek-v4-pro" {
if chat := catalog.Chat(ms); len(chat) != 2 || chat[0].ID != "hy3" || chat[1].ID != "deepseek-v4-pro" {
t.Fatalf("%+v", ms)
}
if len(ms) != 3 || ms[2].ID != "kinfra-text-embedding-0.6b" || ms[2].Serves != catalog.ServesEmbedding {
t.Fatalf("the embedding model: %+v", ms)
}
}
// Tencent moved Token Plan 个人版 from api.lkeap.cloud.tencent.com to