diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index a908c23db..5296d59a2 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -84,14 +84,17 @@ An older peer without the decision-list extension continues serving its other APIs but must be updated before its decisions can be discovered. See [`decide.go`](../../internal/provider/decide.go). -oMLX (#1641) is such a mixed provider too: its server lists Clef, Clef-Flash -and OpenJev among its chat models with nothing to tell them apart, so its -decision models are the ones its `/v1/models/status` gives `model_type` -`decision`, by the name `/v1/models` uses (its alias), kept under +oMLX (#1641) and MLX-Serve are such mixed providers too: oMLX's server lists +Clef, Clef-Flash and OpenJev among its chat models with nothing to tell them +apart, so its decision models are the ones its `/v1/models/status` gives +`model_type` `decision`, by the name `/v1/models` uses (its alias), kept under `.decisions` like OpenRouter's (`omlxDecides`, `listedOMLXDecide` in -[`omlx_decide.go`](../../internal/provider/omlx_decide.go)). A server with -none lists none, and no Jev is made up for it. An oMLX provider saved -before the preset had a decision base gets its chat base as one. +[`omlx_decide.go`](../../internal/provider/omlx_decide.go)). MLX-Serve marks +them in its `/v1/models` with `capabilities: ["decisions"]`, kept under +`.decisions` (`mlxServeDecides`, `listedMLXServeDecide` in +[`mlxserve_decide.go`](../../internal/provider/mlxserve_decide.go)). A server +with none lists none, and no Jev is made up for it. An oMLX or MLX-Serve +provider saved before the preset had a decision base gets its chat base as one. The CLI and TUI report model-list fetch errors for remote and other mixed providers (such as OpenRouter, serving conversation and decision models). Only a diff --git a/internal/provider/decide.go b/internal/provider/decide.go index c19a6425a..ef657ed17 100644 --- a/internal/provider/decide.go +++ b/internal/provider/decide.go @@ -150,10 +150,10 @@ func openRouterDecisions(base string) string { } // listsDecisions reports whether p's decision models are a list of their -// own, OpenRouter's or oMLX's (omlxDecides), rather than Jev's ids among -// its chat models. +// own, OpenRouter's, oMLX's (omlxDecides) or MLX-Serve's (mlxServeDecides), +// rather than Jev's ids among its chat models. func (p Provider) listsDecisions() bool { - return openRouterDecisions(p.Decide) != "" || p.omlxDecides() + return openRouterDecisions(p.Decide) != "" || p.omlxDecides() || p.mlxServeDecides() } // decisionsID is where a provider that serves conversations too keeps the @@ -195,7 +195,7 @@ func (p Provider) decideListDue() bool { return false } live, _, ok := catalog.Live(id) - if p.omlxDecides() { + if p.omlxDecides() || p.mlxServeDecides() { // a server with no decision model loaded lists none, for good return !ok } @@ -281,8 +281,9 @@ func (p Provider) Jev() string { } // OpenRouter's Jev is ~typesafe/jev-latest, in its list of decision // models; its Jev Router is a chat model - if p.omlxDecides() { - // oMLX has no Jev of its own: its first decision model, if any + if p.omlxDecides() || p.mlxServeDecides() { + // oMLX and MLX-Serve have no Jev of their own: their first decision + // model, if any if ms := p.decideListed(); len(ms) > 0 { return ms[0].ID } @@ -388,7 +389,7 @@ func (p Provider) decideListed() []catalog.Model { if live, _, ok := catalog.Live(decisionsID(p.ID)); ok && len(live) > 0 { return live } - if p.omlxDecides() { + if p.omlxDecides() || p.mlxServeDecides() { return nil // none until its server says which } return []catalog.Model{{ID: OpenRouterJev, Name: "Jev"}} @@ -788,6 +789,8 @@ func (p Provider) fetchDecide(ctx context.Context) ([]catalog.Model, error) { list, all = u, true } else if p.omlxDecides() { list = omlxDecisions(p.Decide) + } else if p.mlxServeDecides() { + list = mlxServeDecisions(p.Decide) } else if bailianDecides(p.Decide) { // Bailian lists its chat models only: its decision model is asked return p.decideAsked(ctx) @@ -822,6 +825,14 @@ func (p Provider) fetchDecide(ctx context.Context) ([]catalog.Model, error) { } return ms, catalog.SaveLive(decisionsID(p.ID), p.Decide, ms) } + if p.mlxServeDecides() { + // none is an answer too: the server has no decision model now + ms, err := listedMLXServeDecide(b) + if err != nil { + return nil, fmt.Errorf("%s: %s", p.Name, err) + } + return ms, catalog.SaveLive(decisionsID(p.ID), p.Decide, ms) + } ms, err := listedDecide(b, all) if (err != nil || len(ms) == 0) && own { return p.decideAsked(ctx) diff --git a/internal/provider/mlxserve_decide.go b/internal/provider/mlxserve_decide.go new file mode 100644 index 000000000..1541555d6 --- /dev/null +++ b/internal/provider/mlxserve_decide.go @@ -0,0 +1,78 @@ +package provider + +import ( + "encoding/json" + "fmt" + "slices" + "strings" + + "github.com/yetone/magpie/internal/catalog" +) + +// MLXServePreset is the MLX-Serve preset's id. +const MLXServePreset = "mlx-serve" + +// MLX-Serve (github.com/ddalcu/mlx-serve) serves decision models — +// Clef, Clef-Flash, Kev, Laya, D1 — at POST /v1/systemone (and /v1/decisions), +// System One's questions and answers. Its /v1/models lists them alongside +// chat models, marking them with capabilities: ["decisions"]. That list +// is the provider's decision models, as oMLX's and OpenRouter's are +// (listsDecisions), and a model without that capability stays a chat model. +func (p Provider) mlxServeDecides() bool { + return p.Preset == MLXServePreset && p.Decide != "" && !p.DecideOnly() +} + +// mlxServeDecisions is where MLX-Serve lists its models and capabilities. +func mlxServeDecisions(base string) string { + return strings.TrimRight(base, "/") + "/models" +} + +type mlxServeModel struct { + ID string `json:"id"` + ContextLength int `json:"context_length"` + MaxModelLen int `json:"max_model_len"` + Capabilities []string `json:"capabilities"` + InputModalities []string `json:"input_modalities"` +} + +// listedMLXServeDecide are the decision models in MLX-Serve's /v1/models: +// those whose capabilities include "decisions", with the window and input +// modalities MLX-Serve serves them with. +func listedMLXServeDecide(b []byte) ([]catalog.Model, error) { + var out struct { + Data *[]mlxServeModel `json:"data"` + Models *[]mlxServeModel `json:"models"` + } + if err := json.Unmarshal(b, &out); err != nil || (out.Data == nil && out.Models == nil) { + return nil, fmt.Errorf("not MLX-Serve's model list") + } + rows := out.Data + if rows == nil { + rows = out.Models + } + ms := []catalog.Model{} + for _, m := range *rows { + if m.ID == "" || !slices.Contains(m.Capabilities, "decisions") { + continue + } + ctx := m.MaxModelLen + if ctx <= 0 { + ctx = m.ContextLength + } + var imageInput *bool + images := false + if len(m.InputModalities) > 0 { + images = slices.Contains(m.InputModalities, "image") + imageInput = &images + } + ms = append(ms, catalog.Model{ + ID: m.ID, + Name: m.ID, + Context: ctx, + ImageInput: imageInput, + Images: images, + InputModalities: m.InputModalities, + }) + } + return ms, nil +} diff --git a/internal/provider/mlxserve_decide_test.go b/internal/provider/mlxserve_decide_test.go new file mode 100644 index 000000000..477320221 --- /dev/null +++ b/internal/provider/mlxserve_decide_test.go @@ -0,0 +1,265 @@ +package provider + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "slices" + "sync" + "testing" + + "github.com/yetone/magpie/internal/catalog" +) + +// fakeMLXServe answers as MLX-Serve (github.com/ddalcu/mlx-serve) does: +// /v1/models lists loaded and discovered models with their capabilities and +// input modalities; decision models have capabilities: ["decisions"]; +// /v1/systemone answers System One questions; +// /v1/chat/completions answers chat requests but rejects typed-decision models with 400. +func fakeMLXServe(t *testing.T) (base string, asked func() []string) { + t.Helper() + var mu sync.Mutex + var models []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/v1/models": + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"object":"list","data":[` + + `{"id":"clef-flash-4bit","object":"model","created":1791860041,"owned_by":"mlx-serve","loaded":true,"state":"ready","bytes_resident":6193757576,"bytes_on_disk":5950219560,"context_length":4096,"max_model_len":4096,"batched_decode":true,"capabilities":["decisions"],"input_modalities":["text"],"meta":{"architecture":"clef","engine":"mlx","context_length":4096,"model_max_tokens":4096}},` + + `{"id":"Qwen3.6-35B-A3B-MLX-4bit","object":"model","created":0,"owned_by":"mlx-serve","loaded":false,"state":"unloaded","bytes_resident":0,"bytes_on_disk":20402204271,"context_length":262144,"max_model_len":262144,"capabilities":["chat","tool_use","streaming","json_schema","vision"],"input_modalities":["text","image","video"],"meta":{"architecture":"qwen3_5_moe","engine":"mlx","context_length":262144,"model_max_tokens":262144}},` + + `{"id":"gemma-4-26B-A4B-it-qat-q4_0-gguf","object":"model","created":0,"owned_by":"mlx-serve","loaded":false,"state":"unloaded","bytes_resident":0,"bytes_on_disk":16000000000,"capabilities":["chat","tool_use","streaming","json_schema"],"input_modalities":["text"],"meta":{"architecture":"gguf","engine":"gguf"}}` + + `]}`)) + case "/v1/systemone": + var q struct{ Model string } + json.NewDecoder(r.Body).Decode(&q) + mu.Lock() + models = append(models, q.Model) + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"model":"` + q.Model + `","answers":{"ok":{"type":"noul","noul":0.5322}},"usage":{"input_tokens":146,"output_tokens":0}}`)) + case "/v1/chat/completions": + var q struct{ Model string } + json.NewDecoder(r.Body).Decode(&q) + w.Header().Set("Content-Type", "application/json") + if q.Model == "clef-flash-4bit" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(`{"error":{"message":"This is a typed-decision model; it cannot serve chat/text requests. Use POST /v1/decisions instead.","type":"invalid_request_error","param":null,"code":400}}`)) + return + } + w.Write([]byte(`{"id":"chatcmpl-1","object":"chat.completion","model":"` + q.Model + `","choices":[{"index":0,"message":{"role":"assistant","content":"hello"},"finish_reason":"stop"}]}`)) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + return srv.URL, func() []string { + mu.Lock() + defer mu.Unlock() + return slices.Clone(models) + } +} + +// MLX-Serve's decision models: an MLX-Serve provider serves decision models +// (Clef, Clef-Flash, Kev, Laya, D1) at POST /v1/systemone, and its decision +// models are the ones /v1/models marks with capabilities: ["decisions"]. They +// classify routing groups, are never offered as chat models to agents, and +// provider test runs them via decide. +func TestMlxServeDecisionModels(t *testing.T) { + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + base, asked := fakeMLXServe(t) + + // an MLX-Serve provider saved before its preset had System One, at a port + // of the user's own + if err := Save(Provider{ID: "mlx-serve", Name: "MLX-Serve", Preset: MLXServePreset, + Chat: base + "/v1", Responses: base + "/v1", Anthropic: base}); err != nil { + t.Fatal(err) + } + p, err := Find("mlx-serve") + if err != nil || !p.Decides() || p.DecideOnly() || p.Decide != base+"/v1" { + t.Fatalf("MLX-Serve has no decision API at its own server: %+v", p) + } + if _, err := p.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + p, _ = Find("mlx-serve") + + if !p.DecidesModel("clef-flash-4bit") || p.DecidesModel("Qwen3.6-35B-A3B-MLX-4bit") || p.DecidesModel("gemma-4-26B-A4B-it-qat-q4_0-gguf") { + t.Fatal("decision models are not the ones MLX-Serve capabilities say are") + } + var deciders []string + for _, e := range Deciders() { + deciders = append(deciders, e.ID) + } + if !slices.Equal(deciders, []string{"mlx-serve/clef-flash-4bit"}) { + t.Fatalf("deciders: %v", deciders) + } + var agents []string + for _, e := range providerEntries() { + agents = append(agents, e.Model) + } + if !slices.Equal(agents, []string{"Qwen3.6-35B-A3B-MLX-4bit", "gemma-4-26B-A4B-it-qat-q4_0-gguf"}) { + t.Fatalf("agents' models: %v", agents) + } + for _, m := range p.DecisionModels() { + if m.ID == "clef-flash-4bit" && (ListedWindow(m) != 4096 || m.ImageInput == nil || *m.ImageInput) { + t.Fatalf("Clef-Flash: %+v", m) + } + } + + q, m, err := RouteDecider("mlx-serve/clef-flash-4bit") + if err != nil || q.ID != "mlx-serve" || m != "clef-flash-4bit" { + t.Fatalf("routed to %s %s: %v", q.ID, m, err) + } + if err := q.AskSystemOne(context.Background(), m); err != nil { + t.Fatal(err) + } + if _, m, _ := RouteDecider("mlx-serve"); m != "clef-flash-4bit" { + t.Fatalf("MLX-Serve's default decision model: %q", m) + } + if got := asked(); !slices.Equal(got, []string{"clef-flash-4bit"}) { + t.Fatalf("asked: %v", got) + } + + // provider test mlx-serve clef-flash-4bit tests it via decide + results := p.TestModels(context.Background(), []string{"clef-flash-4bit"}) + if len(results) != 1 || !results[0].OK || results[0].Protocol != "decide" { + t.Fatalf("TestModels clef-flash-4bit: %+v", results) + } + + // chat models are still tested via chat + chatResults := p.TestModels(context.Background(), []string{"Qwen3.6-35B-A3B-MLX-4bit"}) + if len(chatResults) != 1 || !chatResults[0].OK || chatResults[0].Protocol != Chat { + t.Fatalf("TestModels chat model: %+v", chatResults) + } + + // default provider probe tests chat endpoints with chat models, and decide with clef-flash-4bit + defResults := p.Test(context.Background()) + for _, r := range defResults { + if r.Protocol != "decide" && r.Model == "clef-flash-4bit" { + t.Fatalf("default provider test selected decision model for %s: %+v", r.Protocol, r) + } + } +} + +// Table tests for listedMLXServeDecide using real and edge-case responses. +func TestListedMLXServeDecideTable(t *testing.T) { + tests := []struct { + name string + body string + want []catalog.Model + wantErr bool + }{ + { + name: "real captured response with decision and chat models", + body: `{"object":"list","data":[` + + `{"id":"clef-flash-4bit","context_length":4096,"max_model_len":4096,"capabilities":["decisions"],"input_modalities":["text"]},` + + `{"id":"Qwen3.6-35B-A3B-MLX-4bit","context_length":262144,"capabilities":["chat","tool_use"],"input_modalities":["text","image"]}` + + `]}`, + want: []catalog.Model{ + { + ID: "clef-flash-4bit", + Name: "clef-flash-4bit", + Context: 4096, + Images: false, + InputModalities: []string{"text"}, + }, + }, + }, + { + name: "decision model with vision input modality", + body: `{"object":"list","data":[` + + `{"id":"clef-vl","context_length":65536,"capabilities":["decisions"],"input_modalities":["text","image"]}` + + `]}`, + want: []catalog.Model{ + { + ID: "clef-vl", + Name: "clef-vl", + Context: 65536, + Images: true, + InputModalities: []string{"text", "image"}, + }, + }, + }, + { + name: "models field fallback and omitted input modalities", + body: `{"models":[` + + `{"id":"clef-base","context_length":4096,"capabilities":["decisions"]}` + + `]}`, + want: []catalog.Model{ + { + ID: "clef-base", + Name: "clef-base", + Context: 4096, + }, + }, + }, + { + name: "server with chat models only", + body: `{"object":"list","data":[` + + `{"id":"qwen-chat","capabilities":["chat","tools"],"input_modalities":["text"]}` + + `]}`, + want: []catalog.Model{}, + }, + { + name: "empty models list", + body: `{"object":"list","data":[]}`, + want: []catalog.Model{}, + }, + { + name: "invalid json", + body: `{"detail":"Not Found"}`, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := listedMLXServeDecide([]byte(tt.body)) + if (err != nil) != tt.wantErr { + t.Fatalf("listedMLXServeDecide() error = %v, wantErr %v", err, tt.wantErr) + } + if tt.wantErr { + return + } + if len(got) != len(tt.want) { + t.Fatalf("got %d models, want %d", len(got), len(tt.want)) + } + for i := range got { + if got[i].ID != tt.want[i].ID || got[i].Context != tt.want[i].Context || got[i].Images != tt.want[i].Images { + t.Errorf("model[%d] = %+v, want %+v", i, got[i], tt.want[i]) + } + if len(tt.want[i].InputModalities) > 0 { + if got[i].ImageInput == nil || *got[i].ImageInput != tt.want[i].Images { + t.Errorf("model[%d] ImageInput want %v, got %v", i, tt.want[i].Images, got[i].ImageInput) + } + } else if got[i].ImageInput != nil { + t.Errorf("model[%d] ImageInput want nil, got %v", i, *got[i].ImageInput) + } + } + }) + } +} + +// An MLX-Serve server with no decision model has none: no Jev is made up, +// and its chat models stay chat models. +func TestMLXServeWithoutDecisionModels(t *testing.T) { + ms, err := listedMLXServeDecide([]byte(`{"data":[{"id":"Qwen3-8B-4bit","capabilities":["chat"],"input_modalities":["text"]}]}`)) + if err != nil || len(ms) != 0 { + t.Fatalf("%v %v", ms, err) + } + if _, err := listedMLXServeDecide([]byte(`{"detail":"Not Found"}`)); err == nil { + t.Fatal("a 404's body read as a list") + } + p := Provider{ID: "mlx-serve-x", Preset: MLXServePreset, Chat: "http://127.0.0.1:1/v1", Decide: "http://127.0.0.1:1/v1"} + if got := p.decideListed(); len(got) != 0 { + t.Fatalf("made up: %v", got) + } + if p.Jev() != "" || p.DecidesModel("Qwen3-8B-4bit") { + t.Fatalf("Jev: %q", p.Jev()) + } +} diff --git a/internal/provider/mlxserve_test.go b/internal/provider/mlxserve_test.go index a89f10afe..f0ff9f3ea 100644 --- a/internal/provider/mlxserve_test.go +++ b/internal/provider/mlxserve_test.go @@ -20,8 +20,8 @@ func TestMlxServePreset(t *testing.T) { if pr.Kind != KindLocal || !pr.NoKey || pr.KeysURL != "" { t.Fatalf("kind/noKey/keysURL: %q %v %q", pr.Kind, pr.NoKey, pr.KeysURL) } - if pr.Chat != "http://localhost:11234/v1" || pr.Responses != "http://localhost:11234/v1" || pr.Anthropic != "http://localhost:11234" { - t.Fatalf("endpoints: %q %q %q", pr.Chat, pr.Responses, pr.Anthropic) + if pr.Chat != "http://localhost:11234/v1" || pr.Responses != "http://localhost:11234/v1" || pr.Anthropic != "http://localhost:11234" || pr.Decide != "http://localhost:11234/v1" { + t.Fatalf("endpoints: %q %q %q %q", pr.Chat, pr.Responses, pr.Anthropic, pr.Decide) } p, err := FromPreset("mlx-serve") if err != nil { @@ -53,7 +53,7 @@ func TestMlxServeModels(t *testing.T) { if err != nil { t.Fatal(err) } - p.Chat, p.Responses = srv.URL+"/v1", srv.URL+"/v1" + p.Chat, p.Responses, p.Decide = srv.URL+"/v1", srv.URL+"/v1", srv.URL+"/v1" models, err := p.Fetch(context.Background()) if err != nil { t.Fatal(err) diff --git a/internal/provider/presets.go b/internal/provider/presets.go index dfc1f55a6..30be4a11b 100644 --- a/internal/provider/presets.go +++ b/internal/provider/presets.go @@ -547,9 +547,12 @@ var presets = []PresetDef{ Chat: "http://localhost:8000/v1", Responses: "http://localhost:8000/v1", Anthropic: "http://localhost:8000", Decide: "http://localhost:8000/v1", Note: "local server, port 8000 by default", Website: "https://omlx.ai"}, - {ID: "mlx-serve", Name: "MLX-Serve", Icon: "mlx-serve", Kind: KindLocal, NoKey: true, + // its decision models (Clef, Clef-Flash, Kev, Laya, D1), served at + // /v1/systemone, are marked by capabilities in /v1/models (mlxserve_decide.go) + {ID: MLXServePreset, Name: "MLX-Serve", Icon: "mlx-serve", Kind: KindLocal, NoKey: true, Chat: "http://localhost:11234/v1", Responses: "http://localhost:11234/v1", Anthropic: "http://localhost:11234", - Note: "local server, port 11234 by default", Website: "https://github.com/ddalcu/mlx-serve"}, + Decide: "http://localhost:11234/v1", + Note: "local server, port 11234 by default", Website: "https://github.com/ddalcu/mlx-serve"}, // another computer's magpie, shared on its network (remote_magpie.go): // its providers, routing groups and usage stay there, each request diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 3def8a243..90bbbae35 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -1126,9 +1126,9 @@ func normalize(p Provider) Provider { p.Decide = pr.Decide } } - // an oMLX provider saved before its preset had System One (#1641) + // an oMLX or MLX-Serve provider saved before its preset had System One (#1641) // asks it where its chat completions are, at whatever port it was given - if p.Preset == OMLXPreset && p.Decide == "" && p.Chat != "" { + if (p.Preset == OMLXPreset || p.Preset == MLXServePreset) && p.Decide == "" && p.Chat != "" { p.Decide = p.Chat } if p.Routing != Ordered && p.Routing != Rotate && p.Routing != LeastUsed && p.Routing != Pace && p.Routing != Weighted {