diff --git a/docs/integrating.md b/docs/integrating.md index 4009614d6..235a156f0 100644 --- a/docs/integrating.md +++ b/docs/integrating.md @@ -61,7 +61,10 @@ it takes images. List them from there rather than shipping a list: the user adds and removes providers in magpie. Reasoning is asked in your API's own field (`reasoning_effort`, `reasoning.effort`, Anthropic's `thinking` or `output_config.effort`). `?format=text` gives the ids one a -line. +line. The list holds chat models only. Ask for image and video models +with `?kind=image,video` (or `?kind=chat,image,video`, or `?kind=all`). +Each of them is marked `"kind": "image"` or `"kind": "video"` and goes to +`/v1/images/generations` or `/v1/videos`, never to a chat route. **Optional.** Send `X-Magpie-Session: ` with a conversation's requests and `GET /v1/magpie/route?session=` says which model a routing group diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index dc62458da..5f1fecce2 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -88,7 +88,13 @@ bases from one address (`remoteMagpieEndpoints` in [`remote_magpie.go`](../../internal/provider/remote_magpie.go)). Its model list requests images, videos and decisions with `X-Magpie-Drawers`, `X-Magpie-Videomakers` and `X-Magpie-Deciders`. The gateway includes these -only when asked, with `kind` of `image`, `video` or `decision`. Decision +only when asked, with `kind` of `image`, `video` or `decision`. Any other +client asks for image and video models with `?kind=` (`chat`, `image`, +`video`, comma separated, or `all`; `listKinds` in +[`gateway.go`](../../internal/gateway/gateway.go)); without it the list is +chat models alone, so no agent's chat picker offers an image or video +model, and an unknown kind is a 400 (axelburks on Discord; +`TestModelsListMediaOnlyWhenAsked`). Decision entries pass through `keyAllowed`, including model and account restrictions. [`catalog/live.go`](../../internal/catalog/live.go) keeps each kind and all models the remote already exposed, including retrieval models. The shared diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index e0fc44a79..a70a4c7a2 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1442,91 +1442,133 @@ func catalogFor(r *http.Request) []provider.Entry { return keyAllowed(r, shown) } +// listKinds is which of magpie's models a /v1/models call lists: its chat +// models alone, unless it names the kinds it wants in ?kind= (chat, image, +// video, comma separated; all for the three). Image and video models are +// listed only when asked for, each marked "kind" (drawerObjects, +// videomakerObjects): OpenAI's own list puts gpt-image and sora among its +// chat models with nothing to tell them apart, and the clients and agents +// that offer every id this list gives as a model to chat with (OpenCode's, +// Cherry Studio's, ZCode's pasted ?format=text) would offer an image model +// in their chat pickers (axelburks on Discord asked for them here). A kind +// it doesn't know is refused, not read as none. +func listKinds(r *http.Request) (chat, image, video bool, err error) { + q, ok := r.URL.Query()["kind"] + if !ok { + return true, false, false, nil + } + for _, v := range q { + for k := range strings.SplitSeq(v, ",") { + switch strings.ToLower(strings.TrimSpace(k)) { + case "chat": + chat = true + case "image": + image = true + case "video": + video = true + case "all": + chat, image, video = true, true, true + default: + return false, false, false, fmt.Errorf("kind %q: /v1/models lists the kinds chat, image and video (or all), comma separated", k) + } + } + } + return chat, image, video, nil +} + func (s *Server) models(w http.ResponseWriter, r *http.Request) { data := []map[string]any{} - shown := catalogFor(r) - if agent := agentOf(r); agent == "claude-desktop" { - data = desktopModels(shown, desktopKnowsMythos(r.Header.Get("User-Agent"))) - } else if agent == ScienceID { - data = scienceModels(shown) - } else { - labels := provider.Labels(shown) - // for another magpie: how it searches the web for each model - magpie := r.Header.Get(provider.DrawersHeader) != "" - searches := magpie && canSearch() - // for another magpie, what each model costs here, so its usage - // there is counted at the same price: told only to this computer - // and to one this magpie is shared with by a gateway key, as the - // prices are the user's own settings - // - // and to any client, OpenRouter's pricing for each model it knows - // a price of (cleary5779 on Discord: an agent built on magpie - // shows what a call costs), told to the same callers: the price is - // what the Usage page counts the model at, the user's own included. - // The settings, groups and providers are read once for the list - // (EntryPricer), not once a model - told := local(r) || sharedWith(r) - prices := told && r.Header.Get(provider.PricesHeader) != "" - var priceOf func(provider.Entry) (catalog.Price, bool) - if told { - priceOf = provider.EntryPricer(settings.Load(), provider.GroupFinder()) - } - // the tiers Codex here is offered on each model (#1234), for every - // client: another magpie offers them to its own Codex, and Cindy - // shows its Fast switch on a model whose tiers hold priority - // (#1914). A model with none says nothing - tiers := codexTiers(shown) - // each model by its bare id as well, after the provider/model ids, - // when the user asked for it (settings.BareModelIDs): a client - // moved from another proxy asks for gpt-5.6-sol (love1sbug on X). - // Never for another magpie, whose provider would list each twice. - // Each row is the entry the bare id reaches, its label that one's. - rows, ids := slices.Clip(shown), map[int]string{} - if !magpie && provider.BareModelIDs() { - labels = slices.Clip(labels) - for _, b := range provider.BareEntries(shown) { - ids[len(rows)] = b.ID - rows = append(rows, shown[b.Of]) - labels = append(labels, labels[b.Of]) + chat, images, videos, err := listKinds(r) + if err != nil { + writeError(w, provider.Chat, 400, err.Error()) + return + } + // its chat models, unless ?kind= asks for image or video models alone + if chat { + shown := catalogFor(r) + if agent := agentOf(r); agent == "claude-desktop" { + data = desktopModels(shown, desktopKnowsMythos(r.Header.Get("User-Agent"))) + } else if agent == ScienceID { + data = scienceModels(shown) + } else { + labels := provider.Labels(shown) + // for another magpie: how it searches the web for each model + magpie := r.Header.Get(provider.DrawersHeader) != "" + searches := magpie && canSearch() + // for another magpie, what each model costs here, so its usage + // there is counted at the same price: told only to this computer + // and to one this magpie is shared with by a gateway key, as the + // prices are the user's own settings + // + // and to any client, OpenRouter's pricing for each model it knows + // a price of (cleary5779 on Discord: an agent built on magpie + // shows what a call costs), told to the same callers: the price is + // what the Usage page counts the model at, the user's own included. + // The settings, groups and providers are read once for the list + // (EntryPricer), not once a model + told := local(r) || sharedWith(r) + prices := told && r.Header.Get(provider.PricesHeader) != "" + var priceOf func(provider.Entry) (catalog.Price, bool) + if told { + priceOf = provider.EntryPricer(settings.Load(), provider.GroupFinder()) } - } - for i, e := range rows { - m := modelObject(e) - toolsTold(m, e) - if id, ok := ids[i]; ok { - m["id"] = id - } - if magpie { - if how := webSearchOf(e, searches); how != "" { - m["web_search"] = how + // the tiers Codex here is offered on each model (#1234), for every + // client: another magpie offers them to its own Codex, and Cindy + // shows its Fast switch on a model whose tiers hold priority + // (#1914). A model with none says nothing + tiers := codexTiers(shown) + // each model by its bare id as well, after the provider/model ids, + // when the user asked for it (settings.BareModelIDs): a client + // moved from another proxy asks for gpt-5.6-sol (love1sbug on X). + // Never for another magpie, whose provider would list each twice. + // Each row is the entry the bare id reaches, its label that one's. + rows, ids := slices.Clip(shown), map[int]string{} + if !magpie && provider.BareModelIDs() { + labels = slices.Clip(labels) + for _, b := range provider.BareEntries(shown) { + ids[len(rows)] = b.ID + rows = append(rows, shown[b.Of]) + labels = append(labels, labels[b.Of]) } } - if ts := tiers[e.ID]; len(ts) > 0 { - m["service_tiers"] = ts - } - if told { - if pr, ok := priceOf(e); ok { - m["pricing"] = catalog.OpenRouterPricing(pr) - if prices { - m["magpie_price"] = pr + for i, e := range rows { + m := modelObject(e) + toolsTold(m, e) + if id, ok := ids[i]; ok { + m["id"] = id + } + if magpie { + if how := webSearchOf(e, searches); how != "" { + m["web_search"] = how } } + if ts := tiers[e.ID]; len(ts) > 0 { + m["service_tiers"] = ts + } + if told { + if pr, ok := priceOf(e); ok { + m["pricing"] = catalog.OpenRouterPricing(pr) + if prices { + m["magpie_price"] = pr + } + } + } + // for another magpie: its name as the agents' lists here call + // it, with its provider's after it unless the user wants it + // plain, so two providers' models of one name are told apart + // there as they are here + m["magpie_label"] = labels[i] + if agentOf(r) == "cursor-local" { + cursorLocalModel(m, e) + } + data = append(data, m) } - // for another magpie: its name as the agents' lists here call - // it, with its provider's after it unless the user wants it - // plain, so two providers' models of one name are told apart - // there as they are here - m["magpie_label"] = labels[i] - if agentOf(r) == "cursor-local" { - cursorLocalModel(m, e) - } - data = append(data, m) } } - if r.Header.Get(provider.DrawersHeader) != "" { + if images || r.Header.Get(provider.DrawersHeader) != "" { data = append(data, drawerObjects(r)...) } - if r.Header.Get(provider.VideomakersHeader) != "" { + if videos || r.Header.Get(provider.VideomakersHeader) != "" { data = append(data, videomakerObjects(r)...) } if r.Header.Get(provider.DecidersHeader) != "" { diff --git a/internal/gateway/models_kind_test.go b/internal/gateway/models_kind_test.go new file mode 100644 index 000000000..ad141d0f1 --- /dev/null +++ b/internal/gateway/models_kind_test.go @@ -0,0 +1,102 @@ +package gateway + +import ( + "encoding/json" + "net/http/httptest" + "slices" + "strings" + "testing" +) + +// axelburks on Discord asked why /v1/models lists no image or video models. +// An agent or client that offers every id this list gives in its chat +// picker would offer them to chat with, so they are listed only when the +// caller asks: ?kind=image,video (or all), each marked by its "kind". No +// agent's list, the plain one, Claude Desktop's, Claude Science's, +// Cursor's, OpenCode's or the ids of ?format=text, gains an image or a +// video model. +func TestModelsListMediaOnlyWhenAsked(t *testing.T) { + grokSignedIn(t) + newGrokMedia(t) + h := New().Handler() + const image, video = "grok/grok-imagine-image", "grok/grok-imagine-video" + get := func(path string, header map[string]string) (int, string) { + r := httptest.NewRequest("GET", path, nil) + for k, v := range header { + r.Header.Set(k, v) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w.Code, w.Body.String() + } + type row struct{ ID, Kind string } + list := func(path string, header map[string]string) []row { + t.Helper() + code, body := get(path, header) + if code != 200 { + t.Fatalf("%s %v: %d %s", path, header, code, body) + } + var l struct{ Data []row } + if err := json.Unmarshal([]byte(body), &l); err != nil { + t.Fatalf("%s %v: %s", path, header, body) + } + return l.Data + } + agents := map[string]map[string]string{ + "plain": nil, + "opencode": {"User-Agent": "opencode/1.2.3"}, + "cherry": {"User-Agent": "CherryStudio/1.5"}, + "claude-desktop": {"User-Agent": "Mozilla/5.0 (Macintosh) Claude/1.2.3 Chrome/130"}, + "science": {"X-Anthropic-Surface": "operon", "User-Agent": "Anthropic/JS 0.60.0"}, + "cursor": {"User-Agent": "Cursor-CLI/1.0"}, + "magpie-key": {"Authorization": "Bearer magpie-acme"}, + } + for name, header := range agents { + rows := list("/v1/models", header) + if len(rows) == 0 && name == "plain" { + t.Fatalf("plain list is empty") + } + for _, m := range rows { + if m.Kind == "image" || m.Kind == "video" || strings.Contains(m.ID, "imagine") { + t.Errorf("%s's chat list offers %s (%s)", name, m.ID, m.Kind) + } + } + if _, body := get("/v1/models?format=text", header); strings.Contains(body, "imagine") { + t.Errorf("%s's text list offers a media model:\n%s", name, body) + } + } + + kinds := func(rows []row) (chat, img, vid []string) { + for _, m := range rows { + switch m.Kind { + case "image": + img = append(img, m.ID) + case "video": + vid = append(vid, m.ID) + default: + chat = append(chat, m.ID) + } + } + return + } + if chat, img, vid := kinds(list("/v1/models?kind=image,video", nil)); len(chat) != 0 || !slices.Contains(img, image) || !slices.Contains(vid, video) { + t.Fatalf("kind=image,video: chat %v image %v video %v", chat, img, vid) + } + if chat, img, vid := kinds(list("/v1/models?kind=video", nil)); len(chat) != 0 || len(img) != 0 || !slices.Contains(vid, video) { + t.Fatalf("kind=video: chat %v image %v video %v", chat, img, vid) + } + if chat, img, vid := kinds(list("/v1/models?kind=chat&kind=Image", nil)); len(chat) == 0 || !slices.Contains(img, image) || len(vid) != 0 { + t.Fatalf("kind=chat&kind=Image: chat %v image %v video %v", chat, img, vid) + } + if chat, img, vid := kinds(list("/v1/models?kind=all", nil)); len(chat) == 0 || len(img) == 0 || len(vid) == 0 { + t.Fatalf("kind=all: chat %v image %v video %v", chat, img, vid) + } + if _, body := get("/v1/models?kind=image&format=text", nil); !strings.Contains(body, image) || strings.Contains(body, video) { + t.Fatalf("kind=image&format=text:\n%s", body) + } + for _, bad := range []string{"images", "embedding", "", "chat,"} { + if code, body := get("/v1/models?kind="+bad, nil); code != 400 { + t.Errorf("kind=%q: %d %s", bad, code, body) + } + } +} diff --git a/site/public/docs/integrate.html b/site/public/docs/integrate.html index b94bb3a2f..659f9ea33 100644 --- a/site/public/docs/integrate.html +++ b/site/public/docs/integrate.html @@ -120,7 +120,7 @@ curl -s http://127.0.0.1:3425/v1/models -H "Authorization: Bearer magpie-acme"On this machine the gateway takes any key. Send magpie-<your-app-id> (Authorization: Bearer magpie-acme, or x-api-key) and every call is counted as acme in Usage, the Requests log and the routing rules that match on agents. Without it, magpie counts the call by the first word of your User-Agent (Acme/1.4 (darwin) is Acme); an SDK’s own User-Agent (OpenAI/JS …, ai-sdk/…) would count it as that SDK. From another computer (Settings → Share on local network) the key must be one of the user’s gateway keys, and the User-Agent names your app.

