diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 8abc664aa..188f357ed 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -8739,7 +8739,7 @@ func failTo(w http.ResponseWriter, a *keptAlive, proto provider.Protocol, status func streamError(w http.ResponseWriter, proto provider.Protocol, model string, status int, msg string) { sw := newSSEWriter(w) sw.begun = true - text := saysPassing(status, msg) + text := saysPassing(status, saysBusy(status, msg)) ev := Event{Kind: KError, Text: text, Status: status} overflow := tooLong(status, msg) if overflow { @@ -8789,6 +8789,36 @@ func saysPassing(status int, msg string) string { return fmt.Sprintf("%s (%d: you can retry your request)", msg, status) } +// busyWords are how a relay says, under a request-error status, that it +// was busy for a moment: "Concurrency limit exceeded for account, please +// retry later" and "Too many pending requests, please retry later" in a +// 400, "The service is temporarily unavailable. Please retry later." with +// no status at all (#2372, the texts zminds' Pi sessions recorded). +var busyWords = regexp.MustCompile(`(?i)concurrency limit|too many (pending|concurrent|in-?flight) requests|temporarily unavailable|(please )?(retry|try again) later|并发|稍后(再)?重?试`) + +// spentWords say an account is out of what it pays for, which no retry +// clears: Pi's own deny-list keeps such a text from being asked again, and +// magpie doesn't tell it otherwise. +var spentWords = regexp.MustCompile(`(?i)quota|insufficient|balance|credit|billing|budget|usage.?limit|余额|额度|欠费|套餐|用量`) + +// saysBusy is msg, a request error's text (400, 409, 422), with "you can +// retry your request" said in it when its words say only that the relay +// was busy: Pi, which judges an error by its text alone, ended the turn +// on each, where a moment later the same request was answered (#2372). +// A request's own fault, an account out of credit and a conversation too +// long are left as they were said. +func saysBusy(status int, msg string) string { + switch status { + case http.StatusBadRequest, http.StatusConflict, http.StatusUnprocessableEntity: + default: + return msg + } + if !busyWords.MatchString(msg) || spentWords.MatchString(msg) || tooLong(status, msg) || passingSaid.MatchString(msg) { + return msg + } + return msg + " (busy: you can retry your request)" +} + // writeError answers in the client's own error shape. func writeError(w http.ResponseWriter, proto provider.Protocol, status int, msg string) int { return writeErrorSaid(w, proto, status, msg, nil, nil) @@ -8835,6 +8865,8 @@ func writeErrorSaid(w http.ResponseWriter, proto provider.Protocol, status int, case status == 529: typ = "overloaded_error" } + // a relay busy for a moment, said so Pi asks again (#2372) + msg = saysBusy(status, msg) if tooLong(status, msg) { // said the way the client's own API says it, so the agent // compacts the conversation and tries again rather than stopping diff --git a/internal/gateway/stream_error_passing_test.go b/internal/gateway/stream_error_passing_test.go index 68fb3ade3..8378f9533 100644 --- a/internal/gateway/stream_error_passing_test.go +++ b/internal/gateway/stream_error_passing_test.go @@ -169,3 +169,87 @@ func TestStreamErrorByteCapInEveryShape(t *testing.T) { } } } + +// A relay busy for a moment says so under a request-error status, and Pi, +// judging by the text alone, ended the turn on it after one try, where the +// same request a moment later was answered (#2372, zminds: Pi 1.3.0 +// stopped on "Concurrency limit exceeded for account, please retry later" +// and retried once the text said 503). The words that say it may be asked +// again are said in it; a request's own fault, an account out of credit +// and a conversation too long are left as they were. +func TestBusyRelaySaysItPasses(t *testing.T) { + for _, c := range []struct { + status int + msg string + }{ + {400, "Concurrency limit exceeded for account, please retry later"}, + {400, "Too many pending requests, please retry later"}, + {400, "The service is temporarily unavailable. Please retry later."}, + {422, "当前并发请求过多,请稍后重试"}, + } { + if got := saysBusy(c.status, c.msg); !piRetries(got) || !strings.HasPrefix(got, c.msg) { + t.Errorf("%d %q is told %q", c.status, c.msg, got) + } + // in a stream already begun too + if got := saysPassing(c.status, saysBusy(c.status, c.msg)); !piRetries(got) { + t.Errorf("in a stream, %d %q is told %q", c.status, c.msg, got) + } + } + for _, c := range []struct { + status int + msg string + }{ + {400, "Invalid request parameters"}, + {400, "insufficient balance, please retry later after topping up"}, + {400, "Monthly usage limit reached, try again later"}, + {400, "prompt is too long: please retry later with fewer messages"}, + {401, "invalid api key, please retry later"}, + {404, "model not found"}, + {400, "Upstream rate limit exceeded, please retry later"}, + } { + if got := saysBusy(c.status, c.msg); got != c.msg { + t.Errorf("%d %q is told %q", c.status, c.msg, got) + } + } +} + +// Through a group whose every member is busy, before anything was sent +// and in a stream already begun: what reaches the agent is a text Pi asks +// again for. The relay's body is the one zminds' mock answered with. +func TestGroupBusyRelaySaysItPasses(t *testing.T) { + old := retryPause + retryPause = time.Millisecond + t.Cleanup(func() { retryPause = old }) + const busy = `{"message":"Concurrency limit exceeded for account, please retry later","type":"upstream_error"}` + for _, stream := range []bool{false, true} { + t.Run(map[bool]string{false: "whole", true: "stream"}[stream], func(t *testing.T) { + fresh(t) + a := &scripted{replies: []reply{{400, "application/json", busy}}} + b := &scripted{replies: []reply{{400, "application/json", busy}}} + scriptedOn(t, "a", provider.Chat, a) + scriptedOn(t, "b", provider.Chat, b) + if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + s := New() + body := `{"model":"group/g","messages":[{"role":"user","content":"hi"}]}` + if stream { + body = `{"model":"group/g","stream":true,"messages":[{"role":"user","content":"hi"}]}` + } + _, raw := postAs(t, s, "", body) + if a.n == 0 || b.n == 0 { + t.Fatalf("the group didn't ask both members (%d, %d): %s", a.n, b.n, raw) + } + var said string + for _, line := range append([]string{raw}, strings.Split(raw, "\n")...) { + d, _ := strings.CutPrefix(line, "data: ") + if m := gjson.Get(d, "error.message"); m.Exists() { + said = m.String() + } + } + if !strings.Contains(said, "Concurrency limit exceeded") || !piRetries(said) { + t.Fatalf("the agent is told %q, which Pi doesn't ask again for: %s", said, raw) + } + }) + } +}