zhipu: a GLM Coding Plan key at the pay-as-you-go endpoint is asked again at the plan's, and the provider moves there

@cleverpigo on X: "glm coding plan放在codex/chatgpt里显示余额不足没法用". The editor
showed OpenAI https://open.bigmodel.cn/... red with 429 · 余额不足或无可用资源包,
请充值。 next to a green Anthropic https://open.bigmodel.cn/api/anthropic.

Root cause: the zhipu and zai presets start on their first region, Pay as
you go, whose OpenAI URL is /api/paas/v4. The Anthropic URL is the same in
both regions, and it bills the Coding Plan when the account has one. So a
Coding Plan key left at the default works in Claude Code, while Codex goes
to /api/paas/v4 and Zhipu answers 429 code 1113 (no balance). A provider
made by pasting the paas/v4 URL hits the same wall. Nothing in the key
says which kind it is. LESSONS.md's e63fbb0e entry records that last
time only the label was changed; this commit fixes the request itself.

Fix (internal/provider/zhipu_coding.go, following RetryOneAuth):
- A 429 1113 from {open.bigmodel.cn,api.z.ai}/api/paas/v4/... is sent
  once more to /api/coding/paas/v4/.... This happens both in the gateway
  (forwardOnce, Chat) and in the editor's endpoint test (probe).
- If the coding endpoint serves it, LearnZhipuCoding moves the saved
  provider to the plan's OpenAI URL, plus the preset's /api/v1 Responses
  URL if none is set. It only does this when the provider has that one
  key and is still at the paas URL. A provider with more keys, or one
  the user has changed since, is left alone.
- If the coding endpoint refuses too, the 1113 body keeps its code, so
  the error is still classed as out of credit. Its message also names
  both URLs and says what to change: set Plan to Coding Plan (with its
  URL), or top up the pay-as-you-go balance.
- A pay-as-you-go key that has a balance never gets a 1113. It stays on
  /api/paas/v4 and is never sent to the plan's endpoint.

Tests:
- TestGLMCodingPlanKeyAtPayAsYouGo (gateway; zhipu and zai) covers:
  - the Codex /v1/responses path
  - the move
  - a second request going straight to coding
  - a payg key staying put
  - the broke key's message
- TestZhipuCodingPlanKeyTested and TestZhipuCodingBase (provider) cover:
  - a draft
  - a saved preset
  - a pasted custom provider (only Chat moves)
  - a provider with several keys (not moved)
  - payg
  - broke
  - a key the user has changed
- With the two hooks reverted, both new behaviour tests fail.

Run (sandbox HOME, pinned Go caches):
- gofmt -l: clean
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...:
  clean
- GOOS=linux go build -tags nogui and GOOS=windows go build: OK
- go test -tags nogui ./internal/provider/: ok (363s)
- go test -tags nogui -timeout 40m ./internal/gateway/: ok (1922s, on a
  machine at load ~200)

