From 2c05df52b1ff57e88d8df4d36690ee3d52f63142 Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 11 Nov 2026 15:42:27 +0800 Subject: [PATCH] gateway: a relay's 503 "no available channel" on one API sends the model to the next (equinox0253 on X) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A New API relay with Chat, Responses and Anthropic URLs has channels per API. Claude Code's /v1/messages turn for gpt-6.1-sol was relayed on the Anthropic URL (usable lists the client's own API), where the relay has no channel for a GPT and answers 503 "No available channel for model ... under group ..." (or 当前分组 ... 无可用渠道). wrongEndpoint only knew 4xx words, so the 503 reached Claude Code, and only removing the Anthropic URL helped. catalog.NoChannel recognises that 503 (and 404) in English and Chinese. Server.noChannelElsewhere, used in passthrough and forwardTranslated next to wrongEndpoint, marks the model unfit on that API and asks the next one usable gives, but only when p speaks another API; with none left the relay's word is returned and nothing is remembered. Claude models still go to Anthropic: the rule fires only on the refusal. Run (wsl-run, magpie-desktop): new TestNoChannelOnOneAPIGoesToTheNext (fake New API: 503 bodies in Claude and OpenAI shapes; GPT goes to Chat on the first ask and is not asked on Anthropic again; Claude stays on Anthropic) and TestNoChannelWithNothingElseIsTheError, red on the old code (503 reached the client), green with the fix; catalog.TestNoChannel; TestToolsThatNeedResponses* siblings; go vet catalog+gateway; go test catalog, gateway, provider (see push note). The 503 body is New API's as I know it from its source, not captured from a live relay. Not tried: a real New API relay; windows/darwin vet; GUI (no GUI change). A Claude model whose Anthropic channel is briefly down is remembered off Anthropic until magpie restarts. --- internal/catalog/catalog.go | 13 ++ internal/catalog/catalog_test.go | 17 +++ internal/gateway/gateway.go | 15 ++- internal/gateway/newapi_no_channel_test.go | 140 +++++++++++++++++++++ 4 files changed, 184 insertions(+), 1 deletion(-) create mode 100644 internal/gateway/newapi_no_channel_test.go diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go index 52257cc26..ba57308a2 100644 --- a/internal/catalog/catalog.go +++ b/internal/catalog/catalog.go @@ -2156,6 +2156,19 @@ func WrongEndpoint(status int, body []byte) bool { return false } +// NoChannel recognizes a relay (New API and its forks) answering 503 that no +// channel serves the model in the caller's group: the relay holds the model on +// some of its APIs and has no channel for it on the one asked, so another API +// of the same relay may serve it (equinox0253 on X: gpt-6.1-sol asked on a +// relay's Anthropic URL, where only its Claude models have a channel). +func NoChannel(status int, body []byte) bool { + if status != 503 && status != 404 { + return false + } + msg := strings.ToLower(string(Words(body))) + return strings.Contains(msg, "no available channel") || strings.Contains(msg, "无可用渠道") +} + // Words is an error body as its words are matched: a JSON body that // escapes what isn't ASCII as \uXXXX (Python's json.dumps does by default) // has its strings decoded and put after it, one to a line, so "用量", diff --git a/internal/catalog/catalog_test.go b/internal/catalog/catalog_test.go index 09f965c19..d8d753b01 100644 --- a/internal/catalog/catalog_test.go +++ b/internal/catalog/catalog_test.go @@ -478,3 +478,20 @@ func TestProviderAllocsGrowWithModels(t *testing.T) { t.Errorf("after Reset, Provider(openai) = %v, want the new load's m-new", ms) } } + +func TestNoChannel(t *testing.T) { + for _, c := range []struct { + status int + body string + want bool + }{ + {503, `{"type":"error","error":{"type":"new_api_error","message":"No available channel for model gpt-6.1-sol under group default (request id: 2026)"}}`, true}, + {503, `{"error":{"message":"当前分组 default 下对于模型 gpt-6.1-sol 无可用渠道 (request id: 2026)","type":"new_api_error","code":"model_not_found"}}`, true}, + {503, `{"error":{"message":"upstream overloaded"}}`, false}, + {429, `No available channel for model x`, false}, + } { + if got := NoChannel(c.status, []byte(c.body)); got != c.want { + t.Errorf("NoChannel(%d, %s) = %v", c.status, c.body, got) + } + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 27fcecd81..04be23665 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -7086,6 +7086,11 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. if res.StatusCode >= 400 { b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) msg := explained(p, model, res, b) + if s.noChannelElsewhere(p, model, proto, res.StatusCode, b) { + s.markUnfit(p.ID, model, proto) + u.RequestID = "" + return res.StatusCode, msg, false + } if wrongEndpoint(res.StatusCode, b) { s.markUnfit(p.ID, model, proto) if len(s.usable(p, model)) > 0 { @@ -8368,7 +8373,7 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to // cache, not because the model needs it: a model the vendor doesn't // serve on it (404) is asked on Chat, as before #1578 cacheOnly := to == provider.Responses && res.StatusCode == http.StatusNotFound && p.ResponsesTellsCache() - if !cacheOnly && !wrongEndpoint(res.StatusCode, b) { + if !cacheOnly && !wrongEndpoint(res.StatusCode, b) && !s.noChannelElsewhere(p, model, to, res.StatusCode, b) { return res, to, nil } s.markUnfit(p.ID, model, to) @@ -8770,6 +8775,14 @@ func badRequest(status int) bool { // reads too (#3766). func wrongEndpoint(status int, body []byte) bool { return catalog.WrongEndpoint(status, body) } +// noChannelElsewhere is whether a relay said it has no channel for model on +// proto (catalog.NoChannel) while p speaks another API that may serve it. A +// relay with channels per API (New API) answers a GPT asked on its Anthropic +// URL so, and the request goes on to the next API, as for wrongEndpoint. +func (s *Server) noChannelElsewhere(p provider.Provider, model string, proto provider.Protocol, status int, body []byte) bool { + return catalog.NoChannel(status, body) && slices.ContainsFunc(s.usable(p, model), func(o provider.Protocol) bool { return o != proto }) +} + // wrongAPINote goes after an upstream's word that the model isn't served // on the API it was asked on (wrongEndpoint), when no other API is left to // ask: the URL asked, and the APIs the vendor's list serves the model on diff --git a/internal/gateway/newapi_no_channel_test.go b/internal/gateway/newapi_no_channel_test.go new file mode 100644 index 000000000..ef9839df1 --- /dev/null +++ b/internal/gateway/newapi_no_channel_test.go @@ -0,0 +1,140 @@ +package gateway + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// New API's own words when a group has no channel for a model on the API +// asked, in the shape of the API asked (equinox0253 on X: gpt-6.1-sol on the +// relay's Anthropic URL, where only its Claude models have a channel). +const ( + newAPINoChannelClaude = `{"type":"error","error":{"type":"new_api_error","message":"No available channel for model gpt-6.1-sol under group default (request id: 20261111093000123456789)"}}` + newAPINoChannelOpenAI = `{"error":{"message":"No available channel for model claude-sonnet-4-5 under group default (request id: 20261111093000123456790)","type":"new_api_error","param":"","code":"model_not_found"}}` +) + +// newAPI serves GPTs on Chat and Responses and Claude on Anthropic's +// Messages alone, and answers anything else 503 as New API does. +type newAPI struct { + mu sync.Mutex + calls map[string]int +} + +func (f *newAPI) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + f.mu.Lock() + if f.calls == nil { + f.calls = map[string]int{} + } + gpt := strings.Contains(string(b), `"gpt-6.1-sol"`) + f.calls[r.URL.Path+map[bool]string{true: " gpt", false: " claude"}[gpt]]++ + f.mu.Unlock() + refuse := func(body string) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusServiceUnavailable) + io.WriteString(w, body) + } + switch { + case r.URL.Path == "/v1/messages" && gpt: + refuse(newAPINoChannelClaude) + case r.URL.Path != "/v1/messages" && !gpt: + refuse(newAPINoChannelOpenAI) + case r.URL.Path == "/v1/messages": + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"m1","type":"message","role":"assistant","model":"claude-sonnet-4-5","content":[],"usage":{"input_tokens":3,"output_tokens":1}}}`, + `event: content_block_start`+"\n"+`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `event: content_block_delta`+"\n"+`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"claude ok"}}`, + `event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":0}`, + `event: message_delta`+"\n"+`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}`, + `event: message_stop`+"\n"+`data: {"type":"message_stop"}`)) + case r.URL.Path == "/v1/chat/completions": + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `data: {"id":"c1","model":"gpt-6.1-sol","choices":[{"delta":{"role":"assistant","content":"gpt ok"}}]}`, + `data: {"id":"c1","choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2}}`, + `data: [DONE]`)) + case r.URL.Path == "/v1/responses": + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"r1","model":"gpt-6.1-sol"}}`, + `event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"gpt ok"}`, + `event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"r1","status":"completed","usage":{"input_tokens":9,"output_tokens":2}}}`)) + default: + http.NotFound(w, r) + } +} + +func (f *newAPI) count(k string) int { + f.mu.Lock() + defer f.mu.Unlock() + return f.calls[k] +} + +// A relay with Chat, Responses and Anthropic URLs, whose Anthropic channel +// serves Claude only: Claude Code's Messages turn for a GPT is asked on +// Anthropic first, the relay's 503 "no available channel" sends it on to +// Chat, the GPT is remembered off Anthropic, and a Claude model still goes +// to Anthropic. +func TestNoChannelOnOneAPIGoesToTheNext(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + f := &newAPI{} + up := httptest.NewServer(f) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Models: []string{"gpt-6.1-sol", "claude-sonnet-4-5"}, + Chat: up.URL + "/v1", Responses: up.URL + "/v1", Anthropic: up.URL}); err != nil { + t.Fatal(err) + } + handler := New().Handler() + ask := func(model string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(`{"model":"relay/`+model+`","max_tokens":100,"stream":true, + "messages":[{"role":"user","content":"hi"}]}`))) + return rec + } + for i := 0; i < 2; i++ { + rec := ask("gpt-6.1-sol") + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "gpt ok") { + t.Fatalf("gpt call %d: status %d: %s", i, rec.Code, rec.Body.String()) + } + } + if n := f.count("/v1/messages gpt"); n != 1 { + t.Errorf("the GPT was asked on Anthropic %d times, want once (remembered)", n) + } + rec := ask("claude-sonnet-4-5") + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "claude ok") { + t.Fatalf("claude: status %d: %s", rec.Code, rec.Body.String()) + } + if n := f.count("/v1/messages claude"); n != 1 || f.count("/v1/chat/completions claude")+f.count("/v1/responses claude") != 0 { + t.Errorf("Claude left Anthropic: %v", f.calls) + } +} + +// With no other API to ask, the relay's word reaches the client and nothing +// is remembered. +func TestNoChannelWithNothingElseIsTheError(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + f := &newAPI{} + up := httptest.NewServer(f) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Models: []string{"gpt-6.1-sol"}, Anthropic: up.URL}); err != nil { + t.Fatal(err) + } + srv := New() + rec := httptest.NewRecorder() + srv.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(`{"model":"relay/gpt-6.1-sol","max_tokens":100,"messages":[{"role":"user","content":"hi"}]}`))) + if rec.Code != 503 || !strings.Contains(rec.Body.String(), "No available channel") { + t.Fatalf("status %d: %s", rec.Code, rec.Body.String()) + } + if !srv.fits("relay", "gpt-6.1-sol", provider.Anthropic) { + t.Error("the only API was marked unfit") + } +}