diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index dc56ad6a4..9426f7acd 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -322,6 +322,7 @@ recorded as a prediction failure (`noPrediction`). - The Providers page shows a subscription account's rests in force on its row there too: `RestsUnder("@")` lists them, `providerJSON.accountRests` gives them by user in lower case (the account's own, and each model's, with `Rest.Model`, `Until`, `By` and the vendor's words, `Rest.Error`), and the row's line says which model, why and when it is back, the vendor's words beside it, with Try now lifting it by its key (`accountRestLines` in app.js). Before, only a key's rest showed there, and a WorkBuddy AI account whose model rested on a 429 "将在 … 重置" read as fine, its credits 82% left (maxleebeta on Discord; `TestRateLimitedModelListedUnderAccount`, `TestAccountRestsInProviderState`, `account-rest.test.cjs`). - A group member let go for no first content within the group's `FirstToken` (`hw.slow` in [`gateway.go`](../../internal/gateway/gateway.go), 504 "no first token in Ns", `failSlow`) doesn't rest the first time: a long prompt is slow to start anywhere. Slow again on the same account's model with no answer from it in between, and within `slowForget` (30 minutes) of its last slow start, that model rests on that account (`restSlow` in [`routing.go`](../../internal/gateway/routing.go), keyed by `restID`, `Rest.Model` set): a minute from the second time (`slowRests`), doubling each time after, up to the provider's rest cap (`RestCapOr(longestRetry)`), and never for a provider whose cap is off. Its answer clears the count (`servedCandidate`). A request its client cancelled counts nothing, as the cancel is read before `hw.slow`. The walk has a total budget, `groupBudget` (540s, under the 600s a client waits): a member asked when little of it is left gets only what is left (`hw.budgeted`), and when it runs out no further member is asked, nothing rests, and the error names the budget (504 "no member of the group answered within its 540s budget", #5113, mycf_711: nine members at 60s took 660s and the client's hang-up was told as the last member's failure; `TestGroupWalkStopsAtItsBudget`). Before it, each new request asked the stalled member first again and waited out the whole `FirstToken` (小八 on Discord: a WorkBuddy account's kimi-k3-1 and glm-5.3 stalled 58 times on the vendor's per-model token limit, 15 times in 17 minutes in one session). The same model on another account and another model on the same account are asked as before (`TestSlowStartsRestTheModelOnItsAccount`, `TestCanceledSlowStartRestsNothing`; the Routing page's story, `routing-went-on.test.cjs`). - A plugin's try that isn't the last candidate is sent with `x-magpie-fallback: 1` (`provider.FallbackHeader`, `withFallback`), so a plugin whose vendor queues the request (Qoder's 10605, CodeArts' `queue-status: queued`) answers a `busy` 503 with Retry-After and the queue's reason at once instead of waiting minutes in the queue, and the next is asked; the last candidate isn't told and waits as the vendor's client does ([provider-plugins](provider-plugins.md#whether-another-candidate-follows), `TestPluginToldAnotherFollows`). +- A Claude account's refusal worded "You've reached your Fable limit" (also "hit"; `claudeFamilyLimit`) names the family whose own limit it is, found in the model's id: that model rests on the account, its others keep being served (YsiCing on X: Opus was refused with it). "usage", "session", "weekly" or no word there is the account's. `TestClaudeNamedModelLimitRestsThatModelOnly`. - A 402 is out of credit, unless it speaks of a usage limit (`usedUpWords`) and nothing of money (`creditWords`, `insufficient_quota`): then it is out of quota, and rests only the model when the account's windows say its pool is the one used up (`pooled`). Factory answers Standard's pool used up with 402 "You've reached your weekly standard usage limit (resets in …). Switch to Droid Core …"; read as credit, it rested the account 30 minutes and its Droid Core models with it (#1979). Both the built-in's windows and the plugin's (Standard's `notModels`, Core's `models`) are held to it. As a quota rest it lasts until the time the refusal names (`resetsAfter`: "resets in 0h 19min", "resets in 2d 3h", held to `longestWritten`), else the window's end, else `quotaRest` or the provider's own `quota-rest`, and is lifted once a reading finds the window renewed (`renewed`), which a credit rest never was (`TestFactoryStandardOutLeavesCore`, `TestPaymentRequiredReadByItsWords`, `TestResetsInWords`). An account whose windows weren't read yet (a start, or a reading that failed), or whose reading holds a window of some models only (Claude's Opus, Sonnet or Fable week) with none known full, can't tell the model's pool from the account's, so it rests whole, and (`Allowance.Scoped`; `TestClaudeFableWeekRestsFableOnly`, kaitokiku on X: Claude Code's "You've hit your limit" names no window) `narrowWhenRead` waits off the request for a reading (`AwaitAllowance`, up to `allowanceWait`) and moves the rest to the model alone (`restID`, the same end) when the reading says its pool is the one used up; no reading in time, or one that says the whole account, leaves the account's rest, as does a rest lifted or made again meanwhile (#2036; `TestFactoryStandardOutLeavesCore`'s unread case, `TestResetsInWords`). The request itself isn't held for the reading: it has failed over already, and the rest's scope only matters to later requests. - Codex offers its image tool (the `image_gen` namespace, #870) to every magpie provider. When a provider other than a ChatGPT sign-in or openai.com answers a bare 400, `attempt` asks it once more without the tool (`image_tool.go`). This happens both passed through and translated. If that works, the provider is marked unfit for the tool (`tool:image_gen`) and isn't offered it again. If it doesn't, the tool is restored and the 400 stands (#949). - A turn the agent stopped with its tool call still out is replayed by the client with the call and no result, and Google's APIs turn a history whose call turn goes unanswered away with 400, every later turn of the conversation with it. The Gemini build (`buildCodeAssistSent`, which serves a Google sign-in, Vertex AI and a custom provider's Gemini API alike) answers such a call with the synthetic result the chat build pairs an interrupted turn's call with (`pairToolMessages`, #1275), right after the calls (`pairFunctionTurns`, #1560): beside the answers the client sent there, or in a user turn of its own before what the user said, since a turn mixing a `functionResponse` with text is turned away too (#1533), and so is one mixing it with an image: on Vertex AI a tool's images (Codex's view_image) go in a user turn of their own after the response (`buildCodeAssistSent`, Voo_Ler on X); a Claude model on Antigravity gets it in the one tool_result turn. A call with no id counts as answered by a response of its name. A second answer to one call is left out, with the images it carried, before the turns are built (`dropSecondAnswers`, #2262): Google refuses a call turn whose `functionResponse` count differs from its `functionCall` count, and the Chat and Messages builds already keep the first answer. The Responses build (`buildResponses`) leaves it out the same way. A call made again under the same id takes an answer of its own. A Gemini client that keeps no ids answers two calls of one function by name in their order, and each answer goes to its own call (`parseGemini`), not both to the latest. `TestGeminiDropsASecondAnswer`, `TestSecondAnswerDroppedWithItsImages`, `TestGeminiClientUnnamedCallsAnsweredInOrder`. diff --git a/internal/gateway/claude_model_limit_rest_test.go b/internal/gateway/claude_model_limit_rest_test.go new file mode 100644 index 000000000..abc743367 --- /dev/null +++ b/internal/gateway/claude_model_limit_rest_test.go @@ -0,0 +1,48 @@ +package gateway + +import ( + "net/http" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// A Claude refusal that names a model's own limit ("You've reached your +// Fable limit ... switch models with /model", YsiCing on X) rests that +// model on the account, whatever the usage reading holds or lacks: Opus +// and the rest were refused with it, though their quota was left. One that +// names no model ("You've hit your limit", "your usage limit") is still +// the account's. +func TestClaudeNamedModelLimitRestsThatModelOnly(t *testing.T) { + fresh(t) + const user = "named@example.com" + acct := func(model string) candidate { + return candidate{p: provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: user}}, model: model, rest: "claude"} + } + s := &Server{} + body := func(msg string) []byte { + return []byte(`{"type":"error","error":{"type":"rate_limit_error","message":"` + msg + `"}}`) + } + fable := acct("claude-fable-5-1") + r := s.restAfter(fable, http.StatusTooManyRequests, http.Header{}, body("Claude Code: You've reached your Fable limit. Run /usage-credits to continue or switch models with /model.")) + if r.Why != failQuota || r.Model != "claude-fable-5-1" || r.Key != fable.restID() { + t.Fatalf("rest: %+v", r) + } + for _, m := range []string{"claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-4-5"} { + if _, ok := restingOf(acct(m)); ok { + t.Fatalf("%s rests on an account whose Fable limit is reached", m) + } + } + // a model other than the one named is refused with the account's words + for _, msg := range []string{"You've hit your limit · resets 5:58am", "You've reached your usage limit."} { + o := acct("claude-opus-5-5") + if r := s.restAfter(o, http.StatusTooManyRequests, http.Header{}, body(msg)); r.Key != o.restKey() { + t.Fatalf("%q rested %+v, want the account", msg, r) + } + } + // and a limit named for another model's family is not this model's + o := acct("claude-opus-5-5") + if r := s.restAfter(o, http.StatusTooManyRequests, http.Header{}, body("You've reached your Sonnet limit.")); r.Key != o.restKey() { + t.Fatalf("Sonnet's limit rested Opus as %+v, want the account", r) + } +} diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index 3f693cf78..02e584dd8 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -1625,7 +1625,7 @@ func restOf(id string) (Rest, bool) { // quotaWords are how vendors say "out of quota" or "slow down" when their // status code doesn't: some answer 400 or 403 with it. -var quotaWords = lazyre.New(`(?i)quota|insufficient|balance|credit|billing|out of budget|budget (exceeded|exhausted)|exceeded|rate.?limit|usage.?limit|limit.?reached|hit your .*limit|limit.{0,24}resets|too many requests|overloaded|余额|额度|欠费|限流|频率|频繁|速率|套餐|用量|上限`) +var quotaWords = lazyre.New(`(?i)quota|insufficient|balance|credit|billing|out of budget|budget (exceeded|exhausted)|exceeded|rate.?limit|usage.?limit|limit.?reached|(?:hit|reached) your .*limit|limit.{0,24}resets|too many requests|overloaded|余额|额度|欠费|限流|频率|频繁|速率|套餐|用量|上限`) // quotaSaid is whether an error's words, with no status to go by, say // out of quota or slow down: quotaWords, unless they say the conversation diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 70820278e..fe989227b 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -353,7 +353,7 @@ var ( // …" (#5111, wuxiaoqiang12) — its "has been" broke the pair, and read // as a plain rate limit the key was asked again every half an hour, the // user's quota-rest never read - usedUpWords = lazyre.New(`(?i)quota|usage.?limit|out of budget|budget.{0,32}(exceeded|exhausted)|limit.?reached|hit your .*limit|limit.{0,24}resets|exceeded.*(plan|limit)|额度|用量|套餐|上限`) + usedUpWords = lazyre.New(`(?i)quota|usage.?limit|out of budget|budget.{0,32}(exceeded|exhausted)|limit.?reached|(?:hit|reached) your .*limit|limit.{0,24}resets|exceeded.*(plan|limit)|额度|用量|套餐|上限`) // rateWords: a 429 that is a short rate limit — requests or tokens per // minute — which usedUpWords took for a used-up plan ("Rate limit // exceeded", "reached"): as magpie words an upstream error, with @@ -365,7 +365,7 @@ var ( // words or not — a day's free requests, say, or a sub2api key's own // 5-hour, day or 7-day limit ("api key 7天限额已用完", sent as // rate_limit_exceeded). - plannedWords = lazyre.New(`(?i)quota|usage.?limit|hit your .*limit|limit.{0,24}resets|per.?(day|week|month)|daily|weekly|monthly|额度|用量|套餐|限额已用完`) + plannedWords = lazyre.New(`(?i)quota|usage.?limit|(?:hit|reached) your .*limit|limit.{0,24}resets|per.?(day|week|month)|daily|weekly|monthly|额度|用量|套餐|限额已用完`) // minuteWords: a 429 that names a window of a minute or less, or the // rate itself — tokens or requests per minute, TPM, RPM — which some // vendors call a quota all the same: Gemini's "You exceeded your @@ -379,7 +379,7 @@ var ( minuteWords = lazyre.New(`(?i)per.?(second|minute)|per.?(sec|min)\b|\b[rt]p[ms]\b|(token|call|request) rate limit|每分钟|每秒`) // longWords: a window longer than a minute, or a plan's own limit, // named in a 429 — what minuteWords' rate limit is not. - longWords = lazyre.New(`(?i)usage.?limit|hit your .*limit|limit.{0,24}resets|per.?(hour|day|week|month)|\bhours?\b|hourly|daily|weekly|monthly|\b[rt]p[dh]\b|额度已用|用量|套餐|限额已用完|小时|每天|每日|每周|每月`) + longWords = lazyre.New(`(?i)usage.?limit|(?:hit|reached) your .*limit|limit.{0,24}resets|per.?(hour|day|week|month)|\bhours?\b|hourly|daily|weekly|monthly|\b[rt]p[dh]\b|额度已用|用量|套餐|限额已用完|小时|每天|每日|每周|每月`) // urlWords: a link in an error, whose words are its path, not what the // vendor said: Azure's rate limit points to aka.ms/oai/quotaincrease urlWords = lazyre.New(`https?://\S+`) @@ -410,7 +410,8 @@ var ( // otherModels: a refusal that says the account's other models still // answer ("切换其他模型", "switch to the other models"): its limit is // the model's, and the model alone rests - otherModels = lazyre.New(`(?i)switch(?:ing)? to (?:the )?other models?|切换(?:到)?其他模型`) + claudeFamilyWords = lazyre.New(`(?:hit|reached) your ([a-z][a-z0-9.]*) limit`) + otherModels = lazyre.New(`(?i)switch(?:ing)? to (?:the )?other models?|切换(?:到)?其他模型`) // modelCooling is a relay that pools credentials per model saying // those of the requested model cooled down: CLIProxyAPI's 429 // model_cooldown, "All credentials for model model-a are cooling down @@ -1898,7 +1899,7 @@ func modelNamed(c candidate, why string, body []byte) bool { } words := bytes.ToLower(wordsOf(body)) name := strings.ToLower(c.model) - if namesModel(words, name) { + if namesModel(words, name) || claudeFamilyLimit(c, name, words) { return true } // a name the router prefixed (vendor/model) is said without it @@ -1908,6 +1909,29 @@ func modelNamed(c candidate, why string, body []byte) bool { return false } +// claudeFamilyLimit says a Claude account's refusal is its own limit for +// the family of model, as Claude Code words it: "You've reached your Fable +// limit. Run /usage-credits to continue or switch models with /model" +// (YsiCing on X: Opus was refused with it, its quota left). The family is +// the word between "your" and "limit", found in the model's id. The +// account-wide windows say "usage", "session", "weekly", "5-hour" +// or nothing ("You've hit your limit"), and rest the account. +func claudeFamilyLimit(c candidate, model string, words []byte) bool { + if c.p.Account == nil || c.p.Account.UsageAgent() != "claude" { + return false + } + m := claudeFamilyWords.FindSubmatch(words) + if m == nil { + return false + } + switch fam := string(m[1]); fam { + case "usage", "session", "weekly", "monthly", "daily", "hourly", "rate", "plan", "message", "credit", "credits", "free", "extra", "overage": + return false + default: + return strings.Contains(model, fam) + } +} + // namesModel says name stands in words as a whole id: not the front of a // longer one (gpt-4o in gpt-4o-mini), nor the end of one. A full stop or // colon that ends a sentence still ends the id.