Not tried: a real Zhipu or Z.ai key. None was available, so the 1113
body and the coding endpoint's answer come from the report and the
presets, not a live call.
This commit is contained in:
yetone
2026-10-13 13:59:17 +08:00
parent 81f587d7be
commit 488569227e
6 changed files with 551 additions and 0 deletions
+1
View File
@@ -19,6 +19,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| --- | --- | --- |
| Provider | `Provider` holds the endpoint bases for each `Protocol` (Chat, Responses, Anthropic, Gemini), the keys, `Fallback`, `Routing`, `Sink`, `Affinity`, concurrency and queue limits, `Headers`, `Proxy`, models, and balance settings. `BaseAPI` is the API a custom provider's editor shows its Base URL as: the one the user picked and saved, while it has a URL, so a provider with a chat URL beside its Responses one isn't shown as OpenAI compatible after Responses was picked. Requests go by which URLs are set. A custom provider's `Gemini` URL is the base of Google's Gemini API, or of one that answers as it does (#1346): `GeminiBase` keeps it as the base (…/v1beta added to a bare host, a pasted endpoint or model list cut back), requests go to `models/{model}:streamGenerateContent?alt=sse` under it (`GeminiPath`) signed with `x-goog-api-key` (`AuthHeaders`), and its models are listed by `catalog.FetchGemini` (paged, only those serving generateContent). Factory's sign-in alone keeps its own `/generate` route and token (`FactoryGemini`). `Account` is set only for a subscription and is never saved (`json:"-"`). | [`provider.go`](../../internal/provider/provider.go) |
| Anthropic key header | A provider of the user's own on a third-party Anthropic API is sent its key as both `x-api-key` and `Authorization: Bearer` (`AuthHeaders`); Anthropic's own API, Bedrock, Azure, Vertex and every subscription account have their own and never this choice (`BothAuth` is false). Some services refuse the two together with a 401 (Aloha on Discord: "鉴权 header, x-api-key 和 Authorization 不可以同时存在"), so `Provider.AuthHeader` (`authHeader`: empty for both, `x-api-key` or `bearer`; anything else is read as empty) sends one alone, picked in the editor's Key header row (shown while `bothAuth` is true, or a custom provider's Anthropic URL is a third party's). Left at both, a 401 whose body `catalog.BothAuthRefused` tells as that refusal (it names both headers and says they can't be together, in Chinese or English) is asked once more with x-api-key alone, then Bearer alone (`RetryOneAuth`, in the gateway's `forwardOnce` and the provider test's `probe`; `catalog.fetchOne` for the model list through `listAuth`); the first not answered 401 or 403 is kept with `LearnAuthHeader`, which never changes a pick the user made. A request carrying the user's own `Authorization` or `x-api-key` header is never retried. | [`authheader.go`](../../internal/provider/authheader.go), [`test.go`](../../internal/provider/test.go), [`catalog/authheader.go`](../../internal/catalog/authheader.go), [`catalog/live.go`](../../internal/catalog/live.go) |
| GLM Coding Plan key at pay as you go | Zhipu's and Z.ai's presets offer Pay as you go first (`/api/paas/v4`) and the Coding Plan (`/api/coding/paas/v4`, Responses at `/api/v1`); both share `/api/anthropic`, which bills the plan, so a plan's key left at Pay as you go worked in Claude Code and was refused 429 code 1113 "余额不足或无可用资源包" in Codex (@cleverpigo on X). Nothing in the key tells the two apart, so a Chat request to `open.bigmodel.cn` or `api.z.ai` at `/api/paas/v4` refused 1113 is asked once more at `/api/coding/paas/v4` (`RetryZhipuCoding`, in the gateway's `forwardOnce` and the provider test's `probe`). Served there, `LearnZhipuCoding` moves a saved provider with that one key, still at that URL, to the plan's OpenAI URL (and the preset's plan Responses URL when it has none); one with other keys stays and is asked again each time. Refused there too, the 1113 body keeps its code and gets both URLs and what to change in its message (`ZhipuNoBalanceHint`). A pay-as-you-go key with a balance is never answered 1113 and never sent to the plan's endpoint. | [`zhipu_coding.go`](../../internal/provider/zhipu_coding.go), [`test.go`](../../internal/provider/test.go) |
| Extra body | `ExtraBody` (`extraBody` in providers.json, the editor's *Extra body*, #1604) is a JSON object whose fields `WithExtraBody` adds at the top level of every JSON body sent to the provider: Messages, Chat, Responses and Gemini, relayed as they came or translated, in the gateway's `forwardOnce` and in Test and Detect (`tested`). A field the body has already is kept; a name written `"!name"` replaces it. Values are put in as written, objects whole, not merged. `${sessionId}` in any string, at any depth, becomes the request's session: the agent's session header (`sessionOf`), else the id `conversationID` derives from the first user message (`magpie-` and its hash), so it stays the same through one conversation; Test and Detect send `magpie-test-` and 12 random letters, a new one each time. `model`, `stream` and the conversation (`messages`, `input`, `contents`, `system`, `systemInstruction`, `system_instruction`, `instructions`, `tools`, `ExtraBodyReserved`) are magpie's: Save refuses them with or without `!` (`ExtraBodyOK`), the editor says so as they are typed, and one written into providers.json by hand is dropped on read (`cleanExtraBody`). Not sent with it: `count_tokens`, embeddings, images, video and System One's decision model (other APIs), and a signed-in account's requests. One object goes to every API; fields for one API alone are not a thing yet. | [`extrabody.go`](../../internal/provider/extrabody.go), [`gateway.go`](../../internal/gateway/gateway.go) |
| providers.json | `Path` is `providers.json` in magpie's config folder. A read that fails returns `ErrUnreadable` and is never treated as empty. `store` writes atomically through a rename and drops the cached catalog (`catalog.Touched`). | [`provider.go`](../../internal/provider/provider.go) |
| The list | `All` merges stored providers with `Accounts()`. An entry with no URL stores the user's picks for an account. The order is `file.Order`. Reads within one request share one build (`Hold`, #746). | [`provider.go`](../../internal/provider/provider.go) |
+7
View File
@@ -3367,6 +3367,13 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid
// alone, refusing both (Aloha on Discord): asked again with one
res, err = provider.RetryOneAuth(p, req, res, func(r *http.Request) (*http.Response, error) { return p.Do(s.client, r) })
}
if err == nil && to == provider.Chat {
// a GLM Coding Plan's key at Zhipu's or Z.ai's pay-as-you-go
// endpoint, refused there for want of a balance (1113): asked at
// the plan's endpoint, and the provider moved there when it serves
// it; else the refusal says what to change (@cleverpigo on X)
res, err = provider.RetryZhipuCoding(p, req, res, func(r *http.Request) (*http.Response, error) { return p.Do(s.client, r) })
}
if err != nil {
return res, err
}
+165
View File
@@ -0,0 +1,165 @@
package gateway
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
)
// zhipuNoBalance is Zhipu's answer to a key whose account has no balance
// for the API asked, as @cleverpigo's editor showed it (429 · 余额不足…).
const zhipuNoBalance = `{"error":{"code":"1113","message":"余额不足或无可用资源包,请充值。"}}`
// glmKeys plays Zhipu's and Z.ai's OpenAI APIs: the pay-as-you-go one
// (/api/paas/v4) serves the keys with a balance, the GLM Coding Plan's
// (/api/coding/paas/v4) the plans' keys, and each refuses the others 1113.
type glmKeys struct {
mu sync.Mutex
asked []string // host + path
payg map[string]bool
plan map[string]bool
}
func (g *glmKeys) RoundTrip(r *http.Request) (*http.Response, error) {
body, _ := io.ReadAll(r.Body)
g.mu.Lock()
g.asked = append(g.asked, r.URL.Host+r.URL.Path)
g.mu.Unlock()
key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
served := false
switch {
case strings.HasPrefix(r.URL.Path, "/api/paas/v4/"):
served = g.payg[key]
case strings.HasPrefix(r.URL.Path, "/api/coding/paas/v4/"):
served = g.plan[key]
}
if !served {
return &http.Response{StatusCode: 429, Status: "429 Too Many Requests", Header: http.Header{"Content-Type": {"application/json"}},
Body: io.NopCloser(strings.NewReader(zhipuNoBalance)), Request: r}, nil
}
if gjson.GetBytes(body, "stream").Bool() {
return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": {"text/event-stream"}},
Body: io.NopCloser(strings.NewReader("data: {\"id\":\"c\",\"object\":\"chat.completion.chunk\",\"model\":\"glm-5.1\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"pong\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n")), Request: r}, nil
}
return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": {"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"id":"c","object":"chat.completion","model":"glm-5.1","choices":[{"index":0,"message":{"role":"assistant","content":"pong"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}`)), Request: r}, nil
}
func (g *glmKeys) took() []string {
g.mu.Lock()
defer g.mu.Unlock()
out := g.asked
g.asked = nil
return out
}
// A GLM Coding Plan's key on the zhipu or zai preset left at its first
// plan, Pay as you go (@cleverpigo on X: "glm coding plan放在codex里显示余额不足"):
// Claude Code works, its Anthropic endpoint being the plan's too, and
// Codex was refused 429 1113 at /api/paas/v4. Its request is asked again
// at /api/coding/paas/v4 and answered, and the provider moves to the
// plan's endpoints, so the next goes there first. A pay-as-you-go key with
// a balance stays at /api/paas/v4 and is never sent to the plan's; one
// with neither is told what to change.
func TestGLMCodingPlanKeyAtPayAsYouGo(t *testing.T) {
for _, tc := range []struct{ preset, host string }{
{"zhipu", "open.bigmodel.cn"},
{"zai", "api.z.ai"},
} {
t.Run(tc.preset, func(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
// ids of their own per plan: a refused key rests by its id
add := func(id, key string) {
t.Helper()
id = tc.preset + "-" + id
p, err := provider.FromPreset(tc.preset)
if err != nil {
t.Fatal(err)
}
if p.Chat != "https://"+tc.host+"/api/paas/v4" {
t.Fatalf("the preset's first plan is %s, not pay as you go", p.Chat)
}
p.ID, p.Name, p.Key, p.Models = id, id, key, []string{"glm-5.1"}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
add("plan", "plan-key")
add("payg", "payg-key")
add("broke", "broke-key")
fake := &glmKeys{payg: map[string]bool{"payg-key": true}, plan: map[string]bool{"plan-key": true}}
s := New()
s.client = &http.Client{Transport: fake}
ask := func(path, body string) *httptest.ResponseRecorder {
t.Helper()
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body)))
return rec
}
codex := func(id string) *httptest.ResponseRecorder {
id = tc.preset + "-" + id
return ask("/v1/responses", `{"model":"`+id+`/glm-5.1","input":"Say pong","stream":false}`)
}
stored := func(id string) provider.Provider {
t.Helper()
p, err := provider.Find(tc.preset + "-" + id)
if err != nil || p == nil {
t.Fatal(id, err)
}
return *p
}
// the plan's key: answered, by the plan's endpoint
if rec := codex("plan"); rec.Code != 200 {
t.Fatalf("plan key: %d %s", rec.Code, rec.Body)
}
if got := fake.took(); len(got) != 2 || got[0] != tc.host+"/api/paas/v4/chat/completions" || got[1] != tc.host+"/api/coding/paas/v4/chat/completions" {
t.Errorf("plan key asked %v, want pay as you go then the plan's endpoint", got)
}
p := stored("plan")
if p.Chat != "https://"+tc.host+"/api/coding/paas/v4" || p.Responses != "https://"+tc.host+"/api/v1" || p.Anthropic != "https://"+tc.host+"/api/anthropic" {
t.Errorf("plan provider not moved to the Coding Plan's endpoints: chat %s responses %s anthropic %s", p.Chat, p.Responses, p.Anthropic)
}
// and from then on the plan's own endpoints are asked first
if rec := ask("/v1/chat/completions", `{"model":"`+tc.preset+`-plan/glm-5.1","messages":[{"role":"user","content":"Say pong"}]}`); rec.Code != 200 {
t.Fatalf("plan key again: %d %s", rec.Code, rec.Body)
}
if got := fake.took(); len(got) != 1 || got[0] != tc.host+"/api/coding/paas/v4/chat/completions" {
t.Errorf("plan key asked %v the second time, want the plan's endpoint alone", got)
}
// a pay-as-you-go key with a balance: where it was
if rec := codex("payg"); rec.Code != 200 {
t.Fatalf("payg key: %d %s", rec.Code, rec.Body)
}
if got := fake.took(); len(got) != 1 || got[0] != tc.host+"/api/paas/v4/chat/completions" {
t.Errorf("payg key asked %v, want pay as you go alone", got)
}
if p := stored("payg"); p.Chat != "https://"+tc.host+"/api/paas/v4" || p.Responses != "" {
t.Errorf("payg provider moved: chat %s responses %s", p.Chat, p.Responses)
}
// neither: refused, saying what to change
rec := codex("broke")
if rec.Code == 200 {
t.Fatalf("broke key answered: %s", rec.Body)
}
msg := gjson.Get(rec.Body.String(), "error.message").String()
for _, want := range []string{"余额不足", "https://" + tc.host + "/api/paas/v4", "https://" + tc.host + "/api/coding/paas/v4", "Coding Plan", "top up"} {
if !strings.Contains(msg, want) {
t.Errorf("broke key's error %q doesn't say %q", msg, want)
}
}
if p := stored("broke"); p.Chat != "https://"+tc.host+"/api/paas/v4" {
t.Errorf("broke provider moved to %s", p.Chat)
}
})
}
}
+4
View File
@@ -477,6 +477,10 @@ func probe(ctx context.Context, p Provider, proto Protocol, url string, body []b
// a vendor that takes one of the two key headers alone
res, err = RetryOneAuth(p, req, res, func(r *http.Request) (*http.Response, error) { return p.Do(http.DefaultClient, r) })
}
if err == nil && proto == Chat {
// a GLM Coding Plan's key at Zhipu's pay-as-you-go endpoint
res, err = RetryZhipuCoding(p, req, res, func(r *http.Request) (*http.Response, error) { return p.Do(http.DefaultClient, r) })
}
r.Millis = time.Since(start).Milliseconds()
if err != nil {
r.Error = strings.TrimPrefix(err.Error(), "Post \""+url+"\": ")
+184
View File
@@ -0,0 +1,184 @@
package provider
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
)
// A GLM Coding Plan (Zhipu's, on open.bigmodel.cn, and Z.ai's, on
// api.z.ai) is served at its own OpenAI endpoint, /api/coding/paas/v4,
// while the pay-as-you-go API is /api/paas/v4. Both share the Anthropic
// endpoint (/api/anthropic), which bills the plan when the account has one,
// so a plan's key given the zhipu or zai preset at its first plan, Pay as
// you go, works in Claude Code and is refused in Codex: the pay-as-you-go
// endpoint answers it 429, code 1113 "余额不足或无可用资源包,请充值。" (the
// account has no balance), as @cleverpigo on X and kkgg on Discord found.
// Nothing in the key tells the two apart, so a 1113 at /api/paas/v4 is
// asked again at /api/coding/paas/v4: served there, the key is a plan's,
// and the provider is moved to the plan's endpoints (LearnZhipuCoding).
// Refused there too, the refusal says what each endpoint said and what to
// change. A pay-as-you-go key with a balance is never answered 1113 and
// stays where it is.
// zhipuPaygPath and zhipuCodingPath are the pay-as-you-go and the Coding
// Plan's OpenAI paths on both hosts.
const (
zhipuPaygPath = "/api/paas/v4"
zhipuCodingPath = "/api/coding/paas/v4"
)
// zhipuHost is a host that serves a GLM Coding Plan beside pay as you go.
func zhipuHost(host string) bool {
switch strings.ToLower(host) {
case "open.bigmodel.cn", "api.z.ai":
return true
}
return false
}
// ZhipuCodingBase is the GLM Coding Plan's OpenAI base for base, Zhipu's or
// Z.ai's pay-as-you-go one (https://open.bigmodel.cn/api/paas/v4 →
// https://open.bigmodel.cn/api/coding/paas/v4), and whether base is one.
func ZhipuCodingBase(base string) (string, bool) {
b := strings.TrimRight(strings.TrimSpace(base), "/")
if !zhipuHost(HostOf(b)) || basePath(b) != zhipuPaygPath {
return "", false
}
return strings.TrimSuffix(b, zhipuPaygPath) + zhipuCodingPath, true
}
// zhipuNoBalance is Zhipu's refusal of a key whose account has no balance
// for the API asked: 429 with code 1113.
func zhipuNoBalance(status int, b []byte) bool {
return status == http.StatusTooManyRequests && ErrorType(b) == "1113"
}
// RetryZhipuCoding hands on res, the answer to req; or, when req went to
// Zhipu's or Z.ai's pay-as-you-go OpenAI API and was refused for want of a
// balance (1113), the answer to req asked again at the GLM Coding Plan's
// endpoint when that one serves it — remembering it for p
// (LearnZhipuCoding) — else res with what to change added to its message.
// do sends a request as req was sent.
func RetryZhipuCoding(p Provider, req *http.Request, res *http.Response, do func(*http.Request) (*http.Response, error)) (*http.Response, error) {
if res == nil || res.StatusCode != http.StatusTooManyRequests || req.GetBody == nil || !zhipuHost(req.URL.Host) {
return res, nil
}
rest, ok := strings.CutPrefix(req.URL.Path, zhipuPaygPath+"/")
if !ok {
return res, nil
}
b, _ := io.ReadAll(io.LimitReader(res.Body, 64<<10))
res.Body.Close()
res.Body = io.NopCloser(bytes.NewReader(b))
if !zhipuNoBalance(res.StatusCode, b) {
return res, nil
}
body, err := req.GetBody()
if err != nil {
return res, nil
}
again := req.Clone(req.Context())
again.Body = body
again.URL.Path = zhipuCodingPath + "/" + rest
again.URL.RawPath = ""
from := req.URL.Scheme + "://" + req.URL.Host + zhipuPaygPath
coding := req.URL.Scheme + "://" + req.URL.Host + zhipuCodingPath
got, err := do(again)
said := ""
if err != nil {
said = err.Error()
} else if got.StatusCode < 300 {
LearnZhipuCoding(p, from)
return got, nil
} else {
gb, _ := io.ReadAll(io.LimitReader(got.Body, 64<<10))
got.Body.Close()
said = fmt.Sprintf("%d %s", got.StatusCode, APIError(gb, got.Status))
}
b = withMessage(b, apiError(b, res.Status)+" — "+ZhipuNoBalanceHint(from, coding, said))
res.Body = io.NopCloser(bytes.NewReader(b))
res.ContentLength = int64(len(b))
if res.Header == nil {
res.Header = http.Header{}
}
res.Header.Set("Content-Length", strconv.Itoa(len(b)))
return res, nil
}
// ZhipuNoBalanceHint says what a 1113 at the pay-as-you-go endpoint from
// means when the Coding Plan's endpoint coding didn't serve the key either
// (said is what it answered), and what to change.
func ZhipuNoBalanceHint(from, coding, said string) string {
site := "open.bigmodel.cn"
if HostOf(from) == "api.z.ai" {
site = "z.ai"
}
return fmt.Sprintf("this key's account has no balance for the pay-as-you-go API (%s), and the GLM Coding Plan's endpoint (%s) didn't serve it either (%s). "+
"A GLM Coding Plan's key: set the provider's Plan to Coding Plan (its OpenAI URL %s), and check the plan is active at %s. "+
"A pay-as-you-go key: top up the account's balance at %s",
from, coding, said, coding, site, site)
}
// withMessage is the JSON error body b with its message set to msg, the
// rest (Zhipu's code 1113) as it was.
func withMessage(b []byte, msg string) []byte {
var v map[string]any
if json.Unmarshal(b, &v) != nil || v == nil {
v = map[string]any{}
}
e, _ := v["error"].(map[string]any)
if e == nil {
e = map[string]any{}
v["error"] = e
}
e["message"] = msg
out, err := json.Marshal(v)
if err != nil {
return b
}
return out
}
// LearnZhipuCoding moves provider p, whose key the pay-as-you-go endpoint
// from refused and the GLM Coding Plan's served, to the plan's endpoints:
// its OpenAI URL, and the plan's Responses URL when it has none (the zhipu
// and zai presets' Coding Plan region). Only a provider with that one key
// still at from is moved: one with other keys may hold pay-as-you-go keys
// too, and one the user has moved since is theirs. Each of its requests
// is then asked again at the plan's endpoint as this one was.
func LearnZhipuCoding(p Provider, from string) {
coding, ok := ZhipuCodingBase(from)
if !ok || p.ID == "" || p.Account != nil {
return
}
learnMu.Lock()
defer learnMu.Unlock()
f, err := read()
if err != nil {
return
}
for i := range f.Providers {
q := &f.Providers[i]
if q.ID != p.ID {
continue
}
if q.Account != nil || len(q.Keys) > 0 || q.Key != p.Key || strings.TrimRight(q.Chat, "/") != strings.TrimRight(from, "/") {
return
}
q.Chat = coding
if pr := Preset(q.Preset); pr != nil && q.Responses == "" {
for _, r := range pr.Regions {
if r.ID == "coding" && r.Chat == coding {
q.Responses = r.Responses
}
}
}
_ = store(f)
return
}
}
+190
View File
@@ -0,0 +1,190 @@
package provider
import (
"context"
"io"
"net/http"
"strings"
"testing"
)
// The pay-as-you-go OpenAI bases of Zhipu and Z.ai have the Coding Plan's
// beside them; nothing else does, the plan's own base included.
func TestZhipuCodingBase(t *testing.T) {
for base, want := range map[string]string{
"https://open.bigmodel.cn/api/paas/v4": "https://open.bigmodel.cn/api/coding/paas/v4",
"https://open.bigmodel.cn/api/paas/v4/": "https://open.bigmodel.cn/api/coding/paas/v4",
"https://api.z.ai/api/paas/v4": "https://api.z.ai/api/coding/paas/v4",
"https://open.bigmodel.cn/api/coding/paas/v4": "",
"https://open.bigmodel.cn/api/anthropic": "",
"https://api.z.ai/api/v1": "",
"https://relay.example.com/api/paas/v4": "",
"https://open.bigmodel.cn.example/api/paas/v4": "",
} {
got, ok := ZhipuCodingBase(base)
if got != want || ok != (want != "") {
t.Errorf("%s: %q %v, want %q", base, got, ok, want)
}
}
}
// zhipuFake answers as Zhipu's OpenAI APIs do: plan keys at the Coding
// Plan's endpoint, pay-as-you-go keys at /api/paas/v4, anything else 429
// 1113 (its Anthropic endpoint too). asked is each chat completions path
// it was asked.
type zhipuFake struct {
payg, plan map[string]bool
asked []string
}
func (z *zhipuFake) RoundTrip(r *http.Request) (*http.Response, error) {
if r.Body != nil {
io.Copy(io.Discard, r.Body)
}
if strings.HasSuffix(r.URL.Path, "/models") {
return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": {"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"data":[{"id":"glm-5.1"}]}`)), Request: r}, nil
}
if strings.HasSuffix(r.URL.Path, "/chat/completions") {
z.asked = append(z.asked, r.URL.Host+r.URL.Path)
}
key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
served := strings.HasPrefix(r.URL.Path, "/api/paas/v4/") && z.payg[key] || strings.HasPrefix(r.URL.Path, "/api/coding/paas/v4/") && z.plan[key]
if !served {
return &http.Response{StatusCode: 429, Status: "429 Too Many Requests", Header: http.Header{"Content-Type": {"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"error":{"code":"1113","message":"余额不足或无可用资源包,请充值。"}}`)), Request: r}, nil
}
return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": {"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"id":"c","choices":[{"index":0,"message":{"role":"assistant","content":"hi"}}]}`)), Request: r}, nil
}
// The editor's endpoint check (@cleverpigo's screenshot: OpenAI "429 ·
// 余额不足或无可用资源包,请充值。" beside a green Anthropic): a GLM Coding
// Plan's key at the pay-as-you-go endpoint is answered at the plan's, and
// a saved provider with that one key moves there. A provider with other
// keys, one the user moved since, a pay-as-you-go key and a key with
// neither stay where they are, the last told what to change.
func TestZhipuCodingPlanKeyTested(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
fake := &zhipuFake{payg: map[string]bool{"payg": true}, plan: map[string]bool{"plan": true, "plan2": true}}
was := http.DefaultClient.Transport
http.DefaultClient.Transport = fake
t.Cleanup(func() { http.DefaultClient.Transport = was })
openai := func(p Provider) Result {
t.Helper()
for _, r := range p.Test(context.Background()) {
if r.Protocol == Chat {
return r
}
}
t.Fatalf("%s: no OpenAI result", p.ID)
return Result{}
}
mk := func(id, key string) Provider {
p, err := FromPreset("zhipu")
if err != nil {
t.Fatal(err)
}
p.ID, p.Name, p.Key, p.Models = id, id, key, []string{"glm-5.1"}
return p
}
stored := func(id string) Provider {
t.Helper()
p, err := Find(id)
if err != nil || p == nil {
t.Fatal(id, err)
}
return *p
}
// a draft not yet saved: answered, nothing to move
fake.asked = nil
if r := openai(mk("draft", "plan")); !r.OK {
t.Errorf("draft with a plan key: %+v", r)
}
if len(fake.asked) != 2 || fake.asked[1] != "open.bigmodel.cn/api/coding/paas/v4/chat/completions" {
t.Errorf("draft asked %v", fake.asked)
}
// saved, the preset at Pay as you go: moved to the Coding Plan
plan := mk("glm", "plan")
if err := Save(plan); err != nil {
t.Fatal(err)
}
if r := openai(plan); !r.OK {
t.Errorf("plan key: %+v", r)
}
if p := stored("glm"); p.Chat != "https://open.bigmodel.cn/api/coding/paas/v4" || p.Responses != "https://open.bigmodel.cn/api/v1" {
t.Errorf("plan provider at chat %s responses %s, want the Coding Plan's", p.Chat, p.Responses)
}
// pasted by hand, the Anthropic URL and pay as you go's: the OpenAI URL
// alone moves, nothing added
custom := Provider{ID: "mine", Name: "mine", Key: "plan", Models: []string{"glm-5.1"},
Chat: "https://open.bigmodel.cn/api/paas/v4/", Anthropic: "https://open.bigmodel.cn/api/anthropic"}
if err := Save(custom); err != nil {
t.Fatal(err)
}
if r := openai(custom); !r.OK {
t.Errorf("custom plan key: %+v", r)
}
if p := stored("mine"); p.Chat != "https://open.bigmodel.cn/api/coding/paas/v4" || p.Responses != "" || p.Anthropic != "https://open.bigmodel.cn/api/anthropic" {
t.Errorf("custom provider at chat %s responses %s anthropic %s", p.Chat, p.Responses, p.Anthropic)
}
// a provider with other keys, which may be pay as you go's: answered,
// not moved
multi := mk("multi", "plan")
multi.Keys = []KeyAccount{{Name: "other", Key: "payg"}}
if err := Save(multi); err != nil {
t.Fatal(err)
}
if r := openai(stored("multi")); !r.OK {
t.Errorf("multi plan key: %+v", r)
}
if p := stored("multi"); p.Chat != "https://open.bigmodel.cn/api/paas/v4" {
t.Errorf("provider with other keys moved to %s", p.Chat)
}
// a pay-as-you-go key: never sent to the plan's endpoint
payg := mk("payg", "payg")
if err := Save(payg); err != nil {
t.Fatal(err)
}
fake.asked = nil
if r := openai(payg); !r.OK {
t.Errorf("payg key: %+v", r)
}
if len(fake.asked) != 1 || fake.asked[0] != "open.bigmodel.cn/api/paas/v4/chat/completions" {
t.Errorf("payg key asked %v", fake.asked)
}
if p := stored("payg"); p.Chat != "https://open.bigmodel.cn/api/paas/v4" {
t.Errorf("payg provider moved to %s", p.Chat)
}
// neither: refused, saying both URLs and what to change
broke := mk("broke", "broke")
if err := Save(broke); err != nil {
t.Fatal(err)
}
r := openai(broke)
if r.OK || r.Status != 429 {
t.Fatalf("broke key: %+v", r)
}
for _, want := range []string{"余额不足", "https://open.bigmodel.cn/api/paas/v4", "Plan to Coding Plan", "https://open.bigmodel.cn/api/coding/paas/v4", "top up"} {
if !strings.Contains(r.Error, want) {
t.Errorf("broke key's error %q doesn't say %q", r.Error, want)
}
}
if p := stored("broke"); p.Chat != "https://open.bigmodel.cn/api/paas/v4" {
t.Errorf("broke provider moved to %s", p.Chat)
}
// moved by the user since the request went out: theirs
LearnZhipuCoding(Provider{ID: "payg", Key: "other-key"}, "https://open.bigmodel.cn/api/paas/v4")
if p := stored("payg"); p.Chat != "https://open.bigmodel.cn/api/paas/v4" {
t.Errorf("provider with another key now moved to %s", p.Chat)
}
}