Models

-

GET /v1/models lists what the user has turned on: id (provider/model, or a routing group’s name, sent as it is), display_name, owned_by (the provider), reasoning and supported_reasoning_levels ([{"effort":"low"},…], and the same as plain names in reasoning_levels), context_window and max_output_tokens when known, and modalities when magpie knows whether it takes images. List them from there rather than shipping a list: the user adds and removes providers in magpie. Reasoning is asked in your API’s own field (reasoning_effort, reasoning.effort, Anthropic’s thinking or output_config.effort). ?format=text gives the ids one a line.

+

GET /v1/models lists what the user has turned on: id (provider/model, or a routing group’s name, sent as it is), display_name, owned_by (the provider), reasoning and supported_reasoning_levels ([{"effort":"low"},…], and the same as plain names in reasoning_levels), context_window and max_output_tokens when known, and modalities when magpie knows whether it takes images. List them from there rather than shipping a list: the user adds and removes providers in magpie. Reasoning is asked in your API’s own field (reasoning_effort, reasoning.effort, Anthropic’s thinking or output_config.effort). ?format=text gives the ids one a line. The list holds chat models alone: ask for image and video models with ?kind=image,video (or ?kind=all). Each is marked "kind": "image" or "video" and is made on /v1/images/generations or /v1/videos, not a chat route.

