diff --git a/docs/reference.md b/docs/reference.md index 83cd6dfc7..b15f78f07 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -955,7 +955,11 @@ on the site's Plugins page, under Agent plugins. A call is counted at its **effective price**: what you set for that provider and model if you did, otherwise what the provider's own catalogue lists, and -otherwise what models.dev lists for the model's maker. Out of the box that +otherwise what models.dev lists for the model's maker. A provider you added by +its address, with no catalogue named, has for its own the one models.dev +lists at that address (its `api`), when exactly one does and it isn't a +plan's: a provider at `https://developer.amd.com.cn/radeon/api/v1` is priced +from models.dev's `amd`, whatever you called it. Out of the box that last one is the whole story, and it is the wrong number for any provider that does not charge list price — a relay reselling at a discount or a multiplier is counted at whatever the model's maker charges. Say what a provider @@ -979,6 +983,9 @@ relay that sells `kimi-k3` as `moonshot-kimi-k3` answers as `kimi-k3`, so its calls are counted at `relay-a/kimi-k3`'s price. A model with a price of its own, `0` included, keeps it whatever its reply says. +`magpie model price provider/model` says where a price came from, and for a +model with none, the two commands that give it one. + A call with no price at all is left out of a total's cost, never counted as free: the Usage page's sum says how many calls it couldn't price beside it ("≈$1.20+", then "3 calls unpriced"; Sessions, which prices by model, says how diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index cc5c02fc5..8a323f025 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -39,6 +39,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it. A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). Each key of a remote-magpie provider also gets a card of its own, under `/~keys`, one section per key (#1547, `remoteKeyCards` in `remote_key_limits.go`): the gateway key's limit as that magpie holds it, read from `GET /v1/magpie/limit` asked with that key alone, so a key never sees another's numbers. It shows a window per cap (tokens, spend) named for the period, used against the cap, with its reset, plus `GatewayKey` (what is left, calls, a cycle of days, used up); a key held to no limit shows `Unlimited`. It is kept for `remoteCardsFor` like the remote's cards and read again by the card's refresh (`?provider=/~keys&user=`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). A remote that holds the key to a budget, models or accounts answers its cards 403 `gateway_key_held` (#1981, `errKeyHeld`): the cards kept from before are dropped and only the key's own card shows. A remote's cards are kept by provider and key (`remoteCardsID`), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (`keepRemoteCards`). Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → *Allowance reads* at *When I ask* (`QuotaReads == "asked"`, #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page or the tray panel's Allowances opened (no more than once in 30s, `quotasOpened`, #1588) or refreshed (`?asked=1`), a card's refresh (`RefreshUsage`), `magpie quota`, `magpie accounts`, `magpie quota wait` and the TUI's quotas (`Asked`). Any other read (`quotaReading` → `holdUnasked`) carries `netproxy.Hold`, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (`errNotAsked`): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (`StaleAllowance` → `markStaleRead`) or a key refused (`StaleKeyAllowance` → `refused`) is still read, once (`unheld`). Warm-up and check-in are not reads and are unchanged. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`quota_asked.go`](../../internal/provider/quota_asked.go) | | A remote magpie's prices | A local magpie asks a remote magpie's `/v1/models` with `X-Magpie-Prices` (`PricesHeader`, sent by `listHeaders`). The remote answers each model's `magpie_price`: what its own Usage page counts the model at (`EntryPriceIn`: the price its user set, else its provider's list price at its price rate; a routing group only when every member costs the same). It tells it only to a request from its own computer or one let in with a gateway key (`local` or `sharedWith`); a list that didn't ask gets no prices (a remote request without a valid key never reaches the list: `lanGuard` refuses it). The local keeps the price with the fetched list (`catalog.Model.Price`; a value that isn't a price, or has a negative part, is dropped, the model kept) and uses it as that provider's list price (`ListPrice` → `remotePrice`). A price the local user set (`provider/model`, `provider/*`, `*/model`) still comes first, and the local provider's own price rate still applies on top. A remote from before this sends no field and the models stay priced as before; an older local sends no header and is sent nothing new. The model editor says the greyed price is the other magpie's (`remoteList`). | [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`models.go`](../../internal/provider/models.go), [`gateway.go`](../../internal/gateway/gateway.go) (`models`), [`live.go`](../../internal/catalog/live.go) | | A remote magpie's service tiers | A remote magpie's `/v1/models` gives each model the `service_tiers` its own Codex is offered on it (`codexTiers` → `codexcat.ServiceTiers`, from the same `CodexCatalog` and `codexcat.Entries` as its `/v1/codex/models`: Fast on a ChatGPT account's GPT model, the tiers of Codex's own entry on a relay's, none on a model it offers none). The local keeps the ids (`catalog.Model.Tiers` → `Entry.Tiers`), `codexListed` hands them on for the remote's models, and `codexcat.Entries` offers them to the local Codex with Codex's own names (`namedTiers`). The gateway sends the tier Codex asks for to a remote magpie as it was asked (`Request.OwnTier`, as for a provider added by its address; dropped and not sent again if refused), and the remote serves it as its own Codex's turn (#1234). A remote from before this sends no tiers, and its models are offered none, as before. The list gives every client the tiers, not only a magpie asking with `X-Magpie-Drawers`: Cindy shows its Fast switch on a model whose `service_tiers` hold `priority` (#1914, `TestModelsListTiersForEveryClient`). | [`codexcat.go`](../../internal/codexcat/codexcat.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`gateway.go`](../../internal/gateway/gateway.go), [`live.go`](../../internal/catalog/live.go) | +| An endpoint's catalog | A key's provider with no catalog of its own (none named, none from a preset) is priced from the models.dev catalog whose `api` is one of its endpoints (`EndpointCatalog`, `catalog.AtEndpoint`; a trailing slash and case don't count, and an Anthropic base, kept as its root, is also matched with its `/v1`). Only when exactly one catalog is at that address, and it isn't a plan's (an id with `-plan`, or a `membershipCatalogs` one): a plan lists its membership's $0, and two catalogs at one address can't be told apart. A subscription's account never gets one. A provider at AMD's own endpoint is priced from `amd`, which lists Qwen3.8-27B at $0, a price, where its maker sells no such model and it had none (#2052); a relay's endpoint matches nothing and its model stays unpriced, never priced at a reseller's guess. `magpie model price` names the catalog, and says how to give a price when none is known. | [`models.go`](../../internal/provider/models.go), [`catalog.go`](../../internal/catalog/catalog.go) | | A membership's $0 catalog | models.dev lists every model of Kimi Code's plans (`kimi-code-plan-global`, `kimi-code-plan-cn`) and of Xiaomi MiMo's Token Plans (`xiaomi-token-plan-cn`, `-sgp`, `-ams`) at $0: what the membership charges per token, not what the model costs. `membershipCatalogs` are never read for a price (`priceCatalogs`, `makerPriceCatalogs`), so a Xiaomi MiMo model is priced at `xiaomi`'s list price at every region, and each region of the preset names its own catalog, pay as you go `xiaomi` alone (#1873). A Kimi Code provider's model is priced at the Kimi API model it is (`kimiCodeAPI`, from Kimi Code's docs: k3 and k3-256k are kimi-k3, kimi-for-coding-highspeed is kimi-k2.7-code-highspeed), and kimi-for-coding (K2.8 Preview, not on the API) is unpriced rather than free (#1370). The alias is Kimi Code's alone (`kimiCodePlans`): a relay's own `k3` keeps its own price. A catalog other than these that lists a model at $0 still prices it at $0: models.dev has truly free models (nvidia, modelscope). The Requests list names the API model it was priced as (`PricedNameFor`). | [`models.go`](../../internal/provider/models.go) | | A key's own windows | A sub2api key given a spending limit per 5 hours, day or 7 days answers its `/v1/usage` with `rate_limits` and no `remaining` (`readSub2APIKeyLimits`). With the Balance URL set to it, the key's card shows them as the windows *5 hours*, *1 day*, *7 days*, in USD, beside a balance field the user wrote; *Check balance* and `magpie provider show` give what its fullest window has left (`Balance`). `KeyAllowance` gives routing the same windows: never waited for, read in the background at most once a minute, a failed read keeping the last, and seeded from the card's last reading (`quotas.json`) after a restart. A key bought as a plan (Kimi Code, GLM Coding Plan and Z.ai, MiniMax Coding Plan, OpenCode Go, Command Code, Ollama Cloud: `planQuotaSourceOf`) gives routing its card's windows the same way (`planKeyWindows`, Zhipu's team quota behind a key with none of its own); the Usage page's read of its card is taken at once (`noteKeyAllowance`), and a key there that turns out pay-as-you-go, with no windows, is asked again only every 30 minutes (`keyNoWindowsAge`). Ollama Cloud's `ollama.com/api/balance` (#1888, `readOllamaPlan`) tells the plan's included allowance as one window in USD, *Month* when its period is a month long, renewing at `period.until`, and Aside while credits bought on top are left; those credits are the key's balance card (`readOllamaCredits`), and a reply that names none has no balance card rather than $0. StepFun's Step Plan is read through a sign-in, not the key, and isn't one of them. Nor are Volcengine Ark's Coding Plan and Agent Plan (#1427): their 5-hour, weekly and monthly windows are told only to the account's access key (`AccessKeyID`, `SecretAccessKey`), asked of `open.volcengineapi.com` (`GetCodingPlanUsage`, `GetAFPUsage`) and signed as Volcengine's own SDK signs (`volcSign`), so they are cards on the Usage page (`volcPlanQuotas` in `PlanQuotas`), never routing's windows. Nor is Tencent Cloud's Token Plan 企业版 (#1574): what a team plan has used of its cycle's credits (专业套餐) or tokens (轻享套餐) is told only to the account's SecretId and SecretKey (kept as `AccessKeyID`, `SecretAccessKey`), asked of `tokenhub.tencentcloudapi.com` (`DescribeTokenPlanList`, `DescribeTokenPlan`, version 2026-03-22) and signed TC3-HMAC-SHA256 (`tc3Sign`), one card per team plan (`tencentPlanQuotas`). | [`sub2api_usage.go`](../../internal/provider/sub2api_usage.go), [`key_allowance.go`](../../internal/provider/key_allowance.go), [`volcengine_usage.go`](../../internal/provider/volcengine_usage.go), [`tencent_usage.go`](../../internal/provider/tencent_usage.go) | | Account names and seats | `AccountNames` (by the account, in lower case, like `AccountCaps`) are names the user gives accounts, set by `SetAccountName` (GUI `provider/accountname`, `magpie accounts alias`); they live in providers.json only, never in a vendor's or plugin's sign-in. A GLM Coding Plan read with a key (`glmPlan`) and a ZCode account (built-in or `zcode-plugin`) whose windows' resets agree are one seat (`seatMatch`, #90/#953), shown once, on the account's card (`seatCards`, used by `quotas`, `Allotted` and `CachedCards`). A match is remembered in `seats.json` beside `quotas.json`: a failed read or a window with no reset yet is unknown and keeps the key's card off while the account is signed in; windows that disagree forget it (#1515). Cards carry `Seat` (the key provider's name, and the key's when it has several) and `Alias` (the user's name, else `Seat`), as `/v1/magpie/quotas`, `magpie quota` and `magpie accounts` do. | [`account_names.go`](../../internal/provider/account_names.go), [`account_seats.go`](../../internal/provider/account_seats.go) | diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go index a5b8a2e34..388ca5cfd 100644 --- a/internal/catalog/catalog.go +++ b/internal/catalog/catalog.go @@ -278,9 +278,12 @@ func (p Price) CostSplit(input, output, cacheRead, cacheWrite, cacheWrite1h int) } type mdProvider struct { - ID string `json:"id"` - Name string `json:"name"` - Env []string `json:"env"` + ID string `json:"id"` + Name string `json:"name"` + Env []string `json:"env"` + // API is the base URL models.dev says the provider serves its models + // at (AMD's https://developer.amd.com.cn/radeon/api/v1) + API string `json:"api"` Models map[string]mdModel `json:"models"` } @@ -1341,6 +1344,28 @@ func Drawers(id string) []Model { return out } +// AtEndpoint are the models.dev providers whose models are served at base +// (their "api"), in order: the catalog of a provider the user added by its +// endpoint alone. A trailing slash and the case of the address don't count. +func AtEndpoint(base string) []string { + want := endpointKey(base) + if want == "" { + return nil + } + var ids []string + for id, p := range load() { + if endpointKey(p.API) == want { + ids = append(ids, id) + } + } + slices.Sort(ids) + return ids +} + +func endpointKey(u string) string { + return strings.ToLower(strings.TrimRight(strings.TrimSpace(u), "/")) +} + // Providers returns models.dev provider ids known to the catalog. func Providers() []string { var ids []string diff --git a/internal/cli/model_cli.go b/internal/cli/model_cli.go index f70eda7e7..d9872a431 100644 --- a/internal/cli/model_cli.go +++ b/internal/cli/model_cli.go @@ -300,7 +300,13 @@ func modelPrice(args []string) error { if len(rest) == 0 { pr, ok := provider.EffectivePrice(p.ID, model) if !ok { + // a call to it counts at no cost until one is given: say how + // (#2052) fmt.Println(muted.Render(id), faint.Render("· no price is known for it")) + fmt.Println(faint.Render(" · magpie model price " + typedRef(id) + + " ,,, sets it, in USD per 1M tokens")) + fmt.Println(faint.Render(" · magpie model price " + typedRef(provider.AnyPriceKey(model)) + + " ,,, sets it from every provider")) return nil } fmt.Println(bold.Render(perMillion(pr)), muted.Render("· "+id)) @@ -322,6 +328,8 @@ func modelPrice(args []string) error { from := "what its provider lists, else its maker's on models.dev" if p.RemotePriced(model) { from = "what the other magpie counts it at" + } else if c := p.EndpointCatalog(); c != "" { + from = "what models.dev's " + c + " lists at its endpoint, else its maker's" } fmt.Println(faint.Render(" · " + from + " · magpie model price " + typedRef(id) + " ,,, to change it")) diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 2d777aa2a..47d44bf39 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -9037,7 +9037,7 @@ function drawEditor(p, presetID) { inner.append(...field(t("Models URL"), mu, t("Where the vendor lists its models, when that isn't under the base URL; asked with the key"))); const cat = input(draft.catalog, t("models.dev ids, e.g. openai, deepseek")); cat.oninput = () => { draft.catalog = cat.value; }; - inner.append(...field(t("Catalog"), cat, t("Display names and reasoning levels for the models; for a gateway that serves several vendors, list them all, first match wins"))); + inner.append(...field(t("Catalog"), cat, t("Display names, reasoning levels and list prices for the models; for a gateway that serves several vendors, list them all, first match wins"))); const bal = input(draft.balanceURL, "https://…/api/usage/token", "url"); bal.classList.add("bal-url"); bal.oninput = () => { draft.balanceURL = bal.value; balPath.placeholder = balanceFieldOf(bal.value); }; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 307699466..ba71cbaaf 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1754,7 +1754,7 @@ const I18N = { "Gemini generateContent — what the Gemini CLI speaks": "Gemini generateContent — Gemini CLI 使用", "models.dev ids, e.g. openai, deepseek": "models.dev 上的 ID,例如 openai, deepseek", "Catalog": "目录", - "Display names and reasoning levels for the models; for a gateway that serves several vendors, list them all, first match wins": "模型的显示名称与推理等级;网关提供多家厂商的模型时全部列出,先匹配者优先", + "Display names, reasoning levels and list prices for the models; for a gateway that serves several vendors, list them all, first match wins": "模型的显示名称、推理等级与官方价格;网关提供多家厂商的模型时全部列出,先匹配者优先", "Balance URL": "余额查询地址", "Models URL": "模型列表地址", "Where the vendor lists its models, when that isn't under the base URL; asked with the key": "供应商的模型列表接口,不在基础地址下时填写;请求时会带上 Key", @@ -6485,7 +6485,7 @@ const I18N = { "Gemini generateContent — what the Gemini CLI speaks": "Gemini generateContent — Gemini CLI 使用", "models.dev ids, e.g. openai, deepseek": "models.dev 上的 ID,例如 openai, deepseek", "Catalog": "目錄", - "Display names and reasoning levels for the models; for a gateway that serves several vendors, list them all, first match wins": "模型的顯示名稱與推理等級;閘道提供多家廠商的模型時全部列出,先匹配者優先", + "Display names, reasoning levels and list prices for the models; for a gateway that serves several vendors, list them all, first match wins": "模型的顯示名稱、推理等級與官方價格;閘道提供多家廠商的模型時全部列出,先匹配者優先", "Balance URL": "餘額查詢位址", "Models URL": "模型列表位址", "Where the vendor lists its models, when that isn't under the base URL; asked with the key": "供應商的模型列表介面,不在基礎位址下時填寫;請求時會帶上 Key", @@ -11190,7 +11190,7 @@ const I18N = { "Gemini generateContent — what the Gemini CLI speaks": "Gemini generateContent — Gemini CLI が使う形式", "models.dev ids, e.g. openai, deepseek": "models.dev の ID、例:openai, deepseek", "Catalog": "カタログ", - "Display names and reasoning levels for the models; for a gateway that serves several vendors, list them all, first match wins": "モデルの表示名と推論レベル。複数ベンダーを提供するゲートウェイではすべて列挙し、最初に一致したものが使われます", + "Display names, reasoning levels and list prices for the models; for a gateway that serves several vendors, list them all, first match wins": "モデルの表示名、推論レベル、公式価格。複数ベンダーを提供するゲートウェイではすべて列挙し、最初に一致したものが使われます", "Balance URL": "残高 URL", "Models URL": "モデル URL", "Where the vendor lists its models, when that isn't under the base URL; asked with the key": "ベース URL の下にない場合の、ベンダーがモデル一覧を返す場所。キー付きで問い合わせます", @@ -15915,7 +15915,7 @@ const I18N = { "Gemini generateContent — what the Gemini CLI speaks": "Gemini generateContent — spricht die Gemini CLI", "models.dev ids, e.g. openai, deepseek": "models.dev-IDs, z. B. openai, deepseek", "Catalog": "Katalog", - "Display names and reasoning levels for the models; for a gateway that serves several vendors, list them all, first match wins": "Anzeigenamen und Reasoning-Stufen der Modelle; bei einem Zugangspunkt, der Modelle mehrerer Anbieter bereitstellt, alle auflisten, der erste Treffer gilt", + "Display names, reasoning levels and list prices for the models; for a gateway that serves several vendors, list them all, first match wins": "Anzeigenamen, Reasoning-Stufen und Listenpreise der Modelle; bei einem Zugangspunkt, der Modelle mehrerer Anbieter bereitstellt, alle auflisten, der erste Treffer gilt", "Balance URL": "Guthaben-URL", "Models URL": "Modelllisten-URL", "Where the vendor lists its models, when that isn't under the base URL; asked with the key": "Wo der Anbieter seine Modelle auflistet, falls nicht unter der Basis-URL; wird mit dem Schlüssel abgefragt", diff --git a/internal/gui/tests/catalog-hint.test.cjs b/internal/gui/tests/catalog-hint.test.cjs new file mode 100644 index 000000000..1ee7e6032 --- /dev/null +++ b/internal/gui/tests/catalog-hint.test.cjs @@ -0,0 +1,82 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A custom provider's Catalog field says it decides the models' list prices +// too, not only their names and reasoning levels (#2052, mengyianx: a +// provider at AMD's own endpoint had no price, and the field's hint gave no +// sign that naming models.dev's amd there would price it). In every +// language, at a wide and a narrow window, the hint is the Catalog box's +// description and fits the 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"); +const amd = { + id: "002", name: "002", icon: "", preset: "", host: "developer.amd.com.cn", chat: "https://developer.amd.com.cn/radeon/api/v1", + responses: "", anthropic: "", catalog: "", website: "", keysUrl: "", proxy: "", balanceToken: { takes: false, set: false }, + key: { set: true, masked: "sk-…abcd" }, ready: true, chosen: [], fallback: [], routing: "", affinity: "", + models: [{ id: "Qwen3.8-27B", name: "Qwen3.8 27B", efforts: ["low", "medium"], images: false, on: true, list: { input: 0, output: 0, cache_read: 0, cache_write: 0 } }], + exposed: 1, unlisted: false, off: false, fetched: "just now", agents: [], sponsored: false, keyList: [], +}; +const providers = { providers: [amd], presets: [], excluded: [], gateway: { running: true, window: true } }; + +function serve(lang) { + const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; + 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:"${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/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const words = { + en: { more: "More endpoints", prices: "list prices" }, + zh: { more: "更多端点", prices: "官方价格" }, + "zh-TW": { more: "更多端點", prices: "官方價格" }, + ja: { more: "その他のエンドポイント", prices: "公式価格" }, + de: { more: "Weitere Endpunkte", prices: "Listenpreise" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + for (const width of [1100, 420]) { + const w = words[lang]; + test(`${engine} ${lang} ${width}: the Catalog field says it sets list prices`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + await page.goto("http://magpie.test/?view=providers"); + await page.locator(".row.provider", { has: page.locator(".name", { hasText: /^002$/ }) }).click(); + const ed = page.locator(".editor"); + await ed.waitFor(); + const more = ed.locator("details.more"); + await more.locator("summary", { hasText: w.more }).click(); + const hint = more.locator(".hint", { hasText: w.prices }); + assert.equal(await hint.count(), 1, "one hint names list prices"); + await hint.scrollIntoViewIfNeeded(); + assert.ok(await hint.isVisible(), "the hint is shown"); + // it describes the Catalog box + const id = await hint.getAttribute("id"); + const box = more.locator(`input[aria-describedby~="${id}"]`); + assert.equal(await box.count(), 1, "the hint describes one box"); + assert.match(await box.getAttribute("placeholder"), /models\.dev/); + const b = await hint.boundingBox(); + assert.ok(b.x >= 0 && b.x + b.width <= width + 0.5, `the hint fits the window: ${b.x}+${b.width} at ${width}`); + assert.deepEqual(errors, [], "nothing throws"); + }); + } + } +} diff --git a/internal/provider/endpoint_price_test.go b/internal/provider/endpoint_price_test.go new file mode 100644 index 000000000..0013e82ed --- /dev/null +++ b/internal/provider/endpoint_price_test.go @@ -0,0 +1,134 @@ +package provider + +import ( + "os" + "path/filepath" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/settings" +) + +// useEndpointCatalog puts testdata/endpoint_catalog.json in the catalog +// cache: models.dev's amd (2026-10-14, as #2052's reporter read it), whose +// "api" is AMD Radeon Cloud's endpoint and which lists Qwen3.8-27B at $0; +// alibaba, its maker, which sells no qwen3.8-27b; alibaba-coding-plan, a +// plan listing qwen3.5-plus at $0; minimax and minimax-coding-plan, which +// share one "api"; thinkingmachines, alone at an Anthropic API's; and +// openai's gpt-5.5. Id, name, api, cost and canonical +// id of each, as models.dev lists them. +func useEndpointCatalog(t *testing.T) { + t.Helper() + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + b, err := os.ReadFile(filepath.Join("testdata", "endpoint_catalog.json")) + if err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(catalog.CachePath(), b, 0o600); err != nil { + t.Fatal(err) + } + catalog.Reset() + t.Cleanup(catalog.Reset) +} + +const amdEndpoint = "https://developer.amd.com.cn/radeon/api/v1" + +// #2052 (mengyianx): a custom provider at a vendor's own endpoint is priced +// from the catalog models.dev lists at that endpoint, whatever the provider +// is called: Qwen3.8-27B at AMD's is $0, a price, where its maker sells no +// such model and it read as no price at all. +func TestEndpointCatalogPrices(t *testing.T) { + useEndpointCatalog(t) + for _, c := range []struct{ id, chat string }{ + {"002", amdEndpoint}, {"amd", amdEndpoint}, {"001", amdEndpoint}, + // as pasted: a trailing slash, another case + {"002", amdEndpoint + "/"}, {"002", "https://Developer.AMD.com.cn/radeon/api/v1"}, + } { + p := normalize(Provider{ID: c.id, Name: c.id, Key: "k", Chat: c.chat}) + if got := p.EndpointCatalog(); got != "amd" { + t.Errorf("%s at %s: EndpointCatalog() = %q, want amd", c.id, c.chat, got) + } + if pr, ok := p.ListPrice("Qwen3.8-27B"); !ok || !pr.Same(catalog.Price{}) { + t.Errorf("%s at %s: ListPrice(Qwen3.8-27B) = %+v %v, want $0, priced", c.id, c.chat, pr, ok) + } + // a model the endpoint prices, at its price there + want := catalog.Price{Input: 0.14, Output: 0.28, CacheRead: 0.0028} + if pr, ok := p.ListPrice("DeepSeek-V4.1-Flash"); !ok || !pr.Same(want) { + t.Errorf("%s at %s: ListPrice(DeepSeek-V4.1-Flash) = %+v %v, want %+v", c.id, c.chat, pr, ok, want) + } + } + + // an Anthropic API's: magpie keeps its base as its root, models.dev + // writes it with its /v1 + tm := normalize(Provider{ID: "tm", Key: "k", Anthropic: "https://tinker.thinkingmachines.dev/services/tinker-prod/anthropic/api/v1"}) + inkling := catalog.Price{Input: 1.87, Output: 4.68, CacheRead: 0.374} + if pr, ok := tm.ListPrice("thinkingmachines/Inkling"); tm.EndpointCatalog() != "thinkingmachines" || !ok || !pr.Same(inkling) { + t.Errorf("at an Anthropic endpoint: %q, %+v %v, want thinkingmachines at %+v", tm.EndpointCatalog(), pr, ok, inkling) + } + + // what `magpie model price 002/Qwen3.8-27B` and the Usage page read + if err := Save(normalize(Provider{ID: "002", Name: "002", Key: "k", Chat: amdEndpoint})); err != nil { + t.Fatal(err) + } + if pr, ok := EffectivePrice("002", "Qwen3.8-27B"); !ok || !pr.Same(catalog.Price{}) { + t.Errorf("EffectivePrice(002, Qwen3.8-27B) = %+v %v, want $0, priced", pr, ok) + } + // the user's own price still comes first + user := catalog.Price{Input: 0.3, Output: 1.2, CacheRead: 0.05, CacheWrite: 0.2} + s := settings.Settings{ModelPrices: map[string]settings.ModelPrice{ + "002/Qwen3.8-27B": {Input: &user.Input, Output: &user.Output, CacheRead: &user.CacheRead, CacheWrite: &user.CacheWrite}}} + if pr, ok := EffectivePriceIn(s, "002", "Qwen3.8-27B"); !ok || !pr.Same(user) { + t.Errorf("with the user's price: %+v %v, want %+v", pr, ok, user) + } +} + +// #2052: where models.dev names no single catalog for the endpoint, or the +// user named one, nothing changes: a relay's model its maker doesn't sell +// stays unpriced, never priced at a reseller's guess. +func TestEndpointCatalogOnlyItsOwn(t *testing.T) { + useEndpointCatalog(t) + qwen35 := catalog.Price{Input: 0.4, Output: 2.4} + gpt := catalog.Price{Input: 5, Output: 30, CacheRead: 0.5} + minimax := catalog.Price{Input: 0.3, Output: 1.2, CacheRead: 0.06} + for _, c := range []struct { + name string + p Provider + model string + want *catalog.Price // nil: no price + }{ + {"a relay's endpoint", Provider{ID: "001", Key: "k", Chat: "https://relay.example.com/v1"}, "Qwen3.8-27B", nil}, + {"a relay's endpoint, a model its maker sells", Provider{ID: "001", Key: "k", Chat: "https://relay.example.com/v1"}, "gpt-5.5", &gpt}, + // the user's catalog stands: alibaba has no qwen3.8-27b + {"a catalog the user named", Provider{ID: "002", Key: "k", Chat: amdEndpoint, Catalog: "alibaba"}, "Qwen3.8-27B", nil}, + // a plan's $0 is its membership's, not the model's: its maker's + {"a plan's endpoint", Provider{ID: "cp", Key: "k", Chat: "https://coding-intl.dashscope.aliyuncs.com/v1"}, "qwen3.5-plus", &qwen35}, + // two catalogs at one endpoint, the plan's $0 among them: which + // one isn't known, so its maker's (an Anthropic base is kept as its + // root, models.dev's has its /v1) + {"an endpoint two catalogs share", Provider{ID: "mm", Key: "k", Anthropic: "https://api.minimax.io/anthropic/v1"}, "MiniMax-M3", &minimax}, + // a subscription's account is priced as its own code says + {"a subscription's account", Provider{ID: "sub", Chat: amdEndpoint, Account: &Account{Agent: "codex", User: "u"}}, "Qwen3.8-27B", nil}, + } { + p := normalize(c.p) + if c.name != "a catalog the user named" && p.EndpointCatalog() != "" { + t.Errorf("%s: EndpointCatalog() = %q, want none", c.name, p.EndpointCatalog()) + } + pr, ok := p.ListPrice(c.model) + if !ok { + pr, ok = MakerPrice(c.model) + } + switch { + case c.want == nil && ok: + t.Errorf("%s: %s priced at %+v, want no price", c.name, c.model, pr) + case c.want != nil && (!ok || !pr.At(0).Same(*c.want)): + t.Errorf("%s: %s = %+v %v, want %+v", c.name, c.model, pr, ok, *c.want) + } + } +} diff --git a/internal/provider/models.go b/internal/provider/models.go index 3a89f554c..caac4a236 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -1593,8 +1593,12 @@ func (p Provider) ListPrice(model string) (catalog.Price, bool) { names = append(names, id) } } + cats := p.Catalogs() + if c := p.EndpointCatalog(); c != "" { + cats = []string{c} + } for _, m := range names { - if pr, ok := catalog.PricedBy(priceCatalogs(p.Catalogs()), m); ok { + if pr, ok := catalog.PricedBy(priceCatalogs(cats), m); ok { return pr, true } if pr, ok := catalog.PricedBy(makerPriceCatalogs(), m); ok { @@ -1604,6 +1608,40 @@ func (p Provider) ListPrice(model string) (catalog.Price, bool) { return catalog.Price{}, false } +// EndpointCatalog is the models.dev catalog a provider the user added by +// its endpoint alone is priced from: the one models.dev says serves its +// models at that address, when exactly one does (#2052, mengyianx: a +// provider at AMD's own https://developer.amd.com.cn/radeon/api/v1 had no +// price for Qwen3.8-27B, which models.dev's amd lists at $0 there, while +// its maker sells no such model). Only a key's provider with no catalog +// named counts: a catalog the user or a preset gave stands, and a +// subscription's account is priced as its own code says. A plan's catalog +// is never one: it lists what its membership charges per token, $0, not +// what the model costs (membershipCatalogs). +func (p Provider) EndpointCatalog() string { + if p.Account != nil || len(p.Catalogs()) > 0 { + return "" + } + var found []string + // the Anthropic base is kept as its root (normalize), where models.dev + // writes an Anthropic API's with its /v1 + urls := []string{p.Chat, p.Responses, p.Anthropic, p.Gemini} + if p.Anthropic != "" { + urls = append(urls, p.Anthropic+"/v1") + } + for _, u := range urls { + for _, id := range catalog.AtEndpoint(u) { + if !slices.Contains(found, id) { + found = append(found, id) + } + } + } + if len(found) != 1 || strings.Contains(found[0], "-plan") || slices.Contains(membershipCatalogs, found[0]) { + return "" + } + return found[0] +} + // cursorFast is a Cursor id of a Grok model in its fast mode, at an effort // or not, at a window or not: grok-4.7-fast, grok-4.7-low-fast, // grok-4.7-xhigh-fast@500k. m[1] is the model it is fast of. diff --git a/internal/provider/testdata/endpoint_catalog.json b/internal/provider/testdata/endpoint_catalog.json new file mode 100644 index 000000000..3a58c5a05 --- /dev/null +++ b/internal/provider/testdata/endpoint_catalog.json @@ -0,0 +1,228 @@ +{ + "amd": { + "id": "amd", + "name": "AMD", + "api": "https://developer.amd.com.cn/radeon/api/v1", + "models": { + "Qwen3.8-27B": { + "id": "Qwen3.8-27B", + "name": "Qwen3.8 27B", + "cost": { + "input": 0, + "output": 0 + }, + "canonical_model_id": "alibaba/qwen3.8-27b" + }, + "DeepSeek-V4.1-Flash": { + "id": "DeepSeek-V4.1-Flash", + "name": "DeepSeek V4.1 Flash", + "cost": { + "input": 0.14, + "output": 0.28, + "cache_read": 0.0028 + }, + "canonical_model_id": "deepseek/deepseek-v4.1-flash" + }, + "DeepSeek-V4-Flash": { + "id": "DeepSeek-V4-Flash", + "name": "DeepSeek V4 Flash 0731", + "cost": { + "input": 0.14, + "output": 0.28, + "cache_read": 0.0028 + }, + "canonical_model_id": "deepseek/deepseek-v4-flash-0731" + }, + "Qwen3.8-Flash-Next": { + "id": "Qwen3.8-Flash-Next", + "name": "Qwen3.8 Flash Next", + "cost": { + "input": 0.15, + "output": 0.47, + "cache_read": 0.016 + }, + "canonical_model_id": "alibaba/qwen3.8-flash-next" + }, + "MiniCPM5-2B": { + "id": "MiniCPM5-2B", + "name": "MiniCPM5-2B", + "cost": { + "input": 0.124, + "output": 0.7425, + "cache_read": 0.124 + }, + "canonical_model_id": "openbmb/minicpm5-2b" + }, + "DeepSeek-V4-Flash-Vision-Exp": { + "id": "DeepSeek-V4-Flash-Vision-Exp", + "name": "DeepSeek V4 Flash Vision Exp", + "cost": { + "input": 0.14, + "output": 0.28, + "cache_read": 0.0028 + }, + "canonical_model_id": "deepseek/deepseek-v4-flash-vision-exp" + } + } + }, + "alibaba": { + "id": "alibaba", + "name": "Alibaba", + "api": "https://dashscope-intl.aliyuncs.com/compatible-mode/v1", + "models": { + "qwen3.8-max": { + "id": "qwen3.8-max", + "name": "Qwen3.8 Max", + "cost": { + "input": 2, + "output": 6, + "cache_read": 0.25, + "cache_write": 2.5 + }, + "canonical_model_id": "alibaba/qwen3.8-max" + }, + "qwen3.5-plus": { + "id": "qwen3.5-plus", + "name": "Qwen3.5 Plus", + "cost": { + "input": 0.4, + "output": 2.4, + "reasoning": 2.4 + } + }, + "qwen3.8-flash": { + "id": "qwen3.8-flash", + "name": "Qwen3.8 Flash", + "cost": { + "input": 0.15, + "output": 0.47, + "cache_read": 0.016, + "cache_write": 0.2 + }, + "canonical_model_id": "alibaba/qwen3.8-flash" + }, + "qwen3.6-27b": { + "id": "qwen3.6-27b", + "name": "Qwen3.6 27B", + "cost": { + "input": 0.6, + "output": 3.6 + } + } + } + }, + "alibaba-coding-plan": { + "id": "alibaba-coding-plan", + "name": "Alibaba Coding Plan", + "api": "https://coding-intl.dashscope.aliyuncs.com/v1", + "models": { + "qwen3.5-plus": { + "id": "qwen3.5-plus", + "name": "Qwen3.5 Plus", + "cost": { + "input": 0, + "output": 0, + "cache_read": 0, + "cache_write": 0 + } + } + } + }, + "minimax": { + "id": "minimax", + "name": "MiniMax (minimax.io)", + "api": "https://api.minimax.io/anthropic/v1", + "models": { + "MiniMax-M3": { + "id": "MiniMax-M3", + "name": "MiniMax-M3", + "cost": { + "input": 0.3, + "output": 1.2, + "cache_read": 0.06, + "tiers": [ + { + "input": 0.6, + "output": 2.4, + "cache_read": 0.12, + "tier": { + "type": "context", + "size": 512000 + } + } + ], + "context_over_200k": { + "input": 0.6, + "output": 2.4, + "cache_read": 0.12 + } + } + } + } + }, + "minimax-coding-plan": { + "id": "minimax-coding-plan", + "name": "MiniMax Token Plan (minimax.io)", + "api": "https://api.minimax.io/anthropic/v1", + "models": { + "MiniMax-M3": { + "id": "MiniMax-M3", + "name": "MiniMax-M3", + "cost": { + "input": 0, + "output": 0, + "cache_read": 0, + "cache_write": 0 + } + } + } + }, + "openai": { + "id": "openai", + "name": "OpenAI", + "api": "", + "models": { + "gpt-5.5": { + "id": "gpt-5.5", + "name": "GPT-5.5", + "cost": { + "input": 5, + "output": 30, + "cache_read": 0.5, + "tiers": [ + { + "input": 10, + "output": 45, + "cache_read": 1, + "tier": { + "type": "context", + "size": 272000 + } + } + ], + "context_over_200k": { + "input": 10, + "output": 45, + "cache_read": 1 + } + } + } + } + }, + "thinkingmachines": { + "id": "thinkingmachines", + "name": "Thinking Machines", + "api": "https://tinker.thinkingmachines.dev/services/tinker-prod/anthropic/api/v1", + "models": { + "thinkingmachines/Inkling": { + "id": "thinkingmachines/Inkling", + "name": "Inkling", + "cost": { + "input": 1.87, + "output": 4.68, + "cache_read": 0.374 + } + } + } + } +}