From 908c9986cd129958fa11640a3494ffaaa0dbfa74 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 12 Nov 2026 08:29:46 +0800 Subject: [PATCH] =?UTF-8?q?templates:=20routing=20recipes=20=E2=80=94=20Pl?= =?UTF-8?q?an=20first,=20Fastest=20first,=20Spread=20evenly=20(qhyqhy1s=20?= =?UTF-8?q?on=20X)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit qhyqhy1s asked for best-practice templates in routing groups, as only three were offered. The Routing page's template cards and Templates menu (and `magpie group template`) now carry three more, each only a setting the engine already has: - Plan first (plan): the strongest model of up to three providers, the ones billed by a plan (Provider.BillingKind) ahead of pay-as-you-go ones. Not made when no provider is on a plan (NeedPlan). - Fastest first (fast): the same members, routing "fast". - Spread evenly (even): the one strongest model from up to four providers that serve it, routing "rotate" over all their keys and accounts. Names, one-line descriptions and the new "Needs a subscription or token plan" are in zh, zh-TW, ja and de. docs/subsystems/gateway-routing.md has a Routing recipes section. Run on mote at the pushed tree: go test ./internal/provider ./internal/cli ./internal/gui (Template|SizeOf|Group) ok; gofmt -l clean; group-template, getting-started, i18n-keys and i18n-en-no-cjk GUI files, 98 tests, chromium and webkit, 420px, every language, ok. Broken by hand: routing left unset on Fastest first, TestRecipeTemplates red. Not tried: a real account adding each template; the full GUI and Go suites are started after the tag. --- docs/subsystems/gateway-routing.md | 27 +++++++++ internal/gui/assets/i18n.js | 24 ++++++++ internal/gui/assets/plugins/routing/client.js | 4 ++ internal/gui/assets/plugins/routing/i18n.js | 4 ++ internal/gui/tests/group-template.test.cjs | 23 +++++--- internal/provider/grouptemplate.go | 56 +++++++++++++++++-- internal/provider/grouptemplate_test.go | 41 ++++++++++++++ 7 files changed, 166 insertions(+), 13 deletions(-) diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 6686e1dd8..dc56ad6a4 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -57,6 +57,33 @@ removed records stay and turning them on again restores the groups as they were. | Vertex AI | A [Google Vertex AI provider](providers-accounts.md#responsibilities-and-sources-of-truth) speaks Gemini for its Gemini models, chat completions for its partner models, and Anthropic's Messages API for Claude. Claude (`provider.VertexClaude`: `claude-opus-5-5`, `claude-sonnet-4-5@20250929`) is relayed or translated as at any Anthropic vendor, and `forwardOnce`, after every other change to the body, moves the request to where Anthropic's Vertex SDK sends it (`provider.VertexClaudeRequest`): `/publishers/anthropic/models/:streamRawPredict` when the body streams, `:rawPredict` when it doesn't, the model out of the body; count_tokens to `count-tokens:rawPredict` with the model kept (`countTokens` counts at a provider whose `Base(Anthropic)` is set); `anthropic_version` `vertex-2023-10-16` added unless the body has one; Claude Code's `?beta=true` never sent. `thinkingOffAsTaken` and `samplingAsTaken` run before, so they read the model from the body. Tool search's beta goes as `tool-search-tool-2025-10-19`, the name Claude Code gives it for Vertex as for Bedrock (`bedrockBetas`); Bedrock's left-out betas aren't left out for it. Gemini's effort rules (`vertexEffort`) don't touch it (`TestVertexClaudeModel`). A partner model (`provider.VertexPartner`: a `publisher/model` id such as `deepseek-ai/deepseek-v4.1-flash-maas`) goes to Google's OpenAI-compatible `/endpoints/openapi/chat/completions` (`Base(Chat)`, `ListedAPIs`), signed with the same token, its full id in the body. It is relayed or translated there as any chat completions vendor is, and none of the Gemini rules below (`vertexEffort`, `vertexThinking`, signatures) touch it (`TestVertexPartnerModel`). A Gemini model's request goes to `/publishers/google/models/:streamGenerateContent?alt=sse` (`provider.VertexPath`, `upstreamPath`), the model named as the user's upstream name for it says (`UpstreamNameIn`, which the usage log's endpoint names too), with no `model` or `stream` field in its body (`passthrough`, `forwardOnce`, `geminiRequest`). A Gemini client's request is relayed as it came, its own `thinkingConfig`, `safetySettings` and the rest kept: streamed there, asked whole to `:generateContent` (`provider.VertexWholePath`), which answers one JSON body (Factory's rule of translating a whole request, as its route only streams, isn't Vertex AI's). Every other API's is translated (`buildFor`, `buildVertex`) and its stream read by `codeAssistDecoder`, which gives thought parts as reasoning, never as the answer's text. Effort: `vertexEffort` fits it to the model's levels, reasoning turned off going as `minimal` fitted the same way, and holds a model whose levels aren't known to `low`…`high`. `vertexThinking` sends Gemini 3 a `thinkingLevel` (`includeThoughts` false with reasoning off) and 2.5 a `thinkingBudget` in the model's range (`vertexBudgets`): turned off, the budget that stops its thinking, or Pro's least, as Pro can't stop. Thought signatures are every Gemini path's (#1445): a call's signature reaches the client in its id (`signedID`) and goes back on the call it came on, while a call with none in a step Vertex AI signed goes without; a step with nothing to give back has every call sent `skip_thought_signature_validator`. A 400 `Invalid thought signature.` (or AI Studio's `Corrupted thought signature.`, `signatureRefused`) is asked again with every call sent so (`withoutSignatures`), for that request only, at any upstream Gemini's signatures reach (`signaturesReach`), relayed too; it rests no account and lets a group go on (`restAfterMarked`, `shapeRefused`). A 400 refusing `minimal` (`geminiRefusedLevel`) is asked again at the model's lowest other level (`onEffort`), and `markUnfit(offRefused)` keeps that level until magpie restarts; that retry is the translated path's. Vertex AI's own Google Search grounding isn't used: `searchHosts` names only `generativelanguage.googleapis.com` for Gemini, so magpie searches for it (`search.go`). | [`vertex.go`](../../internal/gateway/vertex.go), [`gateway.go`](../../internal/gateway/gateway.go), [`codeassist.go`](../../internal/gateway/codeassist.go), [`gemini.go`](../../internal/gateway/gemini.go), [`gemini_signature.go`](../../internal/gateway/gemini_signature.go), [`search.go`](../../internal/gateway/search.go) | | Bedrock Mantle | A request on chat completions or Responses to an [Amazon Bedrock Mantle provider](providers-accounts.md#responsibilities-and-sources-of-truth) goes to the prefix that serves its model (`mantleRoutes`, `provider.MantleBase` in `forwardOnce`): `/openai/v1` for OpenAI's closed GPTs and xAI's Grok, `/v1` for the rest. A model Mantle refuses there with "model `x` isn't supported on this route" (a maker the rule doesn't know yet) is asked once more at the other prefix, and when it is taken there that prefix is remembered for the model in `unfit` (`mantleRouteKey`) until the gateway restarts. A model refused at both gets the first refusal and nothing is remembered (`mantleReroute`). Messages go to `/anthropic` alone. | [`mantle.go`](../../internal/gateway/mantle.go), [`gateway.go`](../../internal/gateway/gateway.go) | +## Routing recipes + +A routing group's templates (`provider.Templates` in +[`grouptemplate.go`](../../internal/provider/grouptemplate.go); the Routing +page's cards, then its Templates menu; `magpie group template`) are groups +for needs most users have, made of the user's own models. Each only sets +what the engine already has: members, a routing, rules, a classifier. Which +model is strong or cheap comes from list prices and release days, never a +list of names. + +| Template | Routing | Members | Made when | +| --- | --- | --- | --- | +| Hard to strong, easy to cheap (`smart`) | order, with intent rules and a classifier | the strongest model and a cheap one | a cheap model exists | +| Cheap first (`thrifty`) | order, the strongest for high reasoning | up to two cheap models, then the strongest | a cheap model exists | +| Never stuck (`steady`) | order | the strongest model of up to three providers | two providers | +| Plan first (`plan`) | order | as `steady`, the providers billed by a plan (`Provider.BillingKind`) ahead of pay-as-you-go ones | a plan provider, and two providers | +| Fastest first (`fast`) | `fast` | as `steady` | two providers | +| Spread evenly (`even`) | `rotate` | the one strongest model, from up to four providers that serve it | any model | + +Pick by the need. A subscription to spend before any key: Plan first. The +quickest answer: Fastest first. One model shared over several accounts or +relays, so none runs dry: Spread evenly. A provider down or out of quota +mustn't stop the agent: Never stuck. A cheap model for most turns: Cheap first. +Hard turns to a strong model, easy ones to a cheap one: Hard to strong, easy to +cheap. A template that can't be made says what it lacks (`Need*`) and has no +buttons. Adding one saves a group beside the user's others, never over one. + ## Codex titles, descriptions, summaries and predictions Codex's title and description requests are independent hidden turns. The diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 18ca8ae4d..7383b5d5b 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2841,6 +2841,12 @@ const I18N = { "A cheap model first; the strongest for high reasoning, or when the cheap ones fail": "先用便宜模型;需要高推理或便宜模型都失败时,交给最强的模型", "Never stuck": "永不卡住", "The strongest model of each provider, each behind the other: one down doesn't stop the agent": "每家供应商最强的模型依次互为后备:一家挂了,智能体照样能用", + "Plan first": "计划优先", + "Subscriptions and token plans first, pay-as-you-go keys only after them": "订阅和 Token 套餐优先,按量付费的密钥排在后面", + "Fastest first": "最快优先", + "Whichever provider has answered fastest lately goes first": "最近响应最快的供应商排在最前", + "Spread evenly": "均匀分担", + "The strongest model, taken in turn over every provider and account that serves it": "最强模型,在所有提供它的供应商和账号间轮流使用", "Added {name}": "已添加 {name}", "Templates": "模板", "Copy of {name}": "{name} 的副本", @@ -7941,6 +7947,12 @@ const I18N = { "A cheap model first; the strongest for high reasoning, or when the cheap ones fail": "先用便宜模型;需要高推理或便宜模型都失敗時,交給最強的模型", "Never stuck": "永不卡住", "The strongest model of each provider, each behind the other: one down doesn't stop the agent": "每家供應商最強的模型依序互為後備:一家掛了,代理照樣能用", + "Plan first": "方案優先", + "Subscriptions and token plans first, pay-as-you-go keys only after them": "訂閱和 Token 方案優先,按量計費的金鑰排在後面", + "Fastest first": "最快優先", + "Whichever provider has answered fastest lately goes first": "最近回應最快的供應商排在最前", + "Spread evenly": "平均分擔", + "The strongest model, taken in turn over every provider and account that serves it": "最強模型,在所有提供它的供應商和帳號間輪流使用", "Added {name}": "已新增 {name}", "Templates": "範本", "Copy of {name}": "{name} 的副本", @@ -13019,6 +13031,12 @@ const I18N = { "A cheap model first; the strongest for high reasoning, or when the cheap ones fail": "まず安いモデル。高い推理が必要なときや安いモデルが失敗したときは最強のモデルへ", "Never stuck": "止まらない", "The strongest model of each provider, each behind the other: one down doesn't stop the agent": "各プロバイダーの最強モデルが順に控える:一つが落ちてもエージェントは止まらない", + "Plan first": "プラン優先", + "Subscriptions and token plans first, pay-as-you-go keys only after them": "サブスクリプションとトークンプランが先、従量課金のキーはその後", + "Fastest first": "最速優先", + "Whichever provider has answered fastest lately goes first": "直近で最も速く応答したプロバイダーが先頭", + "Spread evenly": "均等に分散", + "The strongest model, taken in turn over every provider and account that serves it": "最強モデルを、それを提供する全プロバイダーとアカウントで順番に使う", "Added {name}": "{name} を追加しました", "Templates": "テンプレート", "Copy of {name}": "{name} のコピー", @@ -18128,6 +18146,12 @@ const I18N = { "A cheap model first; the strongest for high reasoning, or when the cheap ones fail": "Zuerst ein günstiges Modell; das stärkste bei hohem Reasoning oder wenn die günstigen scheitern", "Never stuck": "Nie blockiert", "The strongest model of each provider, each behind the other: one down doesn't stop the agent": "Das stärkste Modell jedes Anbieters, eines hinter dem anderen: fällt einer aus, arbeitet der Agent weiter", + "Plan first": "Tarif zuerst", + "Subscriptions and token plans first, pay-as-you-go keys only after them": "Abos und Token-Tarife zuerst, Pay-as-you-go-Schlüssel erst danach", + "Fastest first": "Schnellster zuerst", + "Whichever provider has answered fastest lately goes first": "Der Anbieter, der zuletzt am schnellsten geantwortet hat, kommt zuerst", + "Spread evenly": "Gleichmäßig verteilen", + "The strongest model, taken in turn over every provider and account that serves it": "Das stärkste Modell, reihum über alle Anbieter und Konten, die es anbieten", "Added {name}": "{name} hinzugefügt", "Templates": "Vorlagen", "Copy of {name}": "Kopie von {name}", diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index 82097250d..23d48554e 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -6654,11 +6654,15 @@ function routingPage(part) { smart: ["Hard to strong, easy to cheap", "A hard task goes to the strongest model, an easy one and compaction to a cheap one"], thrifty: ["Cheap first", "A cheap model first; the strongest for high reasoning, or when the cheap ones fail"], steady: ["Never stuck", "The strongest model of each provider, each behind the other: one down doesn't stop the agent"], + plan: ["Plan first", "Subscriptions and token plans first, pay-as-you-go keys only after them"], + fast: ["Fastest first", "Whichever provider has answered fastest lately goes first"], + even: ["Spread evenly", "The strongest model, taken in turn over every provider and account that serves it"], }; const tplName = (tp) => t(TPL[tp.kind]?.[0] || tp.group.name); // what a template that can't be made is missing (provider.Need*) const tplNeed = (tp) => tp.need === "providers" ? t("Needs models from two providers: {name} is the only one", { name: tp.of }) : tp.need === "cheap" ? t("Needs a model cheap beside {name}", { name: tp.of }) + : tp.need === "plan" ? t("Needs a subscription or token plan") : tp.need ? t("Add a provider first") : ""; const tplMembers = (tp) => tp.group.members.map((id) => memberName(id)).join(" → "); async function addTemplate(tp) { diff --git a/internal/gui/assets/plugins/routing/i18n.js b/internal/gui/assets/plugins/routing/i18n.js index 515a7f036..7721fefd9 100644 --- a/internal/gui/assets/plugins/routing/i18n.js +++ b/internal/gui/assets/plugins/routing/i18n.js @@ -101,6 +101,7 @@ magpie.strings({ "{n} rules left out with them": "{n} 条规则随之略过", "Needs models from two providers: {name} is the only one": "需要两家供应商的模型:目前只有 {name}", "Needs a model cheap beside {name}": "需要一个比 {name} 便宜的模型", + "Needs a subscription or token plan": "需要一个订阅或 Token 套餐", "Add a provider first": "请先添加供应商", "Start from a template: made of your own models, added in a click": "从模板开始:用你自己的模型组成,一键添加", "Edit first": "先编辑", @@ -855,6 +856,7 @@ magpie.strings({ "{n} rules left out with them": "{n} 條規則隨之略過", "Needs models from two providers: {name} is the only one": "需要兩家供應商的模型:目前只有 {name}", "Needs a model cheap beside {name}": "需要一個比 {name} 便宜的模型", + "Needs a subscription or token plan": "需要一個訂閱或 Token 方案", "Add a provider first": "請先新增供應商", "Start from a template: made of your own models, added in a click": "從範本開始:用你自己的模型組成,一鍵新增", "Edit first": "先編輯", @@ -1587,6 +1589,7 @@ magpie.strings({ "{n} rules left out with them": "{n} 件のルールも一緒に除外", "Needs models from two providers: {name} is the only one": "2 つのプロバイダーのモデルが必要です:今は {name} だけです", "Needs a model cheap beside {name}": "{name} より安いモデルが必要です", + "Needs a subscription or token plan": "サブスクリプションまたはトークンプランが必要です", "Add a provider first": "まずプロバイダーを追加してください", "Start from a template: made of your own models, added in a click": "テンプレートから:あなたのモデルで組み、ワンクリックで追加", "Edit first": "先に編集", @@ -2331,6 +2334,7 @@ magpie.strings({ "{n} rules left out with them": "{n} Regeln mit ihnen weggelassen", "Needs models from two providers: {name} is the only one": "Braucht Modelle von zwei Anbietern: {name} ist der einzige", "Needs a model cheap beside {name}": "Braucht ein Modell, das günstiger ist als {name}", + "Needs a subscription or token plan": "Braucht ein Abo oder einen Token-Tarif", "Add a provider first": "Füge zuerst einen Anbieter hinzu", "Start from a template: made of your own models, added in a click": "Mit einer Vorlage beginnen: aus deinen eigenen Modellen, mit einem Klick hinzugefügt", "Edit first": "Erst bearbeiten", diff --git a/internal/gui/tests/group-template.test.cjs b/internal/gui/tests/group-template.test.cjs index d2ae8d809..0bcc753fb 100644 --- a/internal/gui/tests/group-template.test.cjs +++ b/internal/gui/tests/group-template.test.cjs @@ -28,19 +28,22 @@ const templates = [ rules: [{ use: "a/mini", compact: true }, { use: "a/big", intent: HARD }, { use: "a/mini", intent: EASY }] } }, { kind: "thrifty", group: { id: "cheap-first", name: "Cheap first", members: ["a/mini", "a/big"], routing: "order", rules: [{ use: "a/big", effort: "high" }] } }, { kind: "steady", group: { id: "never-stuck", name: "Never stuck", routing: "order" }, why: "it needs models from two providers: A is the only one", need: "providers", of: "A" }, + { kind: "plan", group: { id: "plan-first", name: "Plan first", routing: "order" }, why: "no provider of yours is billed by a plan", need: "plan" }, + { kind: "fast", group: { id: "fastest-first", name: "Fastest first", members: ["a/big", "a/mini"], routing: "fast" } }, + { kind: "even", group: { id: "spread-evenly", name: "Spread evenly", members: ["a/big"], routing: "rotate" } }, ]; const words = { - en: { smart: "Hard to strong, easy to cheap", thrifty: "Cheap first", steady: "Never stuck", add: "Add", edit: "Edit first", added: "Added Hard to strong, easy to cheap", menu: "Templates", need: "Needs models from two providers: A is the only one" }, - zh: { smart: "难题给强模型,简单的给便宜模型", thrifty: "便宜优先", steady: "永不卡住", add: "添加", edit: "先编辑", added: "已添加 难题给强模型,简单的给便宜模型", menu: "模板", need: "需要两家供应商的模型:目前只有 A" }, - "zh-TW": { smart: "難題給強模型,簡單的給便宜模型", thrifty: "便宜優先", steady: "永不卡住", add: "新增", edit: "先編輯", added: "已新增 難題給強模型,簡單的給便宜模型", menu: "範本", need: "需要兩家供應商的模型:目前只有 A" }, - ja: { smart: "難しい作業は強いモデル、簡単な作業は安いモデルへ", thrifty: "安いモデル優先", steady: "止まらない", add: "追加", edit: "先に編集", added: "難しい作業は強いモデル、簡単な作業は安いモデルへ を追加しました", menu: "テンプレート", need: "2 つのプロバイダーのモデルが必要です:今は A だけです" }, - de: { smart: "Schweres zum starken, Leichtes zum günstigen Modell", thrifty: "Günstig zuerst", steady: "Nie blockiert", add: "Hinzufügen", edit: "Erst bearbeiten", added: "Schweres zum starken, Leichtes zum günstigen Modell hinzugefügt", menu: "Vorlagen", need: "Braucht Modelle von zwei Anbietern: A ist der einzige" }, + en: { smart: "Hard to strong, easy to cheap", thrifty: "Cheap first", steady: "Never stuck", add: "Add", edit: "Edit first", added: "Added Hard to strong, easy to cheap", menu: "Templates", need: "Needs models from two providers: A is the only one", plan: "Plan first", fast: "Fastest first", even: "Spread evenly", planNeed: "Needs a subscription or token plan" }, + zh: { smart: "难题给强模型,简单的给便宜模型", thrifty: "便宜优先", steady: "永不卡住", add: "添加", edit: "先编辑", added: "已添加 难题给强模型,简单的给便宜模型", menu: "模板", need: "需要两家供应商的模型:目前只有 A", plan: "计划优先", fast: "最快优先", even: "均匀分担", planNeed: "需要一个订阅或 Token 套餐" }, + "zh-TW": { smart: "難題給強模型,簡單的給便宜模型", thrifty: "便宜優先", steady: "永不卡住", add: "新增", edit: "先編輯", added: "已新增 難題給強模型,簡單的給便宜模型", menu: "範本", need: "需要兩家供應商的模型:目前只有 A", plan: "方案優先", fast: "最快優先", even: "平均分擔", planNeed: "需要一個訂閱或 Token 方案" }, + ja: { smart: "難しい作業は強いモデル、簡単な作業は安いモデルへ", thrifty: "安いモデル優先", steady: "止まらない", add: "追加", edit: "先に編集", added: "難しい作業は強いモデル、簡単な作業は安いモデルへ を追加しました", menu: "テンプレート", need: "2 つのプロバイダーのモデルが必要です:今は A だけです", plan: "プラン優先", fast: "最速優先", even: "均等に分散", planNeed: "サブスクリプションまたはトークンプランが必要です" }, + de: { smart: "Schweres zum starken, Leichtes zum günstigen Modell", thrifty: "Günstig zuerst", steady: "Nie blockiert", add: "Hinzufügen", edit: "Erst bearbeiten", added: "Schweres zum starken, Leichtes zum günstigen Modell hinzugefügt", menu: "Vorlagen", need: "Braucht Modelle von zwei Anbietern: A ist der einzige", plan: "Tarif zuerst", fast: "Schnellster zuerst", even: "Gleichmäßig verteilen", planNeed: "Braucht ein Abo oder einen Token-Tarif" }, }; const KEYS = ["Hard to strong, easy to cheap", "A hard task goes to the strongest model, an easy one and compaction to a cheap one", "Cheap first", "A cheap model first; the strongest for high reasoning, or when the cheap ones fail", "Never stuck", "The strongest model of each provider, each behind the other: one down doesn't stop the agent", "Needs models from two providers: {name} is the only one", - "Needs a model cheap beside {name}", "Add a provider first", "Added {name}", "Start from a template: made of your own models, added in a click", "Edit first", "Templates"]; + "Needs a model cheap beside {name}", "Needs a subscription or token plan", "Plan first", "Subscriptions and token plans first, pay-as-you-go keys only after them", "Fastest first", "Whichever provider has answered fastest lately goes first", "Spread evenly", "The strongest model, taken in turn over every provider and account that serves it", "Add a provider first", "Added {name}", "Start from a template: made of your own models, added in a click", "Edit first", "Templates"]; function serve(lang, posts, mine = 0) { // a group magpie found is no group of the user's: the cards still show @@ -97,15 +100,19 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.route("**/*", serve(lang, posts)); await page.goto("http://magpie.test/?view=groups"); const cards = page.locator(".rt-gtpl-card"); - await cards.nth(2).waitFor(); + await cards.nth(5).waitFor(); await page.waitForTimeout(500); - assert.deepEqual(await cards.evaluateAll((cs) => cs.map((c) => c.dataset.kind)), ["smart", "thrifty", "steady"]); + assert.deepEqual(await cards.evaluateAll((cs) => cs.map((c) => c.dataset.kind)), ["smart", "thrifty", "steady", "plan", "fast", "even"]); const smart = page.locator(".rt-gtpl-card[data-kind=smart]"), steady = page.locator(".rt-gtpl-card[data-kind=steady]"); assert.equal((await smart.locator("b").textContent()).trim(), w.smart); assert.equal((await smart.locator(".mem").textContent()).trim(), "Big → Mini"); // one that can't be made says what it needs, and offers nothing assert.equal((await steady.locator(".why").textContent()).trim(), w.need); assert.equal(await steady.locator("button").count(), 0); + // the recipes: named in the reader's language, one needing a plan says so + assert.deepEqual(await page.locator(".rt-gtpl-card[data-kind=plan] b, .rt-gtpl-card[data-kind=fast] b, .rt-gtpl-card[data-kind=even] b").allTextContents(), [w.plan, w.fast, w.even]); + assert.equal((await page.locator(".rt-gtpl-card[data-kind=plan] .why").textContent()).trim(), w.planNeed); + assert.equal((await page.locator(".rt-gtpl-card[data-kind=fast] .mem").textContent()).trim(), "Big → Mini"); // every card whole on a narrow window, nothing scrolls sideways for (const box of await cards.evaluateAll((cs) => cs.map((c) => c.getBoundingClientRect().toJSON()))) { assert(box.x >= 0 && box.right <= 420, `card off the window: ${JSON.stringify(box)}`); diff --git a/internal/provider/grouptemplate.go b/internal/provider/grouptemplate.go index af92b892b..1f897e401 100644 --- a/internal/provider/grouptemplate.go +++ b/internal/provider/grouptemplate.go @@ -33,10 +33,22 @@ const ( // providers, in order, so one vendor down or out of quota doesn't stop // the agent. TemplateSteady = "steady" + // TemplatePlan is the strongest model of each of up to three + // providers, those billed by a plan (a subscription or token plan) + // before the pay-as-you-go ones, so the allowance already paid for is + // spent first and a key is the last resort. + TemplatePlan = "plan" + // TemplateFast is the same strongest models as TemplateSteady, the + // provider that has answered fastest lately first (Fastest). + TemplateFast = "fast" + // TemplateEven is the strongest model alone, from every provider that + // serves it (up to four), taken in turn over all their keys and + // accounts (Rotate). + TemplateEven = "even" ) // TemplateKinds are the templates, in the order they are offered. -var TemplateKinds = []string{TemplateSmart, TemplateThrifty, TemplateSteady} +var TemplateKinds = []string{TemplateSmart, TemplateThrifty, TemplateSteady, TemplatePlan, TemplateFast, TemplateEven} // The intents TemplateSmart's classifier chooses between. Hard comes // first, so a turn the classifier can't place stays on the strong model, @@ -64,6 +76,9 @@ const ( NeedProvider = "provider" NeedProviders = "providers" NeedCheap = "cheap" + // NeedPlan: no provider is billed by a plan, so "plan first" has + // nothing to put first + NeedPlan = "plan" ) // nonChat are words of a model id that isn't for an agent's chat: it @@ -236,11 +251,14 @@ var TemplateNames = map[string]string{ TemplateSmart: "Hard to strong, easy to cheap", TemplateThrifty: "Cheap first", TemplateSteady: "Never stuck", + TemplatePlan: "Plan first", + TemplateFast: "Fastest first", + TemplateEven: "Spread evenly", } // TemplateIDs are the ids agents pick a template's group as, before a // number when one is in use. -var TemplateIDs = map[string]string{TemplateSmart: "smart-split", TemplateThrifty: "cheap-first", TemplateSteady: "never-stuck"} +var TemplateIDs = map[string]string{TemplateSmart: "smart-split", TemplateThrifty: "cheap-first", TemplateSteady: "never-stuck", TemplatePlan: "plan-first", TemplateFast: "fastest-first", TemplateEven: "spread-evenly"} // templateOf is the template kind made of ms, its classifier a decider of // ds when there is one. @@ -253,10 +271,21 @@ func templateOf(kind string, ms []rated, ds []Entry) Template { } best := strong[0] switch kind { - case TemplateSteady: - // the strongest of each provider, up to three + case TemplateSteady, TemplatePlan, TemplateFast: + // the strongest of each provider, up to three; the plan ones + // first for TemplatePlan + pick := strong + if kind == TemplatePlan { + plan := func(m rated) bool { return m.e.Provider.BillingKind() == BillingPlan } + if !slices.ContainsFunc(strong, plan) { + t.Why, t.Need = "no provider of yours is billed by a plan: add a subscription or token plan", NeedPlan + return t + } + pick = slices.Clone(strong) + slices.SortStableFunc(pick, func(a, b rated) int { return -cmp.Compare(btoi(plan(a)), btoi(plan(b))) }) + } seen := map[string]bool{} - for _, m := range strong { + for _, m := range pick { if len(t.Group.Members) == 3 { break } @@ -269,6 +298,23 @@ func templateOf(kind string, ms []rated, ds []Entry) Template { t.Group.Members = nil t.Why, t.Need, t.Of = "it needs models from two providers: "+best.e.Provider.Name+" is the only one", NeedProviders, best.e.Provider.Name } + if kind == TemplateFast { + t.Group.Routing = Fastest + } + return t + case TemplateEven: + // the one strongest model, from each provider that serves it + seen := map[string]bool{} + for _, m := range strong { + if len(t.Group.Members) == 4 { + break + } + if bareModel(m.e.Model) == bareModel(best.e.Model) && !seen[m.e.Provider.ID] { + seen[m.e.Provider.ID] = true + t.Group.Members = append(t.Group.Members, m.e.ID) + } + } + t.Group.Routing = Rotate return t } cheap := cheapest(ms, best) diff --git a/internal/provider/grouptemplate_test.go b/internal/provider/grouptemplate_test.go index 12707de6f..da1ac0a1c 100644 --- a/internal/provider/grouptemplate_test.go +++ b/internal/provider/grouptemplate_test.go @@ -101,6 +101,47 @@ func TestTemplatesPickStrongAndCheap(t *testing.T) { } } +// The routing recipes (plan first, fastest first, spread evenly) are the +// strongest models set to a routing the engine already has. +func TestRecipeTemplates(t *testing.T) { + sub := tm("sub", "claude-opus-5.5", 50, true, "2026-08-01") + sub.e.Provider.Billing = BillingPlan + key := tm("openai", "gpt-6.1", 40, true, "2026-09-20") + key.e.Provider.Billing = BillingPAYG + relay := tm("relay", "gpt-6.1", 40, true, "2026-09-20") + ms := []rated{key, relay, sub, tm("openai", "gpt-6-mini", 4, true, "2026-07-01")} + + // the plan's model first, though the key's model is newer + plan := templateOf(TemplatePlan, ms, nil) + if want := []string{"sub/claude-opus-5.5", "openai/gpt-6.1", "relay/gpt-6.1"}; plan.Why != "" || !slices.Equal(plan.Group.Members, want) || plan.Group.Routing != Ordered { + t.Errorf("plan = %+v, want %v in order", plan, want) + } + // nothing on a plan: nothing to put first + if tp := templateOf(TemplatePlan, []rated{key, relay}, nil); tp.Need != NeedPlan || len(tp.Group.Members) > 0 { + t.Errorf("plan without a plan: %+v", tp) + } + fast := templateOf(TemplateFast, ms, nil) + if fast.Group.Routing != Fastest || len(fast.Group.Members) != 3 { + t.Errorf("fast = %+v", fast) + } + if tp := templateOf(TemplateFast, []rated{key, ms[3]}, nil); tp.Need != NeedProviders { + t.Errorf("fast with one provider: %+v", tp) + } + // one model, every provider that serves it; the other model stays out + even := templateOf(TemplateEven, ms, nil) + if even.Group.Routing != Rotate || !slices.Equal(even.Group.Members, []string{"openai/gpt-6.1", "relay/gpt-6.1"}) { + t.Errorf("even = %+v, want the one strongest model from both providers", even) + } + if even = templateOf(TemplateEven, []rated{sub, ms[3]}, nil); !slices.Equal(even.Group.Members, []string{"sub/claude-opus-5.5"}) { + t.Errorf("even with one provider = %+v, want it alone", even) + } + for _, k := range TemplateKinds { + if TemplateNames[k] == "" || TemplateIDs[k] == "" { + t.Errorf("template %s has no name or id", k) + } + } +} + func TestTemplatesSayWhatIsMissing(t *testing.T) { if tp := templateOf(TemplateSmart, nil, nil); tp.Need != NeedProvider || len(tp.Group.Members) > 0 { t.Errorf("no models: %+v", tp)