Optional

Send X-Magpie-Session: <id> with a conversation’s requests and GET /v1/magpie/route?session=<id> says which model a routing group picked for the turn and the fallbacks it tried, before the first token (long-poll with after=<seq>&wait=<s>). GET /v1/magpie/quotas lists the user’s subscription allowances, and GET /v1/magpie/usage and /v1/magpie/usage/requests the Usage page’s numbers and its requests (with session, and subagent/parent_agent for a Claude Code subagent’s call). They answer only this machine, or another with a gateway key; a key held to a budget, models or accounts sees its own calls and routes alone, and is refused the quotas unless its owner lets it see those of what it may use (magpie gateway-key quotas <id> on; its own limit is GET /v1/magpie/limit). Calls your app makes to its vendor itself can be reported with POST /v1/magpie/usage/requests (one record or up to 5000 a post, in usage.jsonl’s shape, each with a rid; past times are kept, so a history can be backfilled). They show on the Usage page as reported, and never count against a key’s limit. The reference has the details.

diff --git a/site/public/docs/zh/integrate.html b/site/public/docs/zh/integrate.html index a08889fc4..9b7fe1a73 100644 --- a/site/public/docs/zh/integrate.html +++ b/site/public/docs/zh/integrate.html @@ -120,7 +120,7 @@ curl -s http://127.0.0.1:3425/v1/models -H "Authorization: Bearer magpie-acme"在本机,网关接受任意 key。发送 magpie-<你的应用 id>(Authorization: Bearer magpie-acme,或 x-api-key),每次调用都会在用量、请求记录以及按 Agent 匹配的路由规则里记为 acme。不带它时,magpie 按 User-Agent 的第一个词统计(Acme/1.4 (darwin) 记为 Acme);SDK 自带的 User-Agent(OpenAI/JS …、ai-sdk/…)会被记成那个 SDK。从另一台电脑访问时(设置 → 局域网共享),key 必须是用户的网关密钥之一,应用名就靠 User-Agent。

