diff --git a/internal/gateway/classify.go b/internal/gateway/classify.go index f45e0bd7e..399bb0178 100644 --- a/internal/gateway/classify.go +++ b/internal/gateway/classify.go @@ -14,6 +14,7 @@ import ( "crypto/sha256" "encoding/hex" "encoding/json" + "errors" "fmt" "net/http" "net/http/httptest" @@ -55,6 +56,10 @@ type classifyFailure struct { at time.Time } +// answerError is a classifier that answered, but not with one of the +// numbers: it is up, so it isn't left to rest for it. +type answerError struct{ error } + // classify is ask's answer for the message, from what was asked before // when it can be: the same message and intents within classifyKeep. A // classifier that failed is left to rest for classifyRest rather than @@ -78,7 +83,9 @@ func classify(ask classifier, model string, intents []string, text string) (inte classified.Lock() defer classified.Unlock() if err != nil { - classified.failed[model] = classifyFailure{err: err.Error(), at: time.Now()} + if !errors.As(err, new(answerError)) { + classified.failed[model] = classifyFailure{err: err.Error(), at: time.Now()} + } return "", false, err } delete(classified.failed, model) @@ -124,8 +131,10 @@ const classifyPrompt = "You route a user's message to a coding assistant by what "Given numbered kinds of request and the user's message, answer with the number of the kind the message is, " + "or 0 if it is none of them. Answer with the number only." -// classifyBody is the Chat request asking model which of intents text is. -func classifyBody(model string, intents []string, text string) []byte { +// classifyBody is the Chat request asking model which of intents text is, +// at effort when it isn't "". A model that reasons does so before it +// answers, and how long varies: 2048 leaves room for that and the number. +func classifyBody(model, effort string, intents []string, text string) []byte { var b strings.Builder b.WriteString("Kinds:\n") for i, in := range intents { @@ -134,7 +143,7 @@ func classifyBody(model string, intents []string, text string) []byte { b.WriteString("\nThe user's message:\n\n") b.WriteString(text) b.WriteString("\n\n\nThe number of its kind (0 for none):") - body, _ := json.Marshal(map[string]any{ + req := map[string]any{ "model": model, "messages": []map[string]string{ {"role": "system", "content": classifyPrompt}, @@ -142,8 +151,12 @@ func classifyBody(model string, intents []string, text string) []byte { }, "stream": false, "temperature": 0, - "max_tokens": 512, - }) + "max_tokens": 2048, + } + if effort != "" { + req["reasoning_effort"] = effort + } + body, _ := json.Marshal(req) return body } @@ -158,7 +171,7 @@ func readIntent(answer string, intents []string) (string, error) { if len(a) > 80 { a = append(a[:80], '…') } - return "", fmt.Errorf("it answered %q, not a number from 0 to %d", string(a), len(intents)) + return "", answerError{fmt.Errorf("it answered %q, not a number from 0 to %d", string(a), len(intents))} } if n == 0 { return "", nil @@ -166,6 +179,21 @@ func readIntent(answer string, intents []string) (string, error) { return intents[n-1], nil } +// classifyEffort is the least reasoning model takes: none when it can go +// without, else its lowest level; "" when its levels aren't known, which +// leaves it to the vendor. +func classifyEffort(model string) string { + p, m, ok := provider.Resolve(model) + if !ok { + return "" + } + levels := p.Efforts(m) + if len(levels) == 0 { + return "" + } + return fitEffort("none", levels) +} + // askClassifier asks model through the gateway itself, as a client would. func (s *Server) askClassifier(model string, intents []string, text string) (string, error) { ctx, cancel := context.WithTimeout(context.Background(), classifyTimeout) @@ -177,7 +205,7 @@ func (s *Server) askClassifier(model string, intents []string, text string) (str r.Header.Set("Content-Type", "application/json") r.Header.Set("User-Agent", RouterAgent) w := httptest.NewRecorder() - s.serve(w, r, provider.Chat, classifyBody(model, intents, text)) + s.serve(w, r, provider.Chat, classifyBody(model, classifyEffort(model), intents, text)) if ctx.Err() != nil { return "", fmt.Errorf("%s gave no answer in %s", model, classifyTimeout) } @@ -202,7 +230,7 @@ func (s *Server) askClassifier(model string, intents []string, text string) (str return "", fmt.Errorf("%s: %s", model, msg) } if len(out.Choices) == 0 { - return "", fmt.Errorf("%s gave no answer", model) + return "", answerError{fmt.Errorf("%s gave no answer", model)} } return readIntent(out.Choices[0].Message.Content, intents) } diff --git a/internal/gateway/classify_test.go b/internal/gateway/classify_test.go index 8801dd8f8..7837a1781 100644 --- a/internal/gateway/classify_test.go +++ b/internal/gateway/classify_test.go @@ -252,6 +252,43 @@ func TestIntentClassifierFails(t *testing.T) { } } +// A classifier that answers something else is up: the turn goes on without +// an intent, and the next one asks it again rather than resting. +func TestIntentOddAnswerDoesNotRest(t *testing.T) { + s, _, _, c := intented(t, provider.Rule{Use: "b/big", Intent: "refactoring"}) + c.set("", 0) + out, r := postOK(t, s, "o1", chat("rename this package", nil, 0, "")) + if !strings.Contains(out, "from ka") || r.Rule.N != 0 || !strings.Contains(r.Rule.Classified.Error, "not a number") { + t.Fatalf("empty: %s %+v", out, r.Rule) + } + c.set("1", 0) + out, r = postOK(t, s, "o2", chat("rename that package", nil, 0, "")) + if !strings.Contains(out, "from kb") || r.Rule.N != 1 || r.Rule.Classified.Error != "" || c.n() != 2 { + t.Fatalf("after: %s %+v %d", out, r.Rule, c.n()) + } +} + +// A classifier that reasons is asked to reason least, with room for its +// reasoning and the number; one whose levels aren't known is asked plainly. +func TestIntentClassifierEffort(t *testing.T) { + s, _, _, c := intented(t, provider.Rule{Use: "b/big", Intent: "refactoring"}) + c.set("1", 0) + postOK(t, s, "e1", chat("rename this package", nil, 0, "")) + if asked := c.last(); strings.Contains(asked, "reasoning_effort") || !strings.Contains(asked, `"max_tokens":2048`) { + t.Fatalf("plain: %s", asked) + } + p, _ := provider.Find("c") + for levels, want := range map[string]string{"low,high,max": "low", "none,low,high": "none", "minimal,medium": "minimal"} { + if err := catalog.SaveLive("c", p.Chat, []catalog.Model{{ID: "cls", Context: 32000, Efforts: strings.Split(levels, ",")}}); err != nil { + t.Fatal(err) + } + postOK(t, s, "e-"+levels, chat("rename "+levels, nil, 0, "")) + if asked := c.last(); !strings.Contains(asked, `"reasoning_effort":"`+want+`"`) { + t.Fatalf("%s: %s", levels, asked) + } + } +} + // The same message is classified once: another conversation starting with // it (an agent retrying, a subagent) reads the answer kept. func TestIntentAnswerKept(t *testing.T) { diff --git a/site/public/docs/intent.html b/site/public/docs/intent.html index 93fa40d29..f6127c7be 100644 --- a/site/public/docs/intent.html +++ b/site/public/docs/intent.html @@ -80,7 +80,7 @@
The Coder group: long turns go to Kimi, quick questions to DeepSeek Flash, tests to DeepSeek Pro. Llama 3.1 8B on Groq picks the intent.
-

Intent is one of the conditions a routing group’s rule can have, next to length, images, reasoning and agent. This page describes exactly what magpie does with it, as of v0.1.96, so you can predict every decision and check it in the Routing tab.

+

Intent is one of the conditions a routing group’s rule can have, next to length, images, reasoning and agent. This page describes exactly what magpie does with it, as of v0.1.99, so you can predict every decision and check it in the Routing tab.

In one paragraph. magpie decides once per turn: when you send a message, not while the agent works through tool calls. If a rule with an intent could be the first to match, magpie asks the group’s classifier model one short question through its own gateway. The question holds the intents as a numbered list plus the text of your latest message, and the classifier answers with a number. magpie reads that number and checks the rules top first with it. The first rule that matches puts its model first, and the group’s other models stay behind it for failover. The turn then stays on that model until you speak again. If the classifier fails, times out or answers something else, no intent matches and the turn is routed as if those rules weren’t there. There are no embeddings, no keyword lists and no training: the model you pick reads your message and picks a number.
@@ -155,7 +155,7 @@ The number of its kind (0 for none):
  • Images aren’t sent. A message that is only an image has no words to classify, so no intent matches. To route by images, use the rule’s has an image condition.
  • Agent reminders are removed. <system-reminder>…</system-reminder> blocks, which Claude Code adds to your message, are stripped. Other text an agent puts in the same message is kept.
  • Long messages are shortened. Over 4,000 characters, magpie keeps the first 3,000 and the last 1,000, joined by …. The start and the end usually say what is being asked.
  • -
  • The request settings. An OpenAI-style chat completion, not streamed, with temperature 0, max_tokens 512 and User-Agent magpie-router/1. magpie translates it for the classifier’s provider, like any other request, so an Anthropic, Gemini or other model works too.
  • +
  • The request settings. An OpenAI-style chat completion, not streamed, with temperature 0, max_tokens 2048 and User-Agent magpie-router/1. When magpie knows the classifier’s reasoning levels, it asks for the least: none if the model has it, else its lowest level (for example low). When the levels aren’t known, nothing is sent and the vendor’s default applies. magpie translates it for the classifier’s provider, like any other request, so an Anthropic, Gemini or other model works too.
  • When it can’t say

    @@ -165,8 +165,8 @@ The number of its kind (0 for none): It answers 0No intent matches. Rules without an intent and the group’s usual order decide. No answer within 8 sTreated as a failure: no intent matches, and the turn goes on at once. An error (quota, 5xx, bad key)Its provider’s own failover is tried first, within the 8 s. If it still fails, no intent matches. - An answer that isn’t a number from 0 to nA failure, for example when a reasoning model spends its 512 tokens thinking and answers nothing. - Any failureThat classifier model is left alone for 30 s: turns in that time don’t wait on it, and the trace says it wasn’t asked. The first good answer clears this. + An answer that isn’t a number from 0 to nNo intent matches this turn. The classifier did answer, so it isn’t rested: the next turn asks it again. + An error or the 8 s timeoutThat classifier model is left alone for 30 s: turns in that time don’t wait on it, and the trace says it wasn’t asked. The first good answer clears this. The message has no wordsNot asked. No intent matches.

    Each case is written in the turn’s trace with the reason. An intent rule can therefore make a turn go to a different model than you hoped, but it can’t make it fail.

    @@ -218,7 +218,7 @@ The number of its kind (0 for none):
  • Order still matters. Only the first matching rule counts, so put a rule that must win (such as a long-context rule) above the intent rules. The classifier is then skipped whenever that rule holds.
  • “None” is a real answer. A turn that fits no intent goes to the group’s usual order, so let that order be your default choice.
  • Any language. Intents and messages can be in any language the classifier understands. The fixed prompt is in English, and small models read mixed languages well.
  • -
  • Choosing a classifier. Pick a small, fast model without reasoning: Llama 3.1 8B on Groq, a Flash-Lite, nano or mini model, Claude Haiku, DeepSeek’s non-reasoning chat model, or a local model. A reasoning model is slower and may use its 512 tokens up before it answers. Check the trace for a few turns: if it guesses wrong, rewrite the intents before switching models.
  • +
  • Choosing a classifier. Pick a small, fast model without reasoning: Llama 3.1 8B on Groq, a Flash-Lite, nano or mini model, Claude Haiku, DeepSeek’s non-reasoning chat model, or a local model. A reasoning model is slower; magpie asks it for its least reasoning and leaves it 2048 tokens, but a slow one can still miss the 8 s. Check the trace for a few turns: if it guesses wrong, rewrite the intents before switching models.
  • Numbers

    @@ -229,7 +229,7 @@ The number of its kind (0 for none): Answer cache10 min, per classifier + intents + message; in memory Turn decisions kept24 h after the conversation’s last request; in memory Message sentUp to 4,000 characters; longer is first 3,000 + last 1,000 - Classifier requesttemperature 0, max_tokens 512, not streamed + Classifier requesttemperature 0, max_tokens 2048, the least reasoning the model has, not streamed Intent lengthUp to 200 characters; spaces collapsed, compared without case OutgrownAt 95% of the current model’s context, only to a model with more @@ -271,7 +271,9 @@ The number of its kind (0 for none):

    It can’t be a group: it must be one model, provider/model, which magpie checks when you save. It can be any model magpie has, including one of the group’s members, a subscription model or a local model.

    Can I use a reasoning model?

    -

    It works if it answers with a number within 8 s and 512 tokens. A model that thinks at length may run out and answer nothing, which counts as a failure. A small model without reasoning is faster, cheaper and just as good at this.

    +

    Yes, if it answers within 8 s. magpie asks it for the least reasoning it has (none, else its lowest level) and leaves 2048 tokens, so thinking doesn’t crowd out the answer. A small, fast model is still the better choice: cheaper, and every turn waits for it.

    +

    How well does it work with real models?

    +

    We ran 20 real coding messages (English and Chinese: quick questions, test work, and ordinary coding tasks, including “Fix the bug in parseTokens and add a test for it”) through a group with two intent rules. DeepSeek V4 Flash, GLM-5.3 Flash and MiMo v2.6 Flash each classified all 20 correctly; the median classifier time was 0.75 s, 1.3 s and 1.9 s. Gemini 3.8 Flash through one reseller took 11 s even at low reasoning, so every turn timed out and routed as if there were no intents — the trace said so each time. That is the pattern to expect: a wrong classifier costs you the routing, never the turn.

    Does retrying the same message ask again?

    Not within 10 minutes: the same message with the same intents and the same classifier is answered from the cache, and the trace says “said before”. Changing an intent or the classifier makes it ask again.

    diff --git a/site/public/docs/zh/intent.html b/site/public/docs/zh/intent.html index fa24550a9..ee3f947ad 100644 --- a/site/public/docs/zh/intent.html +++ b/site/public/docs/zh/intent.html @@ -80,7 +80,7 @@
    Coder 分组:长对话交给 Kimi,简单提问交给 DeepSeek Flash,写测试交给 DeepSeek Pro;由 Groq 上的 Llama 3.1 8B 判断意图。
    -

    意图是路由组规则的条件之一,与长度、图片、推理、Agent 并列。本页按 v0.1.96 的实际实现,逐条说明 magpie 拿它做了什么,让你能预判每一次路由决定,并在「路由」页里核对。

    +

    意图是路由组规则的条件之一,与长度、图片、推理、Agent 并列。本页按 v0.1.99 的实际实现,逐条说明 magpie 拿它做了什么,让你能预判每一次路由决定,并在「路由」页里核对。

    一段话说清楚。magpie 每一轮只做一次决定:在你发消息的时候做,Agent 调用工具的过程中不再做。如果某条带意图的规则有可能第一个命中,magpie 就通过自己的网关向分组的意图判断模型发一个很短的问题:给它带编号的意图列表和你最新一条消息的文字,让它回答一个数字。magpie 用这个数字从上往下检查规则,第一条命中的规则把它的模型排到第一,组里其他模型排在后面做故障转移。之后这一轮一直留在那个模型上,直到你再次发言。意图判断模型出错、超时或答非所问时,所有意图都不命中,这一轮按没有这些规则的方式路由。整个过程没有向量嵌入、没有关键词表,也不需要训练,就是让你选的那个模型读一遍消息,选一个编号。
    @@ -111,7 +111,7 @@ magpie group rule rm coder 2
  • 是不是新的一轮?magpie 看请求里最后一条用户消息:带文字或图片、不带工具结果,说明是你刚刚发言,新的一轮开始;带工具结果,说明是 Agent 在继续进行中的一轮(见这一轮的后续请求)。轮次按会话分别计数。子 Agent 是单独的会话:它和主 Agent 共用一个 session,但第一句话不同。
  • 哪些意图可能起作用?magpie 从上往下看规则,先不管意图:一条规则的其他条件(tokens、图片、推理、Agent)对这个请求都成立,它就是候选,把它的意图收集起来。只有大小写不同的意图算同一个。遇到第一条不带意图的候选规则就停止,因为它会直接命中,排在它下面的规则都轮不到。一个意图也没收集到时,不会询问意图判断模型,也不会产生费用。
  • 询问意图判断模型把收集到的意图和你这条消息的文字发给它,完整提示词见下文。这个调用和 Agent 的请求一样,走 magpie 自己的网关,所以用的是该模型所属供应商的 Key 或账号,以及它们的故障转移。它有 8 秒时间作答。
  • -
  • 读取回答取回答里出现的第一个整数:1 到 n 表示对应的意图,0 表示都不是。其他情况(没有数字、数字超出范围)都算失败。同一条消息、同一组意图的回答会缓存 10 分钟。
  • +
  • 读取回答取回答里出现的第一个整数:1 到 n 表示对应的意图,0 表示都不是。其他情况(没有数字、数字超出范围)这一轮都不命中意图。同一条消息、同一组意图的回答会缓存 10 分钟。
  • 匹配规则带着这个回答从上往下检查规则。带意图的规则,只有判断模型说的正是它的意图(不区分大小写),并且其他条件也都满足时才命中。第一条命中的规则生效;一条都不命中时,分组按平常的方式路由这一轮。
  • 给模型排序命中规则指定的模型排第一,组里其他模型按平常的顺序排在后面做故障转移。即使上一轮是别的模型回答的,也是这样:新一轮开始时,规则优先于会话保持。如果规则指定的模型此刻没有可用的 Key 或账号(都在冷却、供应商已关闭),就按分组原本的顺序,路由记录里会写明原因。
  • 记住这次决定magpie 把这次决定和判断模型的回答记在这个会话名下(由分组、Agent 的 session 和会话的第一句话确定),这一轮后面的请求都照它走。
  • @@ -155,7 +155,7 @@ The number of its kind (0 for none):
  • 不发送图片。只有图片的消息没有文字可判断,所有意图都不命中。想按图片路由,请用规则的带图片条件。
  • 去掉 Agent 插入的提醒。Claude Code 附加在消息里的 <system-reminder>…</system-reminder> 会被去掉;Agent 放在同一条消息里的其他文字会保留。
  • 长消息会截短。超过 4000 个字符时,保留前 3000 个和后 1000 个,中间用 … 连接。请求想做什么,一般在开头和结尾都能看出来。
  • -
  • 请求参数。OpenAI 格式的 chat completion,不流式,temperature 0,max_tokens 512,User-Agent 为 magpie-router/1。magpie 会像处理其他请求一样把它转换成判断模型所属供应商的协议,所以 Anthropic、Gemini 等模型也能用。
  • +
  • 请求参数。OpenAI 格式的 chat completion,不流式,temperature 0,max_tokens 2048,User-Agent 为 magpie-router/1。magpie 知道判断模型支持哪些推理档位时,会要最低的一档:支持 none 就用 none,否则用它最低的档位(比如 low);不知道档位时不传,由厂商默认。magpie 会像处理其他请求一样把它转换成判断模型所属供应商的协议,所以 Anthropic、Gemini 等模型也能用。
  • 判断不出来时

    @@ -165,8 +165,8 @@ The number of its kind (0 for none): 回答 0所有意图都不命中,由不带意图的规则和分组平常的顺序决定 8 秒内没有回答算失败:意图都不命中,这一轮立即继续 报错(额度用完、5xx、Key 无效)先在 8 秒内尝试它所属供应商自己的故障转移,仍然失败则意图都不命中 - 回答不是 0 到 n 之间的数字算失败。例如推理模型把 512 个 token 都花在思考上,最后没有给出答案 - 任何失败这个判断模型会冷却 30 秒:这段时间里的轮次不再等它,路由记录里会写 “not asked again for now”。之后第一次答对就解除 + 回答不是 0 到 n 之间的数字这一轮意图都不命中。判断模型确实回答了,所以不冷却,下一轮照常询问 + 报错或 8 秒超时这个判断模型会冷却 30 秒:这段时间里的轮次不再等它,路由记录里会写 “not asked again for now”。之后第一次答对就解除 消息里没有文字不询问,意图都不命中

    每种情况都会连同原因写进这一轮的路由记录。所以带意图的规则可能让这一轮去了你没想到的模型,但不会让它失败。

    @@ -218,7 +218,7 @@ The number of its kind (0 for none):
  • 顺序依然重要。只有第一条命中的规则生效,所以必须优先的规则(例如长上下文规则)要放在带意图的规则上面。它成立时,连判断模型都不用问。
  • “都不是”也是有效回答。不属于任何意图的轮次按分组平常的顺序走,所以把你的默认模型放在这个顺序的第一位。
  • 中文英文都行。意图和消息可以用判断模型能理解的任何语言书写。固定的提示词是英文的,小模型处理中英混合没有问题。
  • -
  • 怎么选判断模型。选小而快、不带推理的模型:Groq 上的 Llama 3.1 8B、各家的 Flash-Lite / nano / mini 系列、Claude Haiku、DeepSeek 的非推理对话模型,或者本地模型。推理模型更慢,还可能在给出答案之前就把 512 个 token 用完。先观察几轮路由记录,判断不准时,先改意图的措辞,再考虑换模型。
  • +
  • 怎么选判断模型。选小而快、不带推理的模型:Groq 上的 Llama 3.1 8B、各家的 Flash-Lite / nano / mini 系列、Claude Haiku、DeepSeek 的非推理对话模型,或者本地模型。推理模型更慢;magpie 会要它最低的推理档位并留 2048 个 token,但慢的模型仍可能超过 8 秒。先观察几轮路由记录,判断不准时,先改意图的措辞,再考虑换模型。
  • 数值一览

    @@ -229,7 +229,7 @@ The number of its kind (0 for none): 回答缓存10 分钟,按判断模型 + 意图 + 消息;仅内存 轮次决定保留会话最后一个请求之后 24 小时;仅内存 发送的消息长度最多 4000 字符;更长时取前 3000 + 后 1000 - 判断请求参数temperature 0,max_tokens 512,不流式 + 判断请求参数temperature 0,max_tokens 2048,模型最低的推理档位,不流式 意图长度最多 200 字符;多余空白会合并,比较时不区分大小写 超出上下文达到当前模型上下文的 95% 时,只换到上下文更大的模型 @@ -271,7 +271,7 @@ The number of its kind (0 for none):

    不能是路由组:它必须是单个模型(provider/model),保存时 magpie 会校验。它可以是 magpie 里的任何模型,包括组里的成员、订阅里的模型或本地模型。

    可以用推理模型吗?

    -

    只要它能在 8 秒、512 个 token 以内回答一个数字就可以。想得太久的模型可能把 token 用完而没有回答,这会算作失败。做这件事,不带推理的小模型更快、更便宜,效果也一样好。

    +

    可以,只要它能在 8 秒内回答。magpie 会要它最低的推理档位(有 none 用 none,否则用最低一档),并留 2048 个 token,思考不会挤掉答案。不过小而快的模型仍是更好的选择:更便宜,而且每一轮都要等它。

    重试同一条消息,会再问一次吗?

    10 分钟内不会:同一条消息、同一组意图、同一个判断模型,直接用缓存的回答,路由记录里写「同一条消息之前已判断过」。改了意图或者换了判断模型,就会重新询问。

    @@ -284,6 +284,8 @@ The number of its kind (0 for none):

    准确率怎么样?

    取决于判断模型,也取决于你的意图之间区分得是否清楚。几个明显不同的类别,小模型能判断得很好;有重叠的类别,它有时会猜错。判断错或没判断出来,影响的只是由哪个模型回答,所以建议先写两三个宽泛的意图,看一天路由记录,再调整措辞。

    +

    用真实模型测过吗?

    +

    测过。我们把 20 条真实的编程消息(中英文都有:简单提问、写测试/修测试、普通编码任务,还有 “Fix the bug in parseTokens and add a test for it” 这种混合的)发给一个带两条意图规则的分组。DeepSeek V4 Flash、GLM-5.3 Flash、MiMo v2.6 Flash 作为判断模型都是 20/20 全对,判断耗时中位数分别是 0.75 秒、1.3 秒、1.9 秒。某家中转上的 Gemini 3.8 Flash 即使用 low 推理档位也要 11 秒,每一轮都超时,于是都按没有意图规则的方式路由,路由记录每次都写明了原因。这也说明:判断模型选得不好,损失的只是路由效果,不会让这一轮失败。

    有问题,或者有值得分享的配置?欢迎到 Discord 交流。路由组的基础用法见快速上手。

    diff --git a/site/public/index.html b/site/public/index.html index 708d0dba2..9f066243a 100644 --- a/site/public/index.html +++ b/site/public/index.html @@ -266,6 +266,7 @@ footer a:hover { color: var(--ink); } .rt-accts .bar { grid-column: 2 / 4; height: 4px; border-radius: 2px; background: var(--bg2); overflow: hidden; } .rt-accts .bar i { display: block; height: 100%; width: 0; border-radius: 2px; background: var(--ink3); transition: width .4s; } .rt-accts li.nobar .bar { visibility: hidden; } +.rt-accts.models .bar { display: none; } .rt-accts .dot { width: 8px; height: 8px; border-radius: 50%; border: 1.5px solid var(--ink3); } .rt-accts li.on { border-color: var(--ink); } .rt-accts li.on em { color: var(--ink); } @@ -495,12 +496,13 @@ footer a:hover { color: var(--ink); }

    Smart routing

    -

    Many accounts. It never runs dry.

    -

    Add every key and subscription you have — several Claude, ChatGPT, Copilot or Grok accounts, several keys for one vendor — and turn them all on. For each request magpie picks the account that should answer, and when one can't, the next answers before your agent ever sees an error.

    +

    The right model for each turn. It never runs dry.

    +

    Say what each model is for — "a quick question", "writing or fixing tests" — and as each turn begins a small, fast model tells magpie which it is: the turn goes to that model, and its tool rounds stay there. How it works. And add every key and subscription you have — several Claude, ChatGPT, Copilot or Grok accounts, several keys for one vendor — and turn them all on. For each request magpie picks the account that should answer, and when one can't, the next answers before your agent ever sees an error.

    - + + @@ -681,7 +683,8 @@ magpie tui # the whole app, in the t const $ = (s) => rt.querySelector(s); const stage = $(".rt-stage"), svg = $(".rt-wires"), src = $(".rt-src"), hub = $(".rt-hub"), list = $(".rt-accts"); const cap = $(".rt-cap"), desc = $(".rt-mode"), chip = hub.querySelector("i"); - const stat = [...rt.querySelectorAll(".rt-stats b")]; + const stat = [...rt.querySelectorAll(".rt-stats b")], statName = [...rt.querySelectorAll(".rt-stats span")].map((e) => e.lastChild); + const who = src.querySelector("small"); const tabs = [...rt.querySelectorAll(".rt-tabs button")]; const still = matchMedia("(prefers-reduced-motion: reduce)").matches; const NS = "http://www.w3.org/2000/svg"; @@ -696,7 +699,29 @@ magpie tui # the whole app, in the t gh: ["octo-dev", "Copilot Business", "githubcopilot", "Copilot", "bird"], }; const A = (v, used, inc, x = {}) => { const [who, plan, icon, name, cls] = V[v]; return { who, plan, icon, name, cls, used, inc, ...x }; }; + // A group's models, each with the rule that sends a turn to it; the first + // takes what no rule matches. + const G = (who, plan, icon, cls, rule, short) => ({ who, plan, icon, cls, rule, short, used: 0, inc: 0, key: 1 }); const MODES = { + intent: { + name: "By intent", n: 0, stats: ["turns", "asked the classifier", "tool rounds kept on their model"], + desc: "By intent: as a turn begins, a small fast model (the group's classifier) is asked once which of your rules' intents the message is. The turn goes to that rule's model; its tool rounds stay there, without asking again.", + accts: () => [ + G("claude-opus-5-5", "Claude Max", "claude-color", "", "first · whatever no rule takes"), + G("deepseek-v4-flash", "DeepSeek", "deepseek-color", "", "intent · a quick question", "quick question"), + G("glm-5.3", "Zhipu GLM", "zhipu-color", "", "intent · writing or fixing tests", "tests"), + G("kimi-k3", "Kimi", "kimi", "bird", "intent · reviewing a diff", "review"), + ], + turns: [ + ["Add a --dry-run flag to the deploy command", 0, 2], + ["What does ^\\d{3}-\\d{4}$ match?", 1, 0], + ["TestRouting fails after my change — fix it", 2, 2], + ["Review my staged changes before I commit", 3, 1], + ["Why does useEffect run twice in dev?", 1, 0], + ["Write table-driven tests for parseTokens", 2, 1], + ["Refactor the retry loop into its own function", 0, 1], + ], + }, smart: { name: "Smart", n: 30, desc: "Smart, the default: the account that resets soonest goes first, so no allowance is left to go to waste; any that can't answer are passed over. (Here each request stands for an hour.)", @@ -778,9 +803,11 @@ magpie tui # the whole app, in the t a.wire = path(); a.served = 0; a.until = 0; }); layout(); - desc.textContent = M.desc; chip.textContent = M.name; + list.classList.toggle("models", !!M.turns); + desc.textContent = M.desc; chip.textContent = M.name; who.textContent = "your agent"; + (M.stats || ["requests", "rerouted", "errors your agent saw"]).forEach((n, i) => (statName[i].textContent = n)); tabs.forEach((b) => b.setAttribute("aria-selected", String(b.dataset.mode === m))); - show("Claude Code sends every request to magpie; magpie decides which account answers it."); + show(M.turns ? "Claude Code sends every turn to one model name — a magpie group. Watch where each message goes." : "Claude Code sends every request to magpie; magpie decides which account answers it."); stats(); render(); } @@ -872,7 +899,75 @@ magpie tui # the whole app, in the t dot.remove(); done++; errs++; stats(); } + // By intent: a turn's first request is classified, once; its tool rounds + // follow it to the same model. + async function turns(g) { + const trip = async (a) => { + const dot = document.createElementNS(NS, "circle"); + dot.setAttribute("r", 4.5); dot.setAttribute("class", "pkt"); dot.setAttribute("cx", -20); + svg.appendChild(dot); tick(src); + await travel(dot, wSrc, false, 380); + if (g !== gen) return dot.remove(); + tick(hub); + if (!a) return dot; + await travel(dot, a.wire, false, 420); + if (g !== gen) return dot.remove(); + last = a; a.served++; + dot.classList.add("back"); dot.setAttribute("r", 4); + await travel(dot, a.wire, true, 360); + await travel(dot, wSrc, true, 320); + dot.remove(); + }; + for (const [msg, n, rounds] of M.turns) { + if (g !== gen) return; + const a = accts[n]; + who.textContent = "new turn"; chip.textContent = "new turn"; + show(`A new turn: “${msg}”`); + const dot = await trip(null); + if (g !== gen) return; + chip.textContent = "classifying…"; + await wait(900); + if (g !== gen) return dot?.remove(); + rerouted++; stats(); + chip.textContent = n ? a.short : "no intent"; + a.li.classList.remove("hit"); void a.li.offsetWidth; a.li.classList.add("tagged"); + a.tg.textContent = n ? "✓ " + a.short : "✓ the group's first"; + setTimeout(() => a.li.classList.remove("tagged"), 1600); + show(n ? `The classifier says: ${a.rule.replace("intent · ", "")} — so ${a.who} answers it.` : `None of the intents — it goes to the group's first model, ${a.who}.`); + await travel(dot, a.wire, false, 420); + if (g !== gen) return dot.remove(); + last = a; a.served++; + dot.classList.add("back"); dot.setAttribute("r", 4); + await travel(dot, a.wire, true, 360); + await travel(dot, wSrc, true, 320); + dot.remove(); done++; stats(); + for (let i = 0; i < rounds; i++) { + if (g !== gen) return; + who.textContent = "tool result"; + chip.textContent = "same turn"; + if (!i) show(`Its tool results come back as more requests — no new question: they stay on ${a.who}.`); + await trip(a); + errs++; stats(); + } + await wait(rounds ? 700 : 1300); + } + if (g !== gen) return; + who.textContent = "your agent"; chip.textContent = M.name; + show(`${done} turns, each on the model its rule names — one question to the classifier per turn, ${errs} tool rounds kept on their model.`); + await wait(4600); + if (g === gen) reset(mode); + } + function render() { + if (M.turns) { + for (const a of accts) { + if (a.st.textContent !== a.rule) a.st.textContent = a.rule; + a.li.classList.toggle("on", last === a); + a.wire.classList.toggle("live", last === a); + } + wSrc.classList.toggle("live", !!last); + return; + } for (const a of accts) { const rest = resting(a), n = Math.round(a.used), s = Math.ceil((a.until - t) / 1000); const label = rest @@ -893,6 +988,7 @@ magpie tui # the whole app, in the t } function step() { + if (M.turns && !sent && t >= next) { sent = 1; turns(gen); } if (sent < M.n && t >= next) { sent++; request(gen); next = t + (still ? 1400 : 900); } const now = trips; trips = []; for (const tr of now) { @@ -910,7 +1006,7 @@ magpie tui # the whole app, in the t say(`${a.name} is back — ${a.why === "rate" ? "its rate limit is over" : "it gets another chance"}.`, true); } if (capQ.length && t - capAt > (capLo && !capQ[0].lo ? 700 : 2200)) show(capQ.shift()); - if (done >= M.n && !endAt) { + if (!M.turns && done >= M.n && !endAt) { endAt = t + 4200; capQ = []; show(`${done} requests answered, ${rerouted} rerouted — and not one error reached Claude Code.`); } @@ -928,7 +1024,7 @@ magpie tui # the whole app, in the t tabs.forEach((b) => b.addEventListener("click", () => reset(b.dataset.mode))); new IntersectionObserver((es) => { vis = es[0].isIntersecting; }).observe(rt); new ResizeObserver(() => layout()).observe(stage); - reset("smart"); + reset("intent"); requestAnimationFrame(frame); })();