diff --git a/docs/reference.md b/docs/reference.md index 6bcab60bc..f6a10e865 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -421,7 +421,9 @@ service tier the client asked for (Claude's fast speed reads `fast`), the one that try went out at (a fast pick sends `priority`, or `ultrafast` where the pick is set to Ultrafast; Ultrafast becomes `priority` on an account whose plan doesn't offer it), and the one the -vendor's reply said it ran at, empty when the reply doesn't say. The JSON +vendor's reply said it ran at, empty when the reply doesn't say. The +ChatGPT backend (Codex signed in with ChatGPT) says `auto` and `default` +whether Fast ran or not, so from it those are left empty too. The JSON log keeps them as `tier_asked`, `tier_sent` and `tier_served`, and each try in `/v1/magpie/route` has `tier` and `tier_served`. The last column, `upstream_stop`, is why the upstream said its reply ended, in its own diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index cffffef4a..b1e34d41f 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -179,7 +179,7 @@ recorded as a prediction failure (`noPrediction`). - A fallback happens only while none of the reply has been sent. An agent never gets half a reply from one upstream and the rest from another. - A refusal that comes as an error (#2400, Jichao). An error whose own `message` is, whole, `The request was rejected because it was considered high risk` is a refusal with no code beside it (`highRiskRefusal` in `policyRefusal`): in an HTTP error body or a stream's error event, never in an answer's text, which may quote it. The vendor that sends it isn't known; it says the request was turned away, so it goes to the next candidate under `RefusalRetries` like any refusal and rests nobody. A refusal error event before any content ends the try at once (`eventRefusalError`, `stop` as for any error), so an upstream that keeps the stream open doesn't hold the next candidate back; a refusal's stop or finish marker is still read to the end for the usage and terminator after it. After content, every write is read for a late refusal (`refusalAfter`), so one whose `event: error` name and data come in separate writes is still noted, and nothing is replayed. `TestHighRisk*`, `TestRefusalErrorDoesNotWaitForEOF` in [`refusal_error_test.go`](../../internal/gateway/refusal_error_test.go). - A request is one usage record, counted once by how it ended (小一 on Discord: Codex on credits showed "5,482 · 1,094 failed" while rows said "2 tries/3 tries" and had been answered). The final record carries `tries` when the route took more than one (`rec.Tries`, from the trace's `Tries`). A try a vendor refused or turned away (`hw.refused`, `hw.turnedAway`) still writes its own record, for what it billed and why it failed, marked `handed_on`; `usage.Totals.count` skips such a record for calls and failures. A request failed only when the agent got an error (`LostRequest`); one answered after a failed try is counted beside it as answered on a retry (`Totals.Retried`, `RetriedRequest`, the `retried` filter). Logs written before `handed_on` are read the same way: the log index marks a failed, non-rejected record followed by another of the same route id as handed on (`routeRows` in [`log_index.go`](../../internal/usage/log_index.go)). Counts by account or route (`vias`, window holds) still count every try. A turn relayed on Codex's own ChatGPT sign-in is recorded as that codex account (`codexServed` in [`codex_backend.go`](../../internal/gateway/codex_backend.go)), so the account card's window counts it; the Routing view still names the seat OpenAI, an API-key call stays `openai` with no account, as does one whose `chatgpt-account-id` isn't the account Codex's auth.json here is signed in to (a Codex in WSL or under another `CODEX_HOME`), and a row already written without an account is left as it is. Those relay rows are still not a lead's answerer (`loggedAnswers`, #1367); a row an account answered, its host `host as email`, still is. -- Each record keeps the service tier three ways (#1784): `tier_asked` is what the client's body asked (`bodyTier`; Claude's speed fast reads `fast`), `tier_sent` is what that try's last request went out with, noted in `forwardOnce` after every rewrite (fast picks, Ultrafast to priority on a plan without it) onto the per-attempt `wireAt`, and `tier_served` is only what the reply said it ran at (`upstreamTier`, read by the sniffer and the translated readers), empty when it says nothing. The route's tries carry `tier` and `tier_served` the same way. A bridge that doesn't go through `forwardOnce` (the Claude subscription, Cursor's built-in) leaves `tier_sent` empty. Code: [`tier_record.go`](../../internal/gateway/tier_record.go). +- Each record keeps the service tier three ways (#1784): `tier_asked` is what the client's body asked (`bodyTier`; Claude's speed fast reads `fast`), `tier_sent` is what that try's last request went out with, noted in `forwardOnce` after every rewrite (fast picks, Ultrafast to priority on a plan without it) onto the per-attempt `wireAt`, and `tier_served` is only what the reply said it ran at (`upstreamTier`, read by the sniffer and the translated readers), empty when it says nothing; from the ChatGPT backend (CodexBase's host) its `auto` and `default` are empty too, since it says them whether priority ran or not (`servedTierAt`, applied in `attempt` and `codexUpstreamOn`). The route's tries carry `tier` and `tier_served` the same way. A bridge that doesn't go through `forwardOnce` (the Claude subscription, Cursor's built-in) leaves `tier_sent` empty. Code: [`tier_record.go`](../../internal/gateway/tier_record.go). - An agent's fast pick (`settings.FastPicks`, the bolt in its picker, #954) may also be in `settings.UltraPicks` (#1954), offered by the GUI only where one of Codex's accounts lists Ultrafast on the model (`provider.CanUltra`, `UltraModels`). `fastPick` marks its candidates `ultra`; a try of one goes with `service_tier: "ultrafast"` on Chat and Responses, and an agent on Messages carries it in the context (`withUltra`) to `forwardTranslated`, which sets `Request.Ultrafast` for the ChatGPT backend. Either way the same check as a client's own Ultrafast ask applies, now on Chat as well as Responses: an account whose list doesn't offer it is put after a mate that does (`tierMate`), or, with none left, sent `priority`. A Chat body's own `service_tier: "ultrafast"` is parsed as Ultrafast too (`chat.go`). `TestUltraPickSentUltrafast`. - A usage record carries its prompt's cache beside `in` and `out` (#1839): `cache_read` (tokens read from the vendor's cache) and `cache_write` (cache creation, Anthropic's `cache_creation_input_tokens`; `cache_write_1h` the part written for an hour). `in` holds neither. Both are written on every record, 0 too, so a prompt that missed the cache reads as that. A record from before then has neither and reads as 0. Every route fills them: Anthropic's messages, Chat (OpenAI's `prompt_tokens_details.cached_tokens`, DeepSeek's `prompt_cache_hit_tokens`), Responses (`input_tokens_details.cached_tokens`) and Gemini (`cachedContentTokenCount`), passed through or translated, whole or streamed, a plugin's fetch, and the Claude subscription bridge. System One's decision calls report no cache. `TestUsageRecordsCacheTokensOnEveryRoute`, `TestPluginUsageRecordsCacheTokens`, `TestClaudeSubscriptionUsageKeepsCacheTokens`, `TestRecordAlwaysCarriesCacheTokens`. - What the vendor read from its cache reaches the agent in the names its SDK reads, not only the record. A relayed Chat reply whose usage tells the cache in another vendor's names (a relay's Anthropic `cache_read_input_tokens` and `cache_creation_input_tokens`, DeepSeek's `prompt_cache_hit_tokens` or Moonshot's top-level `cached_tokens` beside a 0 in `prompt_tokens_details`) is told in OpenAI's too, streamed (`chatTidy`) and whole (`chatWhole`), by `openAIUsage` in [`chattidy.go`](../../internal/gateway/chattidy.go): `prompt_tokens_details.cached_tokens` (and `cache_write_tokens`), with `prompt_tokens` and `total_tokens` made to hold the cached part where the vendor left it out. Every other field stays, and a usage already in OpenAI's names, or with no cache, goes byte for byte; one in OpenAI's names alone isn't even decoded (`mayMendUsage`). pi-ai, which DeepSeek Harness and Pi use, reads `prompt_tokens_details.cached_tokens` first, a 0 there too, and maps no Anthropic names at all, so such a relay showed DSH 缓存命中 0% while magpie had counted the hit (B3TT3R on Discord asked; DeepSeek's own API sends both names and was already read right). Relayed Responses and Messages replies, translated replies and a plugin's need nothing: their usage is written in the agent's own names. `TestAgentReadsCacheTokensOnEveryRoute`, `TestPluginAgentReadsCacheTokens`, `TestOpenAIUsageLeavesOpenAIsAlone`, `TestMayMendUsageOnlyOtherNames` in [`usage_cache_agent_test.go`](../../internal/gateway/usage_cache_agent_test.go). diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index a198050ef..31ac6390a 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -1455,6 +1455,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st call.TTFT, call.FirstText = first.ms() call.ReasoningHidden = first.hidesReasoning(provider.Responses) uu.add(sniff.usage()) + uu.Tier = servedTierAt(provider.HostOf(base), uu.Tier) call.Flow = first.flowFor(uu.Reasoning) call.Usage, served = uu, uu.Served errType := "" diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 2eea83923..692e65358 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -4094,6 +4094,9 @@ func sinceStart(before, d time.Duration) int64 { // attempt sends a request to one provider. call.To stays empty when the // provider has no endpoint to send it to. func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.Protocol, p provider.Provider, model string, body []byte, call *Call) (int, string) { + // the tier the reply said, unknown where the vendor's word tells + // nothing (servedTierAt) + defer func() { call.Usage.Tier = servedTierAt(p.Host(), call.Usage.Tier) }() // Normalize for the actual destination, separately on each fallback. // Native ChatGPT accounts accept standalone tool outputs themselves. if from == provider.Responses && (p.Account == nil || p.Account.Agent != "codex") { diff --git a/internal/gateway/tier_accounts_test.go b/internal/gateway/tier_accounts_test.go index b07c7687f..7aa43c1d2 100644 --- a/internal/gateway/tier_accounts_test.go +++ b/internal/gateway/tier_accounts_test.go @@ -27,8 +27,10 @@ import ( // offer gpt-6-luna's Ultrafast only to the Pro account. It returns the // account and service tier each request was tried with, in order. With // echo set, a reply says the tier it ran at, as OpenAI's API does -// (service_tier on the response: the one asked, or "default"). -func tierAccounts(t *testing.T, proOut, echo *bool) func() []string { +// (service_tier on the response: the one asked, or "default"). With said +// given, response.created and response.completed say the tiers it gives +// for the one asked. +func tierAccounts(t *testing.T, proOut, echo *bool, said ...func(asked string) (created, completed string)) func() []string { t.Helper() home := t.TempDir() t.Setenv("HOME", home) @@ -81,14 +83,18 @@ func tierAccounts(t *testing.T, proOut, echo *bool) func() []string { io.WriteString(w, `{"error":{"message":"You've hit your usage limit"}}`) return } - said := "" + began, ended := "", "" if echo != nil && *echo { - said = `,"service_tier":"` + cmp.Or(q.Tier, "default") + `"` + ended = `,"service_tier":"` + cmp.Or(q.Tier, "default") + `"` + } + if len(said) > 0 { + c, d := said[0](q.Tier) + began, ended = `,"service_tier":"`+c+`"`, `,"service_tier":"`+d+`"` } io.WriteString(w, sse( - `data: {"type":"response.created","response":{"id":"r1","model":"gpt-6-luna"}}`, + `data: {"type":"response.created","response":{"id":"r1","model":"gpt-6-luna"`+began+`}}`, `data: {"type":"response.output_text.delta","delta":"pong"}`, - `data: {"type":"response.completed","response":{"id":"r1"`+said+`,"usage":{"input_tokens":7,"output_tokens":1}}}`)) + `data: {"type":"response.completed","response":{"id":"r1"`+ended+`,"usage":{"input_tokens":7,"output_tokens":1}}}`)) })) t.Cleanup(up.Close) old := provider.CodexBase @@ -277,12 +283,13 @@ func TestTierRecordedPerTry(t *testing.T) { if sr := sessionRouteOf(r); sr.Tier != "ultrafast" || sr.TierServed != "ultrafast" { t.Errorf("route: %+v", sr) } - // none asked: none in the log, and the reply's "default" as it said + // none asked: none in the log, and the ChatGPT backend's "default" + // kept as unknown, which it is there (servedTierAt) postFrom(t, s, "omp", "/v1/responses", `{"model":"codex/gpt-6-luna","input":"ping"}`) tried() recs = usage.Load(time.Time{}) if n := len(recs); n < 3 || recs[n-2].TierAsked != "ultrafast" || recs[n-2].TierSent != "ultrafast" || recs[n-2].TierServed != "ultrafast" || - recs[n-1].TierAsked != "" || recs[n-1].TierSent != "" || recs[n-1].TierServed != "default" { + recs[n-1].TierAsked != "" || recs[n-1].TierSent != "" || recs[n-1].TierServed != "" { t.Fatalf("usage: %+v", recs) } diff --git a/internal/gateway/tier_chatgpt_test.go b/internal/gateway/tier_chatgpt_test.go new file mode 100644 index 000000000..5849cdf97 --- /dev/null +++ b/internal/gateway/tier_chatgpt_test.go @@ -0,0 +1,136 @@ +package gateway + +import ( + "cmp" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" +) + +// jjt on Discord: the ChatGPT backend says "auto" in response.created and +// "default" in response.completed whether priority ran or not (a Plus +// account's Fast turn on gpt-6.1-sol decoded at ~200 tok/s, one without at +// ~110, both "default"). The served tier is kept unknown there, on a +// routed try and on Codex's own sign-in relayed, never as "default". The +// events are jjt's real-priority.sse's, cut to the fields read. +func TestChatGPTBackendTierUnknown(t *testing.T) { + proOut := false + tried := tierAccounts(t, &proOut, nil, func(string) (string, string) { return "auto", "default" }) + to, _ := url.Parse(provider.CodexBase) + provider.CodexBase = "https://chatgpt.com/backend-api/codex" + s := New() + s.client = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { + r.URL.Scheme, r.URL.Host = to.Scheme, to.Host + return http.DefaultTransport.RoundTrip(r) + })} + last := func() usage.Record { + t.Helper() + recs := usage.Load(time.Time{}) + if len(recs) == 0 { + t.Fatal("no usage") + } + return recs[len(recs)-1] + } + + for _, tier := range []string{"priority", ""} { + ask := `{"model":"codex/gpt-6-luna","input":"ping"}` + if tier != "" { + ask = `{"model":"codex/gpt-6-luna","input":"ping","service_tier":"` + tier + `"}` + } + r := postFrom(t, s, "omp", "/v1/responses", ask) + tried() + if sr := sessionRouteOf(r); sr.TierServed != "" || len(sr.Tries) == 0 || sr.Tries[len(sr.Tries)-1].TierServed != "" { + t.Errorf("%q route: %+v", tier, sr) + } + if rec := last(); rec.TierSent != tier || rec.TierServed != "" { + t.Errorf("%q usage: sent %q served %q", tier, rec.TierSent, rec.TierServed) + } + } + + // Codex's own sign-in, relayed as it sent it + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-6-luna","stream":true,"input":"ping","service_tier":"priority"}`)) + req.Header.Set("Authorization", "Bearer chatgpt-token") + req.Header.Set("chatgpt-account-id", "acct-plus") + req.Header.Set("User-Agent", "codex_cli_rs/0.160.1") + s.Handler().ServeHTTP(rec, req) + tried() + if got := last(); rec.Code != 200 || got.TierSent != "priority" || got.TierServed != "" { + t.Errorf("codex relay: %d sent %q served %q", rec.Code, got.TierSent, got.TierServed) + } +} + +// OpenAI's API means its service_tier: "default" and "priority" are kept +// as it said, from a provider at api.openai.com and from Codex signed in +// with an API key, relayed there. +func TestOpenAIAPITierKept(t *testing.T) { + f := &fake{t: t} + up := setup(t, provider.Responses, f) + f.reply = "" // set per request below + if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, Responses: "https://api.openai.com/v1"}); err != nil { + t.Fatal(err) + } + to, _ := url.Parse(up.URL) + s := New() + s.client = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { + if r.URL.Host != "api.openai.com" { + t.Errorf("request to %s", r.URL) + } + r.URL.Scheme, r.URL.Host = to.Scheme, to.Host + return http.DefaultTransport.RoundTrip(r) + })} + reply := func(tier string) string { + return sse( + `data: {"type":"response.created","sequence_number":0,"response":{"id":"r1","object":"response","status":"in_progress","model":"m1","usage":null,"service_tier":"auto"}}`, + `data: {"type":"response.output_text.delta","delta":"ok"}`, + `data: {"type":"response.completed","sequence_number":9,"response":{"id":"r1","object":"response","status":"completed","model":"m1","usage":{"input_tokens":1,"output_tokens":1},"service_tier":"`+cmp.Or(tier, "default")+`"}}`) + } + last := func() usage.Record { + t.Helper() + recs := usage.Load(time.Time{}) + if len(recs) == 0 { + t.Fatal("no usage") + } + return recs[len(recs)-1] + } + for _, c := range []struct{ asked, want string }{{"priority", "priority"}, {"", "default"}} { + f.reply = reply(c.asked) + ask := map[string]any{"model": "fake/m1", "input": "ping", "stream": true} + if c.asked != "" { + ask["service_tier"] = c.asked + } + b, _ := json.Marshal(ask) + r := postFrom(t, s, "omp", "/v1/responses", string(b)) + if sr := sessionRouteOf(r); sr.TierServed != c.want { + t.Errorf("%q route: %+v", c.asked, sr) + } + if rec := last(); rec.TierServed != c.want { + t.Errorf("%q usage: served %q, want %q", c.asked, rec.TierServed, c.want) + } + + // Codex with an API key, relayed to OpenAI's API + f.reply = reply(c.asked) + ask = map[string]any{"model": "m1", "input": "ping", "stream": true} + if c.asked != "" { + ask["service_tier"] = c.asked + } + b, _ = json.Marshal(ask) + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(string(b))) + req.Header.Set("Authorization", "Bearer sk-test") + req.Header.Set("User-Agent", "codex_cli_rs/0.160.1") + s.Handler().ServeHTTP(rec, req) + if got := last(); rec.Code != 200 || got.TierServed != c.want { + body, _ := io.ReadAll(rec.Body) + t.Errorf("%q codex api key: %d served %q, want %q: %s", c.asked, rec.Code, got.TierServed, c.want, body) + } + } +} diff --git a/internal/gateway/tier_record.go b/internal/gateway/tier_record.go index d00bd51b0..2b2220faa 100644 --- a/internal/gateway/tier_record.go +++ b/internal/gateway/tier_record.go @@ -18,6 +18,20 @@ import ( "github.com/yetone/magpie/internal/provider" ) +// servedTierAt is the served tier a reply from host says, as the log keeps +// it. The ChatGPT backend's (CodexBase's host) "auto", in response.created, +// and "default", in response.completed, are what it says whether priority +// ran or not: on gpt-6.1-sol with a Plus account a Fast turn decoded at +// about 200 tok/s and one without at about 110, both "default" (jjt on +// Discord). There they tell nothing, and are kept as unknown (""), never +// as the default tier. OpenAI's API means them, and they are kept as said. +func servedTierAt(host, t string) string { + if (t == "auto" || t == "default") && host != "" && host == provider.HostOf(provider.CodexBase) { + return "" + } + return t +} + // bodyTier is the service tier a request body in proto asks for, in // OpenAI's words (service_tier: "priority", "ultrafast", "flex" …); // Claude's speed "fast" reads as "fast". "" when it asks for none.