yckonnnn on X uses Volcengine's pay as you go and its Agent Plan, and wants a key of each in one provider. Each plan takes its own keys at its own endpoints (/api/v3, /api/plan/v3, /api/coding/v3), and every key of a provider went to the provider's one plan, so only one kind worked. A key now may say which of its preset's Regions it is for (KeyAccount.Plan; Provider.KeyPlan for the first key, as KeyProtocol). None, or the provider's own plan, is the provider's plan, stored as none: old configs read and write as before. Presets whose plans take keys of their own (PresetDef.KeyPlans): zhipu, zai, stepfun, stepfun-cn, xiaomi, baidu-qianfan, tencent-cloud, huaweicloud, volcengine, siliconflow. Not: yylx (one key everywhere), bailian-decision (decide only), bedrock and bedrock-mantle (regions of one account). Every reader of the region or a base URL, and what it does now: - WithKey (keys.go): moves the key's copy to its plan (atKeyPlan: Chat, Responses, Anthropic, Decide, KeysURL, Website, Catalog via atRegionOf; a provider at a host of its own keeps that host) and marks it keyView. Every gateway key path goes through it: chat, Responses, Messages, count_tokens, failover, embeddings (serveRetrieval via onKeys), drawing (drawOnAccounts via perKeyBarred), key tests (test.go), key_models.go, gui/groups.go, markedKey. - perKeyBarred (gateway/fallback.go): a key whose plan's list lacks the model (PlanServing) is not asked; only when no key's plan has it. - fetch / fetchPerKey / planOnly (models.go): a mixed provider lists each key's plan, a NoList plan from its preset list with no request, pay as you go from /api/v3/models with its own key. - planMedia (PlanEmbeddings, PlanDrawers, PlanVideos): every plan's. - PlanQuotas (planquota.go): each key read at its own plan's source. - volcPlanQuotas, tencentPlanQuotas: one view per plan (planViews). - KeyBalances (balance.go): each key at its plan's host (SiliconFlow). - startVideo / videoMaker (gateway/video.go): a mixed provider starts on a key whose plan makes the model (onKeys) and names it in the id (keyMark), so the poll goes to that key's plan. - GUI: POST /api/keys/plan (SetKeyPlan, then the lists are read again); the editor keeps KeyPlan with an unchanged first key, typed() clears it with a new one; KeepSecrets, AddCopy, backup's withoutKeys carry it. - app.js: planPicker, a plan chip in each key row (the app's own menu, openProtoMenu, through pickPill, which protoPicker now shares), shown for a KeyPlans preset while the provider has several keys or the key has a plan; i18n zh, zh-TW, ja, de. A key's plan is not guessed from the key: Volcengine's keys carry nothing that says their plan. Xiaomi's tp-, Tencent's sk-tp-, MiniMax's sk-cp- and Bailian's sk-sp- are noted in code but not used. Not done: a gateway key held to some keys (videoAsker) on a mixed provider's video may pick another key; a mixed provider whose own plan has no balance source while a key's plan has one is not read; keys left out for their plan don't show in the Routing trace; StepFun's plan windows are a sign-in per site, unchanged. Credit: yckonnnn on X (tweet 2114657701305487483). Run at this commit on origin/main1bb8143b3(macOS, go1.26.8): - gofmt -l internal: clean. go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: clean. - go test -count=1 -skip TestUnreadLoginsWriteErrorsKeepCredentials ./internal/provider/ ./internal/gateway/: ok (103s, 421s). The skipped test crashes the whole provider package on main (#3632, from091153bf). - TestCoreScriptBudget: ok, budgets not raised (app.js 1,307,430 bytes). - GUI, chromium and webkit: key-*, provider*-*, add-sheet, i18n-keys, gui-de, gui-ja, gui-zh-tw (58 files): 956 of 956 pass. key-plan.test.cjs covers en, zh, zh-TW, ja and de at 420 and 1000px. Earlier, at the same change on origin/main9120acaff: - go test -timeout 45m ./...: 71 packages ok, internal/gateway and internal/gui among them. internal/provider crashed on #3632 only; run again with that one test skipped, it passed. - The whole GUI suite (node --test tests/*.test.cjs) did not finish: the disk ran out at about 319 tests and the run was stopped. Up to then the only reds were account-discovery in both engines, #3497, red on main. Broken by hand: without atKeyPlan in WithKey, TestKeyPlanEndpoints, TestKeyPlanModelList and TestKeyPlansEachToItsOwnEndpoint go red; without the planless filter in perKeyBarred the gateway test goes red; without the plan chip key-plan.test.cjs goes red. Not tried: real Volcengine (or any other vendor's) keys of two plans in one provider; the video path (startVideo with mixed plans) has no test of its own; Windows and Linux were vetted, not run.
113 lines
4.1 KiB
Go
113 lines
4.1 KiB
Go
package gateway
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// yckonnnn on X: Volcengine's pay as you go and its Agent Plan, a key of
|
|
// each in one provider. Each key is taken only at its own plan's
|
|
// endpoints, so each request with it goes there: on the first try, on
|
|
// a failover to it, and for a model only its plan has.
|
|
func TestKeyPlansEachToItsOwnEndpoint(t *testing.T) {
|
|
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
|
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
|
restingUntil.Lock()
|
|
restingUntil.m, restingUntil.note = map[string]time.Time{}, map[string]Rest{}
|
|
restingUntil.Unlock()
|
|
routed.Lock()
|
|
routed.failures = map[string]int{}
|
|
routed.Unlock()
|
|
home := map[string]string{"k-coding": "/api/coding/v3", "k-api": "/api/v3", "k-agent": "/api/plan/v3"}
|
|
var mu sync.Mutex
|
|
var seen []string
|
|
limited := map[string]bool{}
|
|
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
|
w.Header().Set("Content-Type", "application/json")
|
|
if strings.HasSuffix(r.URL.Path, "/models") {
|
|
io.WriteString(w, `{"data":[{"id":"kimi-k3"},{"id":"deepseek-v3-250324"}]}`)
|
|
return
|
|
}
|
|
var req struct {
|
|
Model string `json:"model"`
|
|
}
|
|
json.NewDecoder(r.Body).Decode(&req)
|
|
mu.Lock()
|
|
seen = append(seen, key+" "+strings.TrimSuffix(r.URL.Path, "/chat/completions")+" "+req.Model)
|
|
lim := limited[key]
|
|
mu.Unlock()
|
|
// Ark answers a key at another plan's endpoint as unknown
|
|
if strings.TrimSuffix(r.URL.Path, "/chat/completions") != home[key] {
|
|
w.WriteHeader(401)
|
|
io.WriteString(w, `{"error":{"code":"AuthenticationError","message":"the API key is invalid"}}`)
|
|
return
|
|
}
|
|
if lim {
|
|
w.WriteHeader(429)
|
|
io.WriteString(w, `{"error":{"message":"rate limited"}}`)
|
|
return
|
|
}
|
|
io.WriteString(w, `{"id":"from-`+key+`","choices":[]}`)
|
|
}))
|
|
defer up.Close()
|
|
p := provider.Provider{ID: "volc", Name: "Volc", Preset: "volcengine",
|
|
Chat: up.URL + "/api/coding/v3", Responses: up.URL + "/api/coding/v3", Anthropic: up.URL + "/api/coding",
|
|
Models: []string{"kimi-k3", "deepseek-v3-250324"},
|
|
Key: "k-coding", KeyName: "Coding",
|
|
Keys: []provider.KeyAccount{{Name: "API", Key: "k-api", Plan: "api"}, {Name: "Agent", Key: "k-agent", Plan: "agent"}}}
|
|
if err := provider.Save(p); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
s := New()
|
|
send := func(model string) (int, string, []string) {
|
|
mu.Lock()
|
|
seen = nil
|
|
mu.Unlock()
|
|
rec := httptest.NewRecorder()
|
|
body := `{"model":"volc/` + model + `","messages":[{"role":"user","content":"hi"}]}`
|
|
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(body)))
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
return rec.Code, rec.Body.String(), append([]string(nil), seen...)
|
|
}
|
|
// the plan's own key, at the plan's endpoint
|
|
if code, body, tried := send("kimi-k3"); code != 200 || !strings.Contains(body, "from-k-coding") || strings.Join(tried, ",") != "k-coding /api/coding/v3 kimi-k3" {
|
|
t.Fatalf("first: %d %s, tried %v", code, body, tried)
|
|
}
|
|
// a model pay as you go alone has: its key alone, at /api/v3
|
|
if code, body, tried := send("deepseek-v3-250324"); code != 200 || !strings.Contains(body, "from-k-api") || strings.Join(tried, ",") != "k-api /api/v3 deepseek-v3-250324" {
|
|
t.Fatalf("pay-as-you-go model: %d %s, tried %v", code, body, tried)
|
|
}
|
|
// failover: the Coding Plan key limited, the next key at its own endpoint
|
|
mu.Lock()
|
|
limited["k-coding"] = true
|
|
mu.Unlock()
|
|
if code, body, tried := send("kimi-k3"); code != 200 || !strings.Contains(body, "from-k-api") ||
|
|
strings.Join(tried, ",") != "k-coding /api/coding/v3 kimi-k3,k-api /api/v3 kimi-k3" {
|
|
t.Fatalf("failover: %d %s, tried %v", code, body, tried)
|
|
}
|
|
// and on to the Agent Plan's
|
|
mu.Lock()
|
|
limited["k-api"] = true
|
|
mu.Unlock()
|
|
code, body, tried := send("kimi-k3")
|
|
if code != 200 || !strings.Contains(body, "from-k-agent") {
|
|
t.Fatalf("second failover: %d %s, tried %v", code, body, tried)
|
|
}
|
|
for _, x := range tried {
|
|
f := strings.Fields(x)
|
|
if home[f[0]] != f[1] {
|
|
t.Errorf("key %s sent to %s", f[0], f[1])
|
|
}
|
|
}
|
|
}
|