模型

-

GET /v1/models 列出用户打开的模型:id(provider/model,或路由组的名字,原样发送即可)、display_name、owned_by(供应商)、reasoning 与 supported_reasoning_levels([{"effort":"low"},…];同样的档位以纯名字列在 reasoning_levels),已知时还有 context_window、max_output_tokens,以及 magpie 知道是否支持图片时的 modalities。请从这里读取,而不是内置一份列表:用户会在 magpie 里增删供应商。推理强度用你所用 API 自己的字段传(reasoning_effort、reasoning.effort、Anthropic 的 thinking 或 output_config.effort)。?format=text 每行一个 id。

+

GET /v1/models 列出用户打开的模型:id(provider/model,或路由组的名字,原样发送即可)、display_name、owned_by(供应商)、reasoning 与 supported_reasoning_levels([{"effort":"low"},…];同样的档位以纯名字列在 reasoning_levels),已知时还有 context_window、max_output_tokens,以及 magpie 知道是否支持图片时的 modalities。请从这里读取,而不是内置一份列表:用户会在 magpie 里增删供应商。推理强度用你所用 API 自己的字段传(reasoning_effort、reasoning.effort、Anthropic 的 thinking 或 output_config.effort)。?format=text 每行一个 id。列表只有对话模型:要图像和视频模型,请加 ?kind=image,video(或 ?kind=all),它们带 "kind": "image" 或 "video",在 /v1/images/generations 或 /v1/videos 上生成,不走对话接口。

可选

在同一会话的请求里带上 X-Magpie-Session: <id>,GET /v1/magpie/route?session=<id> 就能在第一个 token 之前告诉你路由组为这一轮选了哪个模型、尝试过哪些后备(用 after=<seq>&wait=<s> 长轮询)。GET /v1/magpie/quotas 列出用户各订阅的额度,GET /v1/magpie/usage 和 /v1/magpie/usage/requests 给出用量页的统计和逐条请求(带 session;Claude Code 子代理的调用还有 subagent/parent_agent)。它们只回答本机,或带网关密钥的其他机器;限了额度、模型或账号的密钥只看得到自己的调用和路由,额度不告诉它,除非它的主人允许它看自己可用部分的额度(magpie gateway-key quotas <id> on;它自己的限额见 GET /v1/magpie/limit)。你的应用直接发给厂商、不经过 magpie 的调用,可以用 POST /v1/magpie/usage/requests 上报(每次一条,或最多 5000 条,格式同 usage.jsonl 的一行,每条带 rid;过去的时间照原样保留,所以可以补录历史)。它们在用量页上标为上报,且从不计入密钥的限额。细节见参考文档。