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.
@@ -165,8 +165,8 @@ The number of its kind (0 for none):
It answers 0
No intent matches. Rules without an intent and the group’s usual order decide.
No answer within 8 s
Treated 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 n
A failure, for example when a reasoning model spends its 512 tokens thinking and answers nothing.
-
Any failure
That 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 n
No 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 timeout
That 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 words
Not 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.
@@ -229,7 +229,7 @@ The number of its kind (0 for none):
Answer cache
10 min, per classifier + intents + message; in memory
Turn decisions kept
24 h after the conversation’s last request; in memory
Message sent
Up to 4,000 characters; longer is first 3,000 + last 1,000
-
Classifier request
temperature 0, max_tokens 512, not streamed
+
Classifier request
temperature 0, max_tokens 2048, the least reasoning the model has, not streamed
Intent length
Up to 200 characters; spaces collapsed, compared without case
Outgrown
At 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.
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);
})();