diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index cfa774a2c..bf2eafa86 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -17,7 +17,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Part | Responsibility | Source | | --- | --- | --- | -| Provider | `Provider` holds the endpoint bases for each `Protocol` (Chat, Responses, Anthropic, Gemini), the keys, `Fallback`, `Routing`, `Sink`, `UseFirst` (Smart puts it ahead of the other providers it weighs it with, [gateway routing](gateway-routing.md)), `NoStandIn` (never a fallback for another model, [gateway routing](gateway-routing.md)), `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; `Native`, the API agents' model files ask a model on, takes `BaseAPI` where it serves the model, after the OpenAI-model and Claude-on-Messages rules (nb5p on Discord: dsh asked a Responses relay's GPTs on Chat). 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) | +| Provider | `Provider` holds the endpoint bases for each `Protocol` (Chat, Responses, Anthropic, Gemini), the keys, `Fallback`, `Routing`, `Sink`, `UseFirst` (Smart puts it ahead of the other providers it weighs it with, [gateway routing](gateway-routing.md)), `NoStandIn` (never a fallback for another model, [gateway routing](gateway-routing.md)), `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; `Native`, the API agents' model files ask a model on, takes `BaseAPI` where it serves the model, after the OpenAI-model and Claude-on-Messages rules (nb5p on Discord: dsh asked a Responses relay's GPTs on Chat). 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, as typed (a pasted endpoint or model list cut back; only Google's own bare host is given /v1beta, JNDliuliuM on X), and `Base(Gemini)` asks it at `GeminiAsked`'s base: a bare host at its /v1beta, as Google's SDKs ask one, any base with a path as typed (equinox0253 on X, `TestGeminiAsked`, `TestGeminiBareHostAskedAtV1beta`). Requests, a model's test and the model list go there: requests 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) | | Rate windows | A provider bills the hours it says at its own rate (#2463): `RateWindows`, each a span `HH:MM`–`HH:MM` on this computer's clock whose end may pass its start over midnight, the days it is on (`Days`, `time.Weekday`'s numbers, none for every day), and a rate from just over 0 to 1000 at three decimals. The first window that holds a call's time multiplies the price again, on top of `PriceRate` — a price the user set for a model included, which the price rate alone leaves as set — and outside every window the price rate alone counts. A call is priced at its own time wherever a cost is counted call by call — the Usage page and its CSV, a gateway key's cost limit, the gateway's sessions in Usage — by `EffectivePriceAt`, which `EffectivePriceIn` is at `time.Now()`, and its record's time is read on this computer's clock whatever zone it was written in (a call reported as `…Z`); the Sessions page sums a session's calls by model, not by time, so it prices them without any window (`BasePriceIn` in `sessions.priceOf`), the same at every hour it is read; the ledger's `Pricer` holds each provider's base price and windows once and reads each record's rate at the record's own time, so a window that opens mid-page prices only the calls inside it; a gateway block's rows (`blockPricer`, the Requests tab) take their price from a memo asked with no time, which `RateAt` reads as no window, and each row is put at its own window's rate there (`atWindow` before `Price.In`). A list price billed double at peak (`Peak`, DeepSeek's, Ollama Cloud's two DeepSeek models' and the relays `PeakOf` names) is part of the base: the final price is that base, peak included, times the window's rate, so a provider with a `Peak` needs no window for the same hours: the order is the spec (the author, YangHonghang), so a 0.8 window on a shared DeepSeek key takes 0.8 off the peak price at peak, and a window set over the official peak hours would double them twice, which the editor's hint says under the windows. `/v1/models` prices its list at now (`EntryPricer`); the model list magpie writes into an agent's own config (`AgentPricer`, Pi's and omp's cost) leaves every window out, since nothing rewrites that file as a window opens or closes. `CheckRateWindows` says what is wrong with a set; the editor keeps the windows under Advanced, drawn by `ratewindows.js`, which app.js imports when an editor draws the field (`rateWindowsField`) so it adds nothing to the core's scripts — until it has loaded, a save leaves `rateWindows` out, which keeps them. A provider with windows shows what it bills at now on its row (`rateNow` in `/api/providers`, `rateNowOf` in the GUI's `providers.go`: `RateAt` on the server's clock, which calls are counted on, never the browser's); one with a price rate alone shows nothing new. Windows are kept with the provider: a save that leaves them out keeps them, null or an empty list clears them, and a signed-in account's survive its `Save` — the account branch and `withPicks` both go through one list, `accountSettings`, beside its `PriceRate`, or the editor's Save would quietly drop what it shows (#4738: two lists drifted, and `additionalTools`, extraBody, reply headers, its rests, `limitRestOff` and patience were each lost one way; `TestAccountSettingsKept`). | [`ratewindow.go`](../../internal/provider/ratewindow.go), [`models.go`](../../internal/provider/models.go), [`ledger.go`](../../internal/usage/ledger.go) (`Pricer`), [`app.js`](../../internal/gui/assets/app.js) (`rateWindowsField`), [`ratewindows.js`](../../internal/gui/assets/ratewindows.js), [`gui/providers.go`](../../internal/gui/providers.go) (`rateNowOf`) | | Billing | Whether a provider is on a plan or paid as used, marked by a grey badge on its Providers row and summed up as a tag on a routing group's card (EV_John_Liu on X). `BillingKind` ([`billing.go`](../../internal/provider/billing.go)) is the user's word (`Billing`: the editor's *Billing* under Advanced, Auto/Plan/Pay as you go; `magpie provider set billing=plan\|payg\|auto`), else a signed-in account (a plan), a plan's own preset (`planPresets`: Kimi Code, the Token Plans, OpenCode Go, ClinePass), else the name of the preset region it sits at (`regionOf`: "Pay as you go…" or "…Plan…"; one named by place, or a preset with no regions, is the vendor's API, pay as you go), and `mixed` when a key of it is on a plan of the other kind (`KeyAccount.Plan`). It is "", and nothing is shown, for a provider added by its address, a local server, another magpie, a decision model, or a preset whose one endpoint takes both (`unsaidPresets`: MiniMax, ModelScope and the like). `/api/providers` gives `billing` and `billingKind`, a group's `memberInfo[].billing`; the card's tag is shown only when every member's is known. It marks only: routing and prices don't read it. `TestBillingKind`, `TestBillingEveryRegion`, `TestProviderBilling`, `TestProviderSetBilling`, `provider-billing.test.cjs`. | [`billing.go`](../../internal/provider/billing.go), [`providers.go`](../../internal/gui/providers.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) | diff --git a/internal/gateway/gemini_bare_host_test.go b/internal/gateway/gemini_bare_host_test.go new file mode 100644 index 000000000..20164ea7c --- /dev/null +++ b/internal/gateway/gemini_bare_host_test.go @@ -0,0 +1,55 @@ +package gateway + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// A Gemini compatible URL saved as a relay's bare host is kept as typed +// (cc0d9c8b0, JNDliuliuM on X), and asked as Google's SDKs ask one, at +// its /v1beta (equinox0253 on X: WandAPI's https://api.wandapi.ai under +// "Gemini 兼容", Claude Code's /v1/messages for gemini-3.8-flash went to +// /models/gemini-3.8-flash:streamGenerateContent with no version). A base +// with a path of its own is asked as typed. +func TestGeminiBareHostAskedAtV1beta(t *testing.T) { + for _, c := range []struct{ name, base, want string }{ + {"bare host", "", "/v1beta/models/gemini-3.8-flash:streamGenerateContent?alt=sse"}, + {"bare host with a slash", "/", "/v1beta/models/gemini-3.8-flash:streamGenerateContent?alt=sse"}, + {"versioned", "/v1beta", "/v1beta/models/gemini-3.8-flash:streamGenerateContent?alt=sse"}, + {"a path of its own", "/gemini", "/gemini/models/gemini-3.8-flash:streamGenerateContent?alt=sse"}, + } { + t.Run(c.name, func(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + var asked []string + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + asked = append(asked, r.URL.RequestURI()) + if r.URL.RequestURI() != c.want { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"flash ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":3,"candidatesTokenCount":2,"totalTokenCount":5}}`, + )) + })) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Gemini: up.URL + c.base, Models: []string{"gemini-3.8-flash"}}); err != nil { + t.Fatal(err) + } + code, body := post(t, "/v1/messages", `{"model":"relay/gemini-3.8-flash","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"hi"}]}`) + if code != 200 || !strings.Contains(body, "flash ok") { + t.Fatalf("status %d, asked %v: %s", code, asked, body) + } + if len(asked) != 1 || asked[0] != c.want { + t.Errorf("asked %v, want %s", asked, c.want) + } + }) + } +} diff --git a/internal/provider/gemini_api.go b/internal/provider/gemini_api.go index ea4c71c5f..62aba04b8 100644 --- a/internal/provider/gemini_api.go +++ b/internal/provider/gemini_api.go @@ -46,6 +46,20 @@ func geminiVersioned(u string) string { return u } +// GeminiAsked is the base a Gemini API is asked at: the saved base, and a +// bare host given /v1beta, as Google's SDKs add the version to a base_url +// with no path. GeminiBase keeps a relay's root as typed (JNDliuliuM on X), +// so the version is added here, where a request goes: WandAPI's +// https://api.wandapi.ai was asked at /models/… and refused (equinox0253 +// on X). A base with a path of its own (/v1beta, a relay's /gemini) is +// asked as typed. +func GeminiAsked(u string) string { + if u == "" { + return "" + } + return geminiVersioned(u) +} + // GeminiPath is the path under a Gemini base model is asked at: streamed as // server-sent events (alt=sse) when stream, else one JSON reply. func GeminiPath(model string, stream bool) string { diff --git a/internal/provider/gemini_api_test.go b/internal/provider/gemini_api_test.go index 7043cdcbf..adc495763 100644 --- a/internal/provider/gemini_api_test.go +++ b/internal/provider/gemini_api_test.go @@ -219,3 +219,30 @@ func TestGeminiBaseSavedAsTyped(t *testing.T) { t.Errorf("openai bases changed: %q %q", got.Chat, got.Responses) } } + +// A relay's bare host, kept as typed (TestGeminiBase), is asked at its +// /v1beta, as Google's SDKs ask one; a base with a path is asked as typed +// (equinox0253 on X). The model list, a model's test and the gateway all +// ask at Base(Gemini). +func TestGeminiAsked(t *testing.T) { + for in, want := range map[string]string{ + "": "", + "https://api.wandapi.ai": "https://api.wandapi.ai/v1beta", + "https://api.wandapi.ai/": "https://api.wandapi.ai/v1beta", + "http://127.0.0.1:8080": "http://127.0.0.1:8080/v1beta", + "https://api.wandapi.ai/v1beta": "https://api.wandapi.ai/v1beta", + "https://relay.example/gemini": "https://relay.example/gemini", + "https://relay.example/proxy/v1": "https://relay.example/proxy/v1", + "https://generativelanguage.googleapis.com/v1beta": "https://generativelanguage.googleapis.com/v1beta", + } { + if got := GeminiAsked(in); got != want { + t.Errorf("GeminiAsked(%q) = %q, want %q", in, got, want) + } + if got := (Provider{Gemini: in}).Base(Gemini); got != want { + t.Errorf("Base(Gemini) of %q = %q, want %q", in, got, want) + } + } + if got, _ := tiny(Provider{Gemini: "https://api.wandapi.ai"}, Gemini, "gemini-3.8-flash"); got != "https://api.wandapi.ai/v1beta/models/gemini-3.8-flash:generateContent" { + t.Errorf("a model's test asks %s", got) + } +} diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 97c5e85c8..8be61e245 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -2180,7 +2180,7 @@ func (p Provider) Base(proto Protocol) string { if p.IsVertex() { return p.vertexBase() } - return p.Gemini + return GeminiAsked(p.Gemini) } return "" } diff --git a/internal/provider/test.go b/internal/provider/test.go index 984a6eda3..bfc331006 100644 --- a/internal/provider/test.go +++ b/internal/provider/test.go @@ -263,7 +263,7 @@ func tinyBody(q Provider, proto Protocol, model string) (url, body string) { // Factory's generate route. droid sends no stream field. return q.Base(Gemini) + "/generate", fmt.Sprintf(`{"model":%q,"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`, model) } - return q.Gemini + GeminiPath(model, false), `{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"generationConfig":{"maxOutputTokens":16}}` + return q.Base(Gemini) + GeminiPath(model, false), `{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"generationConfig":{"maxOutputTokens":16}}` } return "", "" }