provider: a model's test asks the account or key routing sends it to (#4992)
On a provider with several accounts or keys whose models differ (a magpie-newapi pool, a relay whose keys sit in different groups), "测试模型", the right-click test and the provider's Test asked the first account or key. A model that only another account serves failed (grok-4.7: 503 "no available channel") while real requests were answered, because the gateway's perKeyEvery passes over accounts and keys the user set not to serve the model (AccountModels, #474) and accounts whose own list lacks it. The test path had none of that. Cause: the choice lived in the gateway only (perKeyEvery and accountsOn in gateway/fallback.go), so the test had nothing to share. keySeeing checked the key's list but not AccountModels. Change: - internal/provider/route_accounts.go: AccountsOn, AccountsFor and KeysFor are the routing choice. The code moved there from perKeyEvery and accountsOn, and the gateway's caps are passed in as a held func. - gateway/fallback.go: perKeyEvery and accountsOn call it. They behave as before. - test.go: - testOne (the model test and the right-click test) runs as AccountsFor's first account. A model barred on every account is not asked; it says so. - The provider's Test picks key and model together (testWith), then the account that serves the model (routedTo). - The log row names the account asked (loggedAs). - keySeeing and testModel take keys from KeysFor and AccountServes. - detect.go: detectOne, a sibling, asks each model with keySeeing's key. Before, it asked the endpoint's first key. - Not changed: AskSystemOne's decision model still asks the provider's own account. Tests (internal/provider/test_account_route_test.go), on a two-account fake plugin and a relay that answers one key:model: - TestModelTestAsksTheAccountThatServesIt - TestModelTestPassesAnAccountWhoseListLacksIt - TestProviderTestAsksAnAccountThatServesItsModel - TestModelTestUsesTheKeyServingIt - TestModelTestBarredModelIsNotAsked - TestDetectModelsUsesTheKeyServingIt All six are red on origin/maine932cd258(test file alone): "Bearer a@fake /v1/responses" 503, sk-a asked m-b, and so on. All six are green after. Run on mote: - go test -count=1 -timeout 45m ./internal/provider ./internal/gateway: ok one932cd258. After the rebase ontod9f63dfee: go vet, the whole of internal/provider, and internal/gateway -run "Fallback|PerKey|Account|Key|Cap|Spend", all ok. - go vet, GOOS=linux -tags nogui go vet, GOOS=windows go vet for both packages; gofmt -l clean. - node --test with the GUI files that test models (model-test-as, model-test-one, model-test-stop, model-test-why, test-models-key-hint): 60/60, Chromium and WebKit. They fake /api, so they don't reach this change. Broken by hand: - `|| true` on Lists in AccountsFor: TestModelTestPassesAnAccountWhoseListLacksIt and the gateway's TestCodexProviderListsEveryAccountsModels go red. - The AccountServes case in KeysFor turned off: TestModelTestUsesTheKeyServingIt goes red. The gateway goes through the shared code. Not tried: - A real newapi pool or a real multi-account sign-in. - Usage and spend caps are not applied to a test (held is nil). - The Windows and Linux runs. - The full suite was started on mote after the push, under suite.lock. Reported-by: scutken Co-authored-by: xiejiayu <scut_ken@qq.com> Co-authored-by: Jackzigen <zigenhan@gmail.com>
This commit is contained in:
co-authored by
xiejiayu
Jackzigen
parent
d9f63dfee8
commit
5c5160c940
@@ -77,7 +77,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
| Last served | `served.json` records when each account, plan or key last answered, shown as `lastServedAt` (#570) on `/v1/magpie/quotas` and on the Usage page's own cards (`Quotas` → `cardsServed`, this computer's cards only, the caches left alone). The Usage page and the tray panel show the last-answered account in full, and a menu bar card that follows the account in use (`codex|*`) takes the one that answered within the last hour, else `InUseLogin`'s guess, else the one that answered last at all (a plugin's accounts, #1516) (`trayInUseCard`; okingkee on X: A spent, B answering, the menu bar stayed on A). `NoteServed` calls `OnServedMoved` when a provider's answers move to another account or key, and `SwitchLogin` after a switch, so the menu bar reads its cards again at once. | [`served.go`](../../internal/provider/served.go), [`trayusage.go`](../../internal/gui/trayusage.go) |
|
||||
| Partners | Services that pay to be listed first in the add sheet, under a heading of their own ("Partners · magpie's sponsors"). The list is `site/partners.js`, served at `usemagpie.ai/api/partners`: a change reaches users with a deploy, not a release. `Partners` never waits: it returns what was fetched last and fetches again behind the call on a process's first ask, whatever the kept list's age, and hourly after (10 minutes after a failure), keeping the list in `partners.json` in the cache folder. The magpie serving the gateway fetches it when it starts and whenever it is due, asked for or not (`KeepPartnersFresh`), so an app left open on another page still learns of a partner added. The file also says when the last fetch started (`tried`) and, when it failed, why (`error`, logged once until a fetch gets the list again), so a list that stops changing tells a fetch that fails from one that never came back (`tried` after `at`, no error) and from none asked (#3362). Each entry is checked again on every read (`validPartners`): its own id, never a built-in preset's, a name, an endpoint, https only, at most 12; what only magpie's presets may set (a decision API, no key, a user endpoint) is cleared. Its logo is fetched through `FetchIcon` and kept as an uploaded icon, used as it is while its `iconUrl` stays the same; the prune after a save of `providers.json` (`pruneIcons`) leaves the logos of the partners listed now (`keptPartnerIcons`), as it leaves a plugin's. A partner is a preset to the rest of magpie (`Preset`, `FromPreset`, the editor), and one no longer listed still is to the providers added from it (`Seen`), without the sponsored mark. The window lists a partner in the languages it names (`langs`) only and shows its tagline in the page's language (`notes`, else `en`). `MAGPIE_PARTNERS` points it elsewhere, `off` lists none; tests list none unless they name a list. How often each listed partner was shown, opened (its row, its key page) and added is counted per UTC day (`CountPartner`, capped at 20 of each and 5 adds, kept in `partner-counts.json` in the cache folder) and sent with the next day's stats event as `magpie partner` events (`internal/stats`); nothing is counted with the stats or their usage part off. A listed partner the add sheet (or the TUI's, or `magpie providers presets`) hasn't shown yet is new (`NoticePartners` keeps those shown, as `noticed` in `partners.json`, whatever the stats); the window's add button carries a small dot for it, with its name in the title, until the sheet shows it. | [`partners.go`](../../internal/provider/partners.go), [`partner_events.go`](../../internal/provider/partner_events.go), [`site/partners.js`](../../site/partners.js) |
|
||||
| Local servers | A preset of `KindLocal` (Ollama, LM Studio, oMLX, MLX-Serve) is at its server's default port on this machine. Another address — a port, or another computer — is given in the window's editor, in its Server address field, shown first above the key and never folded (a folded one read as an LM Studio whose base URL can't be changed, mengxiangziyou on X), or in the TUI (asked on adding, `w` after); on the command line with `address=` (`atAddress` in `providers_cli.go`: every URL moves, from the preset's when the provider was saved with none, and `address=` alone puts a local server back at its preset's), or the URLs themselves (`url=`, `anthropic=`, `responses=`). `AtAddress` replaces only each URL's scheme, host and port, each API keeping its path; `AddressOf` is the address an editor starts from. The window sends the URLs moved only when the address was changed, so a Save doesn't move URLs set apart (another app's import). A provider of the user's own (no preset) has `w` in the TUI too: each base URL it has is asked in turn, typed in as it is, Enter alone keeping one (`customURLsAsk`). | [`local_address.go`](../../internal/provider/local_address.go), [`providers_cli.go`](../../internal/cli/providers_cli.go) |
|
||||
| Protocol detection | Works out which of Chat, Responses, Anthropic Messages and Gemini generateContent a base URL speaks when a provider is added. Each is asked at the URL as it takes it (`DetectBase`); Gemini's at the `…/v1beta` beside a typed `…/v1` or bare host, a Gemini model from the list picked for it, with the key in `x-goog-api-key` (#1346). Each API is asked with a model that chats, if the list has one; an embedding or rerank model (`catalog.ServesOf`) is asked only on Chat's URL, at its `/embeddings` or `/rerank` with the smallest body and no extra body, as the gateway's `retrieve` asks it, and the other APIs say why they weren't asked (heatonz on Discord: a vendor of only those detected nothing, asked to chat; `TestDetectEmbeddingOnly`). A saved provider whose list has nothing to chat with tests on such a model (`testModel`, `TestTestEmbeddingOnly`), and its editor and the add form's Fetch models say the models need no pick (`retrieval` in the list's answer and the provider's JSON, `provider-retrieval-only.test.cjs`). Detection, endpoint tests and model tests share `probe`, which adds `anthropic-version` only for Anthropic Messages; OpenAI probes omit that default so a relay that refuses it can answer. A model's test that the vendor turns away with its word that the model is served on another API (`catalog.WrongEndpoint`, the gateway's words) asks the next API the provider has a URL for, as the gateway's `usable` takes it (the model's picked or listed API, else each API it isn't named-only on), with a key that sees the model there (`keySeeing`); that API's answer is the model's, and with none left, or every one saying it, the first stays. As Codex the next API is asked with Codex's headers, as the gateway sends them on Responses and Chat; as Claude Code it isn't, since the gateway sends Claude Code's on Messages alone (#3766, `TestTestModelsMovesToTheAPIServingIt`, `TestTestModelsKeepsAModelOnItsAPI`, `TestTestModelsAsAClientMovesAsTheGatewayDoes`). User-supplied headers still apply through `Sign`. The editor asks with the form as it stands, before any Save (#1545): the URL, key and models typed (`picked`, else the saved picks, else the vendor list); a key not typed again is the saved provider's, or for an unsaved copy the copied one's (`copyOf`). The probe writes nothing and adds no provider, and the route stays behind `magpie web`'s key. An endpoint or model test fails fast and can be stopped (RIck on Discord: 测试模型 took long to fail and couldn't be cancelled): a probe on magpie's own client that has no connection in `connectWait` (10s) fails then (`connecting`, an httptrace `GotConn`), and a host that couldn't be reached (no connection, DNS, refused, a bad certificate) fails the run's other models at once (`withUnreached`, `TestTestModelsUnreachedHostFailsOnce`); a stream that breaks off before an answer is a failure. While a test runs its Test models and endpoints' Test read Stop, which aborts the window's request and posts `provider/teststop` with the test's `run`, ending the vendor's request on the server too (`testRuns` in [`providers.go`](../../internal/gui/providers.go), since WebView2 doesn't end the request when a fetch is aborted; `TestProviderTestStops`, `model-test-stop.test.cjs`). | [`detect.go`](../../internal/provider/detect.go), [`test.go`](../../internal/provider/test.go) |
|
||||
| Protocol detection | Works out which of Chat, Responses, Anthropic Messages and Gemini generateContent a base URL speaks when a provider is added. Each is asked at the URL as it takes it (`DetectBase`); Gemini's at the `…/v1beta` beside a typed `…/v1` or bare host, a Gemini model from the list picked for it, with the key in `x-goog-api-key` (#1346). Each API is asked with a model that chats, if the list has one; an embedding or rerank model (`catalog.ServesOf`) is asked only on Chat's URL, at its `/embeddings` or `/rerank` with the smallest body and no extra body, as the gateway's `retrieve` asks it, and the other APIs say why they weren't asked (heatonz on Discord: a vendor of only those detected nothing, asked to chat; `TestDetectEmbeddingOnly`). A saved provider whose list has nothing to chat with tests on such a model (`testModel`, `TestTestEmbeddingOnly`), and its editor and the add form's Fetch models say the models need no pick (`retrieval` in the list's answer and the provider's JSON, `provider-retrieval-only.test.cjs`). A model's test (Test models, a model's right-click, `magpie provider test`) asks the account or key a request for it goes to: `provider.AccountsFor` and `provider.KeysFor` ([`route_accounts.go`](../../internal/provider/route_accounts.go)), which the gateway's `perKeyEvery` routes by too, its usage and spend caps aside (one the user lets serve it, `AccountModels`; whose own list or plan has it, `Account.Lists`, `PlanServing`, `Serving`; in the user's order, `AccountsOn`), so a pool whose accounts list different models (a newapi plugin's) asks the one whose list has it, and one every account is barred from isn't asked. The provider's Test picks each endpoint's model from every account's and asks it of the account that serves it (`routedTo`), and with keys the first key with a model of its own to test (`testWith`). The request log's row names the account asked (`loggedAs`; #4992, `TestModelTestAsksTheAccountThatServesIt`). Detection, endpoint tests and model tests share `probe`, which adds `anthropic-version` only for Anthropic Messages; OpenAI probes omit that default so a relay that refuses it can answer. A model's test that the vendor turns away with its word that the model is served on another API (`catalog.WrongEndpoint`, the gateway's words) asks the next API the provider has a URL for, as the gateway's `usable` takes it (the model's picked or listed API, else each API it isn't named-only on), with a key that sees the model there (`keySeeing`); that API's answer is the model's, and with none left, or every one saying it, the first stays. As Codex the next API is asked with Codex's headers, as the gateway sends them on Responses and Chat; as Claude Code it isn't, since the gateway sends Claude Code's on Messages alone (#3766, `TestTestModelsMovesToTheAPIServingIt`, `TestTestModelsKeepsAModelOnItsAPI`, `TestTestModelsAsAClientMovesAsTheGatewayDoes`). User-supplied headers still apply through `Sign`. The editor asks with the form as it stands, before any Save (#1545): the URL, key and models typed (`picked`, else the saved picks, else the vendor list); a key not typed again is the saved provider's, or for an unsaved copy the copied one's (`copyOf`). The probe writes nothing and adds no provider, and the route stays behind `magpie web`'s key. An endpoint or model test fails fast and can be stopped (RIck on Discord: 测试模型 took long to fail and couldn't be cancelled): a probe on magpie's own client that has no connection in `connectWait` (10s) fails then (`connecting`, an httptrace `GotConn`), and a host that couldn't be reached (no connection, DNS, refused, a bad certificate) fails the run's other models at once (`withUnreached`, `TestTestModelsUnreachedHostFailsOnce`); a stream that breaks off before an answer is a failure. While a test runs its Test models and endpoints' Test read Stop, which aborts the window's request and posts `provider/teststop` with the test's `run`, ending the vendor's request on the server too (`testRuns` in [`providers.go`](../../internal/gui/providers.go), since WebView2 doesn't end the request when a fetch is aborted; `TestProviderTestStops`, `model-test-stop.test.cjs`). | [`detect.go`](../../internal/provider/detect.go), [`test.go`](../../internal/provider/test.go) |
|
||||
| A pasted curl command | A curl command from a vendor's docs pasted into a custom provider's Base URL or API key fills the editor in (@mark_li21 on X). `curlOf` reads it as a shell would (lines joined by `\`, cmd's `^` or PowerShell's backtick; `curl.exe`; quotes and escapes), and takes: the API its URL's endpoint names (`…/chat/completions` Chat, `…/messages` Anthropic Messages, `…/responses` Responses) with the base URL before it, spelled as that API wants it (`respellURL`: Anthropic at its root, `/v1` after a bare host); the key from `Authorization: Bearer`, `x-api-key` or `api-key`, unless it only stands for one (`$OPENAI_API_KEY`, `${X}`, `%X%`, `<token>`, `YOUR_API_KEY`), when the key's box is left empty and focused; and the `model` of its JSON body, added to a new provider's models (a saved one's picks are left alone, since adding to none would narrow what it serves). A preset's editor takes only the key. A note (`editorError`, kind `note`) says what was taken, a placeholder like `{WorkspaceId}` left in the URL, and a URL with no known endpoint. Text that isn't a curl command pastes as before, several keys included. Tested on the docs' own examples (`fixtures/curl`). | [`app.js`](../../internal/gui/assets/app.js) (`curlOf`, `fromCurl`), [`provider-curl-paste.test.cjs`](../../internal/gui/tests/provider-curl-paste.test.cjs) |
|
||||
|
||||
## Remote magpie
|
||||
|
||||
+64
-106
@@ -336,143 +336,101 @@ func keepAtOnce(n int, out, aside []candidate) ([]candidate, []candidate) {
|
||||
}
|
||||
|
||||
// accountsOn are the accounts of p (signed in: p.Account) a request may
|
||||
// take, in the user's order: the one signed in to, unless the user paused
|
||||
// it for the others on (#263), then the others on; kept signed in to an
|
||||
// account of the user's choosing, the one signed in to stands at its own
|
||||
// place in the order, not first (#524). A search API that signs in as a
|
||||
// plugin's provider takes its accounts so too (search_signin.go).
|
||||
// take, in the user's order (provider.AccountsOn). A search API that
|
||||
// signs in as a plugin's provider takes its accounts so too
|
||||
// (search_signin.go).
|
||||
func accountsOn(p provider.Provider, model string) []candidate {
|
||||
also := p.AlsoOn()
|
||||
var all []candidate
|
||||
if len(also) == 0 || !p.OwnPaused() {
|
||||
all = append(all, candidate{p: p, model: model, rest: p.ID})
|
||||
}
|
||||
for i, q := range also {
|
||||
all = append(all, candidate{p: q, model: model, rest: p.ID + "@" + q.Account.User, rank: i + 1})
|
||||
}
|
||||
if ranks := p.LoginRanks(); ranks != nil {
|
||||
at := func(c candidate) int {
|
||||
if r, ok := ranks[strings.ToLower(c.p.Account.User)]; ok {
|
||||
return r
|
||||
}
|
||||
return len(ranks)
|
||||
}
|
||||
slices.SortStableFunc(all, func(a, b candidate) int { return at(a) - at(b) })
|
||||
for i := range all {
|
||||
all[i].rank = i
|
||||
}
|
||||
for _, a := range p.AccountsOn() {
|
||||
all = append(all, accountCandidate(p, a, model, nil))
|
||||
}
|
||||
return all
|
||||
}
|
||||
|
||||
// accountCandidate is a of p's accounts as a candidate for model.
|
||||
func accountCandidate(p provider.Provider, a provider.AccountOn, model string, capped *capHold) candidate {
|
||||
rest := p.ID
|
||||
if !a.Own {
|
||||
rest += "@" + a.Account.User
|
||||
}
|
||||
return candidate{p: a.Provider, model: model, rest: rest, rank: a.Rank, capped: capped}
|
||||
}
|
||||
|
||||
// keyCandidate is k of p's keys as a candidate for model.
|
||||
func keyCandidate(p provider.Provider, k provider.KeyOn, model string, capped *capHold) candidate {
|
||||
rest := p.ID
|
||||
if k.Of > 1 {
|
||||
rest += "#" + provider.KeyID(k.Key)
|
||||
}
|
||||
return candidate{p: p.WithKey(k.KeyAccount), model: model, rest: rest, rank: k.Rank, capped: capped}
|
||||
}
|
||||
|
||||
// perKeyEvery is perKeyBarred with every account or key routed over, the
|
||||
// provider's AtOnce aside.
|
||||
// provider's AtOnce aside. Which accounts or keys take the model, and in
|
||||
// what order, is provider.AccountsFor and provider.KeysFor, which a
|
||||
// model's test takes them from too (#4992); the usage and spend caps are
|
||||
// the gateway's own.
|
||||
func perKeyEvery(p provider.Provider, model string, from provider.Protocol) (out, aside, left, barred []candidate) {
|
||||
if _, off := provider.ModelDisabled(p.ID, model); off || provider.DisabledUnknown() {
|
||||
return nil, nil, nil, nil // the user disabled it (#1867): never planned, a fallback no more than the model asked
|
||||
}
|
||||
if p.Account != nil {
|
||||
all := accountsOn(p, model)
|
||||
all = slices.DeleteFunc(all, func(c candidate) bool {
|
||||
if p.AccountServes(c.p.Account.User, model) {
|
||||
return false
|
||||
}
|
||||
barred = append(barred, c)
|
||||
return true
|
||||
})
|
||||
// an account at its usage cap is used up for routing until the
|
||||
// window it filled renews: never tried, so groups, fallbacks and
|
||||
// the other accounts take the request (provider/account_caps.go);
|
||||
// so is a Codex account at 100% set not to spend its credits
|
||||
// (provider/codex_credits.go)
|
||||
all = slices.DeleteFunc(all, func(c candidate) bool {
|
||||
h := capHeld(p, c.p, model, time.Now())
|
||||
if h == nil {
|
||||
return false
|
||||
now := time.Now()
|
||||
caps := map[int]*capHold{}
|
||||
on, unlisted, off := p.AccountsFor(model, func(a provider.AccountOn) bool {
|
||||
h := capHeld(p, a.Provider, model, now)
|
||||
if h != nil {
|
||||
caps[a.Rank] = h
|
||||
}
|
||||
c.capped = h
|
||||
barred = append(barred, c)
|
||||
return true
|
||||
return h != nil
|
||||
})
|
||||
// an account whose plan lacks the model (a Free one behind a Plus)
|
||||
// would only answer 400; it is tried only when none lists it
|
||||
// (by the vendor's own id: an account's list names its models by
|
||||
// theirs, not by one the user lists one by)
|
||||
own := p.OwnModelID(model)
|
||||
for _, c := range all {
|
||||
if c.p.Account.Lists(own) {
|
||||
out = append(out, c)
|
||||
} else {
|
||||
left = append(left, c)
|
||||
}
|
||||
for _, a := range on {
|
||||
out = append(out, accountCandidate(p, a, model, nil))
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return all, nil, nil, barred
|
||||
for _, a := range unlisted {
|
||||
left = append(left, accountCandidate(p, a, model, nil))
|
||||
}
|
||||
for _, a := range off {
|
||||
barred = append(barred, accountCandidate(p, a, model, caps[a.Rank]))
|
||||
}
|
||||
return out, nil, left, barred
|
||||
}
|
||||
keys := p.KeysOn()
|
||||
serves := p.Serving(model) // the lists read once, not once a key (@NetRozee on X)
|
||||
// a key on a plan of its own whose models leave this one out
|
||||
// (KeyAccount.Plan): the Agent Plan's key is never sent the pay as
|
||||
// you go's deepseek-v4-1-flash-261017, while a key whose plan has it
|
||||
// can take it (yckonnnn on X)
|
||||
planHas := p.PlanServing(model)
|
||||
var unlisted, planless []candidate
|
||||
var noURL provider.Protocol
|
||||
for i, k := range keys {
|
||||
q := p.WithKey(k)
|
||||
if len(q.Speaks()) == 0 && !q.DecidesModel(model) {
|
||||
if noURL == "" {
|
||||
noURL = k.Protocol
|
||||
}
|
||||
continue // made for a protocol this provider has no endpoint for
|
||||
// a key at the spend cap set on it is used up for routing until the
|
||||
// period renews: never tried, so the other keys and the fallbacks
|
||||
// take the request (provider/key_spend.go)
|
||||
now := time.Now()
|
||||
spends := map[int]*capHold{}
|
||||
on, unlisted, off, noURL := p.KeysFor(model, func(k provider.KeyOn) bool {
|
||||
h := spendHeld(p, k.KeyAccount, now)
|
||||
if h != nil {
|
||||
spends[k.Rank] = h
|
||||
}
|
||||
rest := p.ID
|
||||
if len(keys) > 1 {
|
||||
rest += "#" + provider.KeyID(k.Key)
|
||||
}
|
||||
if !p.AccountServes(provider.KeyID(k.Key), model) {
|
||||
barred = append(barred, candidate{p: q, model: model, rest: rest, rank: i})
|
||||
continue
|
||||
}
|
||||
// a key at the spend cap set on it is used up for routing until
|
||||
// the period renews: never tried, so the other keys and the
|
||||
// fallbacks take the request (provider/key_spend.go)
|
||||
if h := spendHeld(p, k, time.Now()); h != nil {
|
||||
barred = append(barred, candidate{p: q, model: model, rest: rest, rank: i, capped: h})
|
||||
continue
|
||||
}
|
||||
if !planHas(k) {
|
||||
planless = append(planless, candidate{p: q, model: model, rest: rest, rank: i})
|
||||
continue
|
||||
}
|
||||
if !serves(k) {
|
||||
// the vendor lists the model to another key only
|
||||
unlisted = append(unlisted, candidate{p: q, model: model, rest: rest, rank: i})
|
||||
continue
|
||||
}
|
||||
out = append(out, candidate{p: q, model: model, rest: rest, rank: i})
|
||||
return h != nil
|
||||
})
|
||||
for _, k := range off {
|
||||
barred = append(barred, keyCandidate(p, k, model, spends[k.Rank]))
|
||||
}
|
||||
if len(out) == 0 {
|
||||
out, unlisted = unlisted, nil // no key lists it: try them all the same
|
||||
}
|
||||
if len(out) == 0 {
|
||||
// no key's plan has it as magpie knows the plans: a model the
|
||||
// vendor added since, tried on them all the same. Else a key
|
||||
// whose plan lacks it is never asked, not even after the others
|
||||
// refused it: its endpoint has no such model either
|
||||
out = planless
|
||||
}
|
||||
if len(out) == 0 && len(barred) > 0 {
|
||||
if len(on) == 0 && len(barred) > 0 {
|
||||
return nil, nil, nil, barred
|
||||
}
|
||||
if len(out) == 0 {
|
||||
if len(on) == 0 {
|
||||
// every key is set to a protocol the provider has no URL for (or
|
||||
// it has none on): the provider as it is, on the URLs it has,
|
||||
// marked so Routing says so rather than sending it there quietly
|
||||
return []candidate{{p: p, model: model, rest: p.ID, noURL: noURL}}, nil, nil, nil
|
||||
}
|
||||
for _, k := range on {
|
||||
out = append(out, keyCandidate(p, k, model, nil))
|
||||
}
|
||||
var rest []candidate
|
||||
for _, k := range unlisted {
|
||||
rest = append(rest, keyCandidate(p, k, model, nil))
|
||||
}
|
||||
sort.SliceStable(out, func(i, j int) bool { return keyFit(out[i].p, model, from) < keyFit(out[j].p, model, from) })
|
||||
pool := out[:0:0]
|
||||
for _, c := range out {
|
||||
@@ -482,7 +440,7 @@ func perKeyEvery(p provider.Provider, model string, from provider.Protocol) (out
|
||||
aside = append(aside, c)
|
||||
}
|
||||
}
|
||||
return pool, aside, unlisted, barred
|
||||
return pool, aside, rest, barred
|
||||
}
|
||||
|
||||
// keyFit ranks how well a key suits a request, best first: 0 fits, 1 needs
|
||||
|
||||
@@ -165,9 +165,14 @@ func (q Provider) detectOne(proto Protocol, m string, wait time.Duration) (Detec
|
||||
d.Error = "no model to try: type one the vendor serves"
|
||||
return d, nil
|
||||
}
|
||||
k, ok := q.keyFor(proto)
|
||||
// the key a request for m goes to (keySeeing, #4992): a relay whose
|
||||
// keys are each kept for some models is asked m with one that serves it
|
||||
k, ok := q.keySeeing(proto, m)
|
||||
if !ok {
|
||||
d.Error = "no key is on for this endpoint"
|
||||
if _, any := q.keyFor(proto); any {
|
||||
d.Error = "no key that's on for this endpoint serves this model"
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
if proto != Chat {
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Which of a provider's accounts or keys a model goes to. The gateway's
|
||||
// routing (gateway/fallback.go, perKeyEvery) and magpie's own test of a
|
||||
// model (test.go) both take them from here, so a test asks the account
|
||||
// or key a real request would: a pool whose accounts list different
|
||||
// models tested every one of them with its first account, and a model
|
||||
// only another account serves failed a test the gateway answered (#4992,
|
||||
// scutken).
|
||||
|
||||
// AccountOn is one of a signed-in provider's accounts a request may take:
|
||||
// Own is the one the agent is signed in to, Rank its place in the user's
|
||||
// order.
|
||||
type AccountOn struct {
|
||||
Provider
|
||||
Own bool
|
||||
Rank int
|
||||
}
|
||||
|
||||
// AccountsOn are the accounts of p (signed in: p.Account) a request may
|
||||
// take, in the user's order: the one signed in to, unless the user paused
|
||||
// it for the others on (#263), then the others on; kept signed in to an
|
||||
// account of the user's choosing, the one signed in to stands at its own
|
||||
// place in the order, not first (#524).
|
||||
func (p Provider) AccountsOn() []AccountOn {
|
||||
also := p.AlsoOn()
|
||||
var all []AccountOn
|
||||
if len(also) == 0 || !p.OwnPaused() {
|
||||
all = append(all, AccountOn{Provider: p, Own: true})
|
||||
}
|
||||
for i, q := range also {
|
||||
all = append(all, AccountOn{Provider: q, Rank: i + 1})
|
||||
}
|
||||
if ranks := p.LoginRanks(); ranks != nil {
|
||||
at := func(a AccountOn) int {
|
||||
if r, ok := ranks[strings.ToLower(a.Account.User)]; ok {
|
||||
return r
|
||||
}
|
||||
return len(ranks)
|
||||
}
|
||||
slices.SortStableFunc(all, func(a, b AccountOn) int { return at(a) - at(b) })
|
||||
for i := range all {
|
||||
all[i].Rank = i
|
||||
}
|
||||
}
|
||||
return all
|
||||
}
|
||||
|
||||
// AccountsFor are p's accounts on (AccountsOn) as routing takes them for
|
||||
// model: out, those it goes over; left, those whose own list (their plan)
|
||||
// leaves the model out, tried only after them; barred, those the user set
|
||||
// not to serve it (AccountModels, #474), then those held reports held
|
||||
// back (the gateway's usage caps; nil holds none). An account whose list
|
||||
// lacks the model would only answer 400, so it is in out only when no
|
||||
// account lists it (by the vendor's own id: an account's list names its
|
||||
// models by theirs, not by one the user lists one by).
|
||||
func (p Provider) AccountsFor(model string, held func(AccountOn) bool) (out, left, barred []AccountOn) {
|
||||
all := slices.DeleteFunc(p.AccountsOn(), func(a AccountOn) bool {
|
||||
if p.AccountServes(a.Account.User, model) {
|
||||
return false
|
||||
}
|
||||
barred = append(barred, a)
|
||||
return true
|
||||
})
|
||||
if held != nil {
|
||||
all = slices.DeleteFunc(all, func(a AccountOn) bool {
|
||||
if !held(a) {
|
||||
return false
|
||||
}
|
||||
barred = append(barred, a)
|
||||
return true
|
||||
})
|
||||
}
|
||||
own := p.OwnModelID(model)
|
||||
for _, a := range all {
|
||||
if a.Account.Lists(own) {
|
||||
out = append(out, a)
|
||||
} else {
|
||||
left = append(left, a)
|
||||
}
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return all, nil, barred
|
||||
}
|
||||
return out, left, barred
|
||||
}
|
||||
|
||||
// KeyOn is one of a provider's keys on, at its place among them (Rank),
|
||||
// of how many it has on (Of).
|
||||
type KeyOn struct {
|
||||
KeyAccount
|
||||
Rank, Of int
|
||||
}
|
||||
|
||||
// KeysFor are p's keys on as routing takes them for model: out, those it
|
||||
// goes over; unlisted, those the vendor lists the model to no key of
|
||||
// (tried after out, or as out when no key lists it); barred, those the
|
||||
// user set not to serve it (AccountModels, #474) and those held reports
|
||||
// held back (the gateway's spend caps; nil holds none). A key on a plan
|
||||
// of its own whose models leave this one out (KeyAccount.Plan) is never
|
||||
// asked while another can be: only when no key's plan has it, a model
|
||||
// the vendor added since, are they out. A key made for a protocol p has
|
||||
// no endpoint for is in none of them; noURL is the first such key's.
|
||||
func (p Provider) KeysFor(model string, held func(KeyOn) bool) (out, unlisted, barred []KeyOn, noURL Protocol) {
|
||||
keys := p.KeysOn()
|
||||
serves := p.Serving(model) // the lists read once, not once a key (@NetRozee on X)
|
||||
// the Agent Plan's key is never sent the pay as you go's
|
||||
// deepseek-v4-1-flash-261017, while a key whose plan has it can take
|
||||
// it (yckonnnn on X)
|
||||
planHas := p.PlanServing(model)
|
||||
var planless []KeyOn
|
||||
for i, k := range keys {
|
||||
q := p.WithKey(k)
|
||||
if len(q.Speaks()) == 0 && !q.DecidesModel(model) {
|
||||
if noURL == "" {
|
||||
noURL = k.Protocol
|
||||
}
|
||||
continue // made for a protocol this provider has no endpoint for
|
||||
}
|
||||
ko := KeyOn{KeyAccount: k, Rank: i, Of: len(keys)}
|
||||
switch {
|
||||
case !p.AccountServes(keyID(k.Key), model):
|
||||
barred = append(barred, ko)
|
||||
case held != nil && held(ko):
|
||||
barred = append(barred, ko)
|
||||
case !planHas(k):
|
||||
planless = append(planless, ko)
|
||||
case !serves(k):
|
||||
// the vendor lists the model to another key only
|
||||
unlisted = append(unlisted, ko)
|
||||
default:
|
||||
out = append(out, ko)
|
||||
}
|
||||
}
|
||||
if len(out) == 0 {
|
||||
out, unlisted = unlisted, nil // no key lists it: try them all the same
|
||||
}
|
||||
if len(out) == 0 {
|
||||
// no key's plan has it as magpie knows the plans: a model the
|
||||
// vendor added since, tried on them all the same. Else a key
|
||||
// whose plan lacks it is never asked, not even after the others
|
||||
// refused it: its endpoint has no such model either
|
||||
out = planless
|
||||
}
|
||||
return out, unlisted, barred, noURL
|
||||
}
|
||||
+107
-18
@@ -51,8 +51,7 @@ func (p Provider) Test(ctx context.Context) []Result {
|
||||
if client := testClient(ctx); client != "" {
|
||||
// the one endpoint that agent's requests go to
|
||||
proto := clientProto(client, p.Speaks())
|
||||
q, ok := p.keyFor(proto)
|
||||
model := p.testModel(q, proto)
|
||||
q, model, ok := p.testWith(proto)
|
||||
if why := p.TestsAs(client); why != "" {
|
||||
return []Result{{Protocol: proto, Model: model, Error: why}}
|
||||
}
|
||||
@@ -63,14 +62,18 @@ func (p Provider) Test(ctx context.Context) []Result {
|
||||
return []Result{{Protocol: proto, Error: zenPublicNone}}
|
||||
}
|
||||
url, body := tiny(q, proto, UpstreamName(p, model))
|
||||
ctx, b := q.tested(ctx, url, asClient(client, proto, body))
|
||||
ctx, b := q.tested(p.loggedAs(ctx, q), url, asClient(client, proto, body))
|
||||
return []Result{probe(ctx, q, proto, url, b, model, testWait)}
|
||||
}
|
||||
if p.isClaudeAccount() {
|
||||
return []Result{p.testClaude(ctx, p.testModel(p, Anthropic))}
|
||||
model := p.testModel(p, Anthropic)
|
||||
q := p.routedTo(model)
|
||||
return []Result{q.testClaude(p.loggedAs(ctx, q), model)}
|
||||
}
|
||||
if p.testsTranslated() {
|
||||
return []Result{p.testTranslated(ctx, p.testModel(p, CodeAssist))}
|
||||
model := p.testModel(p, CodeAssist)
|
||||
q := p.routedTo(model)
|
||||
return []Result{q.testTranslated(p.loggedAs(ctx, q), model)}
|
||||
}
|
||||
var out []Result
|
||||
for _, proto := range p.Speaks() {
|
||||
@@ -80,8 +83,7 @@ func (p Provider) Test(ctx context.Context) []Result {
|
||||
// on Gemini, and such a model by its own test (TestModel)
|
||||
continue
|
||||
}
|
||||
q, ok := p.keyFor(proto)
|
||||
model := p.testModel(q, proto)
|
||||
q, model, ok := p.testWith(proto)
|
||||
if !ok {
|
||||
out = append(out, Result{Protocol: proto, Model: model, Error: "no key is on for this endpoint"})
|
||||
continue
|
||||
@@ -92,7 +94,7 @@ func (p Provider) Test(ctx context.Context) []Result {
|
||||
continue
|
||||
}
|
||||
url, body := tiny(q, proto, UpstreamName(p, model))
|
||||
ctx, b := q.tested(ctx, url, body)
|
||||
ctx, b := q.tested(p.loggedAs(ctx, q), url, body)
|
||||
out = append(out, probe(ctx, q, proto, url, b, model, testWait))
|
||||
}
|
||||
if len(out) == 0 && p.zenPublic() {
|
||||
@@ -407,6 +409,16 @@ func (p Provider) testOne(ctx context.Context, model string) Result {
|
||||
if why := p.TestsAs(client); why != "" {
|
||||
return Result{Protocol: clientProto(client, p.Speaks()), Model: model, Error: why}
|
||||
}
|
||||
// the account a request for it goes to, not the pool's first: one
|
||||
// the user lets serve it whose own list has it, as routing takes it
|
||||
// (AccountsFor; #4992, scutken: a newapi pool's grok-4.7, served by
|
||||
// its third account alone, was asked of the first and failed 503 "no
|
||||
// available channel" while real requests were answered)
|
||||
acct, ok := p.accountFor(model)
|
||||
if !ok {
|
||||
return Result{Model: model, Error: "every account that's on is set not to serve this model"}
|
||||
}
|
||||
ctx, p = p.loggedAs(ctx, acct), acct
|
||||
if p.isClaudeAccount() {
|
||||
return p.testClaude(ctx, model)
|
||||
}
|
||||
@@ -513,25 +525,97 @@ func (p Provider) testOne(ctx context.Context, model string) Result {
|
||||
return r
|
||||
}
|
||||
|
||||
// keySeeing is p with the key a test of model on proto goes with: one made
|
||||
// for that API, else one made for any, that sees the model. A provider
|
||||
// without keys is left as it is.
|
||||
// keySeeing is p with the key a test of model on proto goes with: of
|
||||
// the keys routing takes the model to (KeysFor: one the user lets serve
|
||||
// it, whose plan and list have it), one made for that API, else one made
|
||||
// for any. A provider without keys is left as it is.
|
||||
func (p Provider) keySeeing(proto Protocol, model string) (Provider, bool) {
|
||||
keys := p.KeysOn()
|
||||
if len(keys) == 0 {
|
||||
if len(p.KeysOn()) == 0 {
|
||||
return p, true
|
||||
}
|
||||
serves := p.Serving(model)
|
||||
keys, _, _, _ := p.KeysFor(model, nil)
|
||||
for _, want := range []Protocol{proto, ""} {
|
||||
for _, k := range keys {
|
||||
if k.Protocol == want && serves(k) {
|
||||
return p.WithKey(k), true
|
||||
if k.Protocol == want {
|
||||
return p.WithKey(k.KeyAccount), true
|
||||
}
|
||||
}
|
||||
}
|
||||
return p, false
|
||||
}
|
||||
|
||||
// testWith is the key or account an endpoint's test goes with, and the
|
||||
// model it asks: the first key on made for proto, else for any, with a
|
||||
// model of its to test there (one the user lets it serve, AccountModels),
|
||||
// else the first such key with none; a provider without keys, with the
|
||||
// model picked from every account's, as the account that serves it
|
||||
// (routedTo). ok is false when no key is on for proto.
|
||||
func (p Provider) testWith(proto Protocol) (Provider, string, bool) {
|
||||
keys := p.KeysOn()
|
||||
if len(keys) == 0 {
|
||||
model := p.testModel(p, proto)
|
||||
return p.routedTo(model), model, true
|
||||
}
|
||||
var first Provider
|
||||
found := false
|
||||
for _, want := range []Protocol{proto, ""} {
|
||||
for _, k := range keys {
|
||||
if k.Protocol != want {
|
||||
continue
|
||||
}
|
||||
q := p.WithKey(k)
|
||||
if model := p.testModel(q, proto); model != "" {
|
||||
return q, model, true
|
||||
}
|
||||
if !found {
|
||||
first, found = q, true
|
||||
}
|
||||
}
|
||||
}
|
||||
if found {
|
||||
return first, "", true
|
||||
}
|
||||
return p, "", false
|
||||
}
|
||||
|
||||
// accountFor is p as the account of its accounts on a request for model
|
||||
// goes to first (AccountsFor); ok is false when the user set every one
|
||||
// not to serve it. A provider of keys is left as it is.
|
||||
func (p Provider) accountFor(model string) (Provider, bool) {
|
||||
if p.Account == nil {
|
||||
return p, true
|
||||
}
|
||||
out, _, _ := p.AccountsFor(model, nil)
|
||||
if len(out) == 0 {
|
||||
return p, false
|
||||
}
|
||||
return out[0].Provider, true
|
||||
}
|
||||
|
||||
// routedTo is q, the key or account an endpoint's test goes with, as the
|
||||
// account a request for model goes to: the model is picked from every
|
||||
// account's on, and asked of one that serves it (#4992). With no model,
|
||||
// or none that may serve it, q is left as it is.
|
||||
func (q Provider) routedTo(model string) Provider {
|
||||
if model == "" {
|
||||
return q
|
||||
}
|
||||
if a, ok := q.accountFor(model); ok {
|
||||
return a
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
// loggedAs is ctx with its test's row in the request log named for q,
|
||||
// the account the test asked, when that is another of p's than p (the
|
||||
// row says who answered, as the gateway's rows do).
|
||||
func (p Provider) loggedAs(ctx context.Context, q Provider) context.Context {
|
||||
if q.Account == nil || p.Account != nil && q.Account.User == p.Account.User {
|
||||
return ctx
|
||||
}
|
||||
return q.ownRequests(ctx, probelog.KindTest)
|
||||
}
|
||||
|
||||
// testOn is model's test on proto's endpoint with p's key, asked for by
|
||||
// its upstream name, as client would ask it when one is named (TestAs).
|
||||
func (p Provider) testOn(ctx context.Context, client string, proto Protocol, model, upstream string) Result {
|
||||
@@ -580,6 +664,11 @@ const zenPublicNone = "no free model of OpenCode Zen is listed for this API: the
|
||||
// Responses, and every one failed, though big-pickle answers on chat).
|
||||
func (p Provider) testModel(q Provider, proto Protocol) string {
|
||||
k := q.first()
|
||||
// a model the key's vendor lists it, and the user lets it serve
|
||||
// (AccountModels, #474), as routing has it
|
||||
sees := func(id string) bool {
|
||||
return k.Key == "" || p.Serves(k, id) && p.AccountServes(keyID(k.Key), id)
|
||||
}
|
||||
public := q.zenPublic()
|
||||
off := disabledNow() // a model the user disabled is never asked (#1867)
|
||||
var pools [][]catalog.Model
|
||||
@@ -608,7 +697,7 @@ func (p Provider) testModel(q Provider, proto Protocol) string {
|
||||
if public && !p.OpenCodeFree(m.ID) {
|
||||
continue
|
||||
}
|
||||
if !p.DecidesModel(m.ID) && !off(p.ID, m.ID) && want(m.ID) && (k.Key == "" || p.Serves(k, m.ID)) {
|
||||
if !p.DecidesModel(m.ID) && !off(p.ID, m.ID) && want(m.ID) && sees(m.ID) {
|
||||
return m.ID
|
||||
}
|
||||
}
|
||||
@@ -620,7 +709,7 @@ func (p Provider) testModel(q Provider, proto Protocol) string {
|
||||
// sends it (heatonz on Discord: a provider serving only those)
|
||||
// or one its preset names (Voyage AI, which lists none)
|
||||
for _, m := range append(catalog.LiveServing(p.ID, ""), p.PlanRetrieval("")...) {
|
||||
if retrievalOf(m.ID) != "" && !off(p.ID, m.ID) && (k.Key == "" || p.Serves(k, m.ID)) {
|
||||
if retrievalOf(m.ID) != "" && !off(p.ID, m.ID) && sees(m.ID) {
|
||||
return m.ID
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
// A model's test asks the account a request for it goes to (#4992,
|
||||
// scutken): a newapi pool's accounts list different models, and its
|
||||
// grok-4.7, served by one account alone, was asked of the first and
|
||||
// failed 503 "no available channel" while the gateway answered real
|
||||
// requests on the account that serves it.
|
||||
|
||||
// twoAccountPlugin is the fake plugin signed in twice, a@fake first:
|
||||
// first, the first sign-in (an OAuth one with access a@fake unless
|
||||
// given), and b@fake an OAuth one. The fake vendor answers b@fake
|
||||
// alone and says what else asked it, as newapi tells an account without
|
||||
// the model it isn't there.
|
||||
func twoAccountPlugin(t *testing.T, ctx context.Context, first map[string]any) (Provider, func() []string) {
|
||||
t.Helper()
|
||||
bun := testenv.Bun(t)
|
||||
claudeHome(t)
|
||||
t.Setenv("MAGPIE_BUN", bun)
|
||||
t.Setenv("FAKE_GROK", "1")
|
||||
t.Cleanup(plugin.Settle)
|
||||
var mu sync.Mutex
|
||||
var wrong []string
|
||||
testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if auth := r.Header.Get("Authorization"); auth != "Bearer b@fake" {
|
||||
mu.Lock()
|
||||
wrong = append(wrong, auth+" "+r.URL.Path)
|
||||
mu.Unlock()
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
fmt.Fprint(w, `{"error":{"message":"no available channel for model","type":"new_api_error"}}`)
|
||||
return
|
||||
}
|
||||
fmt.Fprint(w, `{"id":"x","object":"chat.completion","created":1,"model":"m","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`)
|
||||
}))
|
||||
abs, _ := filepath.Abs("../plugin/testdata/fake/index.js")
|
||||
if _, err := plugin.Add(ctx, abs); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first == nil {
|
||||
first = map[string]any{"type": "oauth", "refresh": "r-a", "access": "a@fake", "expires": 9e15, "accountId": "a@fake"}
|
||||
}
|
||||
var ls []savedLogin
|
||||
for _, u := range []struct {
|
||||
user string
|
||||
auth map[string]any
|
||||
}{
|
||||
{"a@fake", first},
|
||||
{"b@fake", map[string]any{"type": "oauth", "refresh": "r-b", "access": "b@fake", "expires": 9e15, "accountId": "b@fake"}},
|
||||
} {
|
||||
k, err := plugin.Import(ctx, "fakeco", u.auth)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ls = append(ls, savedLogin{Agent: "plugin:fakeco", User: u.user, Home: k, On: true})
|
||||
}
|
||||
saveLogins(t, ls...)
|
||||
if _, err := plugin.Providers(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, err := Find(PluginID("fakeco"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p.Account == nil || p.Account.User == "b@fake" || len(p.AlsoOn()) != 1 {
|
||||
t.Fatalf("the pool: first %+v, %d more", p.Account, len(p.AlsoOn()))
|
||||
}
|
||||
return *p, func() []string {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return append([]string(nil), wrong...)
|
||||
}
|
||||
}
|
||||
|
||||
// A model the user lets one account serve (AccountModels, #474), asked
|
||||
// by "测试模型" and the right-click test (TestModels), goes to that
|
||||
// account, and its row in the request log names it.
|
||||
func TestModelTestAsksTheAccountThatServesIt(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
p, wrong := twoAccountPlugin(t, ctx, nil)
|
||||
rows := probeRows(t)
|
||||
p.AccountModels = map[string][]string{"a@fake": {"fake-1"}, "b@fake": {"grok-4.7"}}
|
||||
rs := p.TestModels(ctx, []string{"grok-4.7"})
|
||||
if len(rs) != 1 || !rs[0].OK {
|
||||
t.Fatalf("grok-4.7's test: %+v (others asked: %v)", rs, wrong())
|
||||
}
|
||||
if w := wrong(); len(w) != 0 {
|
||||
t.Errorf("asked an account the user kept off grok-4.7: %v", w)
|
||||
}
|
||||
for _, r := range rows() {
|
||||
if r.Model == "grok-4.7" && r.Account != "b@fake" {
|
||||
t.Errorf("the test's row names %q, not the account asked: %+v", r.Account, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// An account whose own list (its plan, as the plugin lists it) leaves a
|
||||
// model out is passed over for one whose list has it, as the gateway
|
||||
// passes it over (Account.Lists): the fake plugin lists fake-1 alone to
|
||||
// an API key "few".
|
||||
func TestModelTestPassesAnAccountWhoseListLacksIt(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
p, wrong := twoAccountPlugin(t, ctx, map[string]any{"type": "api", "key": "few"})
|
||||
if p.Account.Lists("grok-4.7") || !p.Account.Lists("fake-1") {
|
||||
t.Fatal("the first account's own list is not fake-1 alone")
|
||||
}
|
||||
rs := p.TestModels(ctx, []string{"grok-4.7"})
|
||||
if len(rs) != 1 || !rs[0].OK {
|
||||
t.Fatalf("grok-4.7's test: %+v (others asked: %v)", rs, wrong())
|
||||
}
|
||||
if w := wrong(); len(w) != 0 {
|
||||
t.Errorf("asked the account whose list lacks grok-4.7: %v", w)
|
||||
}
|
||||
}
|
||||
|
||||
// The provider's Test picks each endpoint's model from every account's,
|
||||
// and asks it of an account that serves it: a first account kept for a
|
||||
// model the fake plugin doesn't have is never asked.
|
||||
func TestProviderTestAsksAnAccountThatServesItsModel(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
p, wrong := twoAccountPlugin(t, ctx, nil)
|
||||
p.AccountModels = map[string][]string{"a@fake": {"none-of-these"}}
|
||||
rs := p.Test(ctx)
|
||||
if len(rs) == 0 {
|
||||
t.Fatal("no endpoint tested")
|
||||
}
|
||||
for _, r := range rs {
|
||||
if !r.OK {
|
||||
t.Errorf("%s with %s: %+v (others asked: %v)", r.Protocol, r.Model, r, wrong())
|
||||
}
|
||||
}
|
||||
if w := wrong(); len(w) != 0 {
|
||||
t.Errorf("asked the account kept off every model: %v", w)
|
||||
}
|
||||
}
|
||||
|
||||
// askingRelay is a relay that answers one model only with one key, as a
|
||||
// site whose groups serve different models does. It keeps what was
|
||||
// asked, as key:model.
|
||||
func askingRelay(t *testing.T, good, model string) (*httptest.Server, func() []string) {
|
||||
t.Helper()
|
||||
var mu sync.Mutex
|
||||
asked := []string{}
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct{ Model string }
|
||||
_ = json.NewDecoder(r.Body).Decode(&in)
|
||||
key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
mu.Lock()
|
||||
asked = append(asked, key+":"+in.Model)
|
||||
mu.Unlock()
|
||||
if key != good || in.Model != model {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
fmt.Fprintf(w, `{"error":{"message":"no available channel for model %s under key %s"}}`, in.Model, key)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprint(w, `{"choices":[{"message":{"content":"hi"}}]}`)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv, func() []string {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return append([]string(nil), asked...)
|
||||
}
|
||||
}
|
||||
|
||||
// A key the user lets serve a model (AccountModels by KeyID, #474) is the
|
||||
// one its test goes with, as routing's, for a model's test and for the
|
||||
// provider's Test, not the provider's first key.
|
||||
func TestModelTestUsesTheKeyServingIt(t *testing.T) {
|
||||
probeHome(t)
|
||||
srv, asked := askingRelay(t, "sk-b", "m-b")
|
||||
if err := Save(Provider{ID: "relay", Name: "Relay", Chat: srv.URL + "/v1",
|
||||
Key: "sk-a", Keys: []KeyAccount{{Name: "b", Key: "sk-b"}}, Models: []string{"m-b"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SetAccountModels("relay", keyID("sk-a"), []string{"m-a"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, err := Find("relay")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rs := p.TestModels(context.Background(), []string{"m-b"}); len(rs) != 1 || !rs[0].OK {
|
||||
t.Fatalf("m-b's test: %+v (asked %v)", rs, asked())
|
||||
}
|
||||
if rs := p.Test(context.Background()); len(rs) == 0 || !rs[0].OK || rs[0].Model != "m-b" {
|
||||
t.Fatalf("the provider's test: %+v (asked %v)", rs, asked())
|
||||
}
|
||||
for _, a := range asked() {
|
||||
// "sk-a:" alone is the model list the Test reads first, a GET
|
||||
if strings.HasPrefix(a, "sk-a:") && a != "sk-a:" {
|
||||
t.Errorf("asked the key the user kept off m-b: %v", asked())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A model the user barred every account on from is not asked, as the
|
||||
// gateway never routes it, rather than asked of the first account and
|
||||
// failed for a reason the user already set.
|
||||
func TestModelTestBarredModelIsNotAsked(t *testing.T) {
|
||||
probeHome(t)
|
||||
srv, asked := askingRelay(t, "sk-a", "m-a")
|
||||
p := Provider{ID: "pool", Name: "Pool", Chat: srv.URL + "/v1",
|
||||
Account: &Account{Agent: "pool", User: "first"},
|
||||
Models: []string{"m-a", "m-b"},
|
||||
AccountModels: map[string][]string{"first": {"m-a"}}}
|
||||
rs := p.TestModels(context.Background(), []string{"m-b"})
|
||||
if len(rs) != 1 || rs[0].OK || !strings.Contains(rs[0].Error, "set not to serve") {
|
||||
t.Fatalf("m-b's test: %+v", rs)
|
||||
}
|
||||
if got := asked(); len(got) != 0 {
|
||||
t.Errorf("asked anyway: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Detect APIs asks each model with a key a request for it goes to, as a
|
||||
// model's test does: a relay's key kept for other models is not asked.
|
||||
func TestDetectModelsUsesTheKeyServingIt(t *testing.T) {
|
||||
probeHome(t)
|
||||
srv, asked := askingRelay(t, "sk-b", "m-b")
|
||||
if err := Save(Provider{ID: "relay", Name: "Relay", Chat: srv.URL + "/v1",
|
||||
Key: "sk-a", Keys: []KeyAccount{{Name: "b", Key: "sk-b"}}, Models: []string{"m-b"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SetAccountModels("relay", keyID("sk-a"), []string{"m-a"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, err := Find("relay")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ms, _, err := p.DetectModels(context.Background(), srv.URL+"/v1", []string{"m-b"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(ms) != 1 || len(ms[0].Results) == 0 || !ms[0].Results[0].OK {
|
||||
t.Fatalf("m-b's detection: %+v (asked %v)", ms, asked())
|
||||
}
|
||||
for _, a := range asked() {
|
||||
if strings.HasPrefix(a, "sk-a:") {
|
||||
t.Errorf("asked the key the user kept off m-b: %v", asked())
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user