diff --git a/docs/reference.md b/docs/reference.md index 480093668..bce9d1ae8 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -304,8 +304,14 @@ card each count is a button for its requests in the list below (the Failed and Retried filters, `failed=1` and `retried=1`). A try a vendor refused or turned away keeps its own row, for what it billed and why, marked handed on, and isn't counted as a request. The CSV's last columns are -`tries` (on the final row, when the request took more than one) and -`handed_on`. +`tries` (on the final row, when the request took more than one), +`handed_on`, then `tier_asked`, `tier_sent` and `tier_served`: the +service tier the client asked for (Claude's fast speed reads `fast`), the +one that try went out at (a fast pick sends `priority`; 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 +log keeps them as `tier_asked`, `tier_sent` and `tier_served`, and each +try in `/v1/magpie/route` has `tier` and `tier_served`. **Output speed** (tok/s on the Usage and Routing pages, `magpie usage`) is output tokens over the time after the first token, summed per request: the diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 474082105..b2f96e234 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -69,6 +69,7 @@ foreign sealed history or repair ChatGPT's response protection. - 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 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. +- 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). - 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`. - A request whose key is a Claude sign-in (`claudeSignIn`: `Authorization: Bearer sk-ant-oat…`, Claude Code signed in to claude.ai with magpie as its base URL) is never told a 401, nor a 403 saying "OAuth token has been revoked". magpie never passes that sign-in on, so such an answer is a provider refusing magpie's credential, or one of magpie's own Claude accounts lapsing; told it, Claude Code renews its own sign-in before each of its retries (ten for one request) and then asks to `/login`. Any error whose message mentions x-api-key, whatever its status, Claude Code tells as "Not logged in · Please run /login" too. It is told as a 502 in magpie's words, an `api_error` saying " refused magpie's credential (HTTP 401): …" with x-api-key said as "API key", and any other error such a request is told keeps its status with x-api-key said as "API key", as does a stream's error after its 200 (`keepsSignIn`, `claude_signin.go`). Recent calls and the usage log keep the provider's status and message. Any other 403, and a request with magpie's key or an API key, is answered as before. The sign-in's beta (`oauth-…` in `anthropic-beta`) isn't passed on either (`askedBetas`), so a provider gets the request as Claude Code with magpie's key sends it; a provider's own `header.anthropic-beta` still goes. - A 2xx that can't be an API's answer is the 502 it stands for (`notAnAPIReply`, #1012): a web page (`text/html`, or a body that begins as one: a sign-in page, Cloudflare's challenge), a body with nothing in it, or one sent as JSON that doesn't begin as JSON. Every upstream request goes through it (`forwardOnce`, and the built-in clients' own: the ChatGPT backend's `/responses`, Kiro, Zed, Qoder, Devin, Cursor, Command Code), so it fails over, rests and is logged as a 502 does, its reason naming the page's title. Only the first bytes are peeked, which a stream waits for anyway, and a compressed body is left as it came. diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 402b78ef0..088cd33c1 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -695,7 +695,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st captureTitle = link != nil && isTitleKind(kind) turn, scan := agentTurnOf(r, kind) tools = scan - tr = s.trace.begin(Route{turn: turn, dirOf: dirOf(provider.Responses, body), tools: tools, imageTurn: drawingTurnID(metadata.Turn), imageCaller: codexTurnKey(r, callerOf(r).agent), imageProvider: imageProvider, TitleLink: link, Time: start, Agent: agentOf(r), Session: sessionOf(r.Header), Conv: convOf(r.Header, body), ParentSession: titleParentSession(r.Header, metadata, kind), Kind: kind, Model: model, Effort: effort, Provider: "openai", Subagent: subagentPickOf(r), + tr = s.trace.begin(Route{turn: turn, dirOf: dirOf(provider.Responses, body), tools: tools, imageTurn: drawingTurnID(metadata.Turn), imageCaller: codexTurnKey(r, callerOf(r).agent), imageProvider: imageProvider, TitleLink: link, Time: start, Agent: agentOf(r), Session: sessionOf(r.Header), Conv: convOf(r.Header, body), ParentSession: titleParentSession(r.Header, metadata, kind), Kind: kind, Model: model, Effort: effort, Tier: bodyTier(provider.Responses, body), Provider: "openai", Subagent: subagentPickOf(r), Order: []Weighed{seat}, Tries: []Try{{ID: seat.ID, Model: model, Effort: effort, Start: start}}}) promptRead := s.inspectPrompt(tr, provider.Responses, body, body) end = func(status int, msg string, tokens, out int) { @@ -939,7 +939,9 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st rec := usage.Record{RouteID: tr.ID, Time: start, Agent: call.Agent, Provider: call.Provider, Host: provider.HostOf(base), Model: call.Model, Requested: call.Model, Served: served, Input: uu.Input, Output: uu.Output, CacheRead: uu.CacheRead, CacheWrite: uu.CacheWrite, - Reasoning: uu.Reasoning, Effort: effort, Millis: call.Millis, TTFT: call.TTFT, FirstText: call.FirstText, ReasoningHidden: call.ReasoningHidden, Flow: call.Flow, Status: call.Status, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind, + Reasoning: uu.Reasoning, Effort: effort, Millis: call.Millis, + // Codex's own sign-in: the request goes as Codex sent it + TierAsked: bodyTier(provider.Responses, body), TierSent: bodyTier(provider.Responses, body), TierServed: uu.Tier, TTFT: call.TTFT, FirstText: call.FirstText, ReasoningHidden: call.ReasoningHidden, Flow: call.Flow, Status: call.Status, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind, RequestID: requestID(res.Header), ResponseID: uu.ResponseID, Endpoint: r.URL.Path} failedWith(&rec, call.Status, call.Error, errType) appendUsage(r, rec) diff --git a/internal/gateway/continuation.go b/internal/gateway/continuation.go index a83aba3e1..dcd32a9cf 100644 --- a/internal/gateway/continuation.go +++ b/internal/gateway/continuation.go @@ -475,7 +475,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov ended := false // the upstream said its reply ended serr = readSSEAlive(rd, func(_, data string) error { st := upstreamStop([]byte(data)) - u.add(Usage{Upstream: upstreamOf([]byte(data)), Stop: st}) + u.add(Usage{Upstream: upstreamOf([]byte(data)), Stop: st, Tier: upstreamTier([]byte(data))}) ended = ended || st != "" || (actual == provider.Anthropic || actual == provider.Responses) && upstreamEnds(data) || geminiKin(actual) && geminiEnds([]byte(data)) diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index ce44427ed..063b737cf 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1911,7 +1911,8 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro if turn { capture.tools = tools } - tr := s.trace.begin(Route{turn: turn, dirOf: dirOf(from, plain), tools: tools, imageTurn: drawingTurnID(metadata.Turn), imageCaller: codexTurnKey(r, call.Agent), TitleLink: link, Pinned: pin, Time: start, Agent: call.Agent, Session: sessionOf(r.Header), Conv: convOf(r.Header, body), ParentSession: titleParentSession(r.Header, metadata, call.Kind), Kind: call.Kind, For: call.For, Model: call.Model, Effort: requestEffort(from, body), Provider: p.ID, Group: group, Rule: hit, Nested: nested, SealedTask: sealedTask, LeadAccount: leadAccount, Subagent: subagent, Affinity: shown, Order: pl.order, Left: pl.left}) + tierAsked := bodyTier(from, body) // the service tier the client asked for (#1784) + tr := s.trace.begin(Route{turn: turn, dirOf: dirOf(from, plain), tools: tools, imageTurn: drawingTurnID(metadata.Turn), imageCaller: codexTurnKey(r, call.Agent), TitleLink: link, Pinned: pin, Time: start, Agent: call.Agent, Session: sessionOf(r.Header), Conv: convOf(r.Header, body), ParentSession: titleParentSession(r.Header, metadata, call.Kind), Kind: call.Kind, For: call.For, Model: call.Model, Effort: requestEffort(from, body), Tier: tierAsked, Provider: p.ID, Group: group, Rule: hit, Nested: nested, SealedTask: sealedTask, LeadAccount: leadAccount, Subagent: subagent, Affinity: shown, Order: pl.order, Left: pl.left}) if telemetry != nil { telemetry.routeID = tr.ID } @@ -1926,6 +1927,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro var skipped []string sent := "" // the reasoning the last try's model was asked for wentAt := "" // and the level that went, once translated (wireEffort, #1636) + wentTier := "" // the service tier the last try went out at (noteWireTier, #1784) where := "" // the last try's provider.Where, for the usage again := 0 // times the last one left has been tried again resealed := 0 // what of the conversation another account sealed was taken out: its reasoning, then its compaction @@ -2318,8 +2320,9 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro if wentAt = sent; at.set { wentAt = at.effort } + wentTier = at.tier try := Try{ID: c.rest, Model: c.model, Effort: wentAt, Picked: picked, Fixed: fixed, Fast: fast, Start: began, Done: true, Status: call.Status, Millis: time.Since(began).Milliseconds(), Error: call.Error, Queued: queued, - Served: call.Usage.Served, Upstream: call.Usage.Upstream, Auto: autoPicked()} + Served: call.Usage.Served, Upstream: call.Usage.Upstream, Tier: wentTier, TierServed: call.Usage.Tier, Auto: autoPicked()} if resetFirst != nil { // the reset spent for it before it was asked try.Reset, resetFirst = resetFirst, nil @@ -2448,6 +2451,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro Requested: call.Model, Served: call.Usage.Served, Upstream: call.Usage.Upstream, Input: call.Usage.Input, Output: call.Usage.Output, CacheRead: call.Usage.CacheRead, CacheWrite: call.Usage.CacheWrite, CacheWrite1h: call.Usage.CacheWrite1h, Reasoning: call.Usage.Reasoning, Effort: wentAt, Millis: time.Since(began).Milliseconds(), Status: call.Status, + TierAsked: tierAsked, TierSent: wentTier, TierServed: call.Usage.Tier, TTFT: try.TTFT, FirstText: try.FirstText, FirstReasoning: try.FirstReasoning, ReasoningHidden: try.ReasoningHidden, Flow: try.Flow, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind, RequestID: call.Usage.RequestID, Endpoint: endpointOf(r, from, call.To, c.p, c.model), Archive: call.archiveName(), HandedOn: true} failedWith(&rec, call.Status, call.Error, call.Usage.ErrType) @@ -2491,6 +2495,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro Requested: call.Model, Served: call.Usage.Served, Input: call.Usage.Input, Output: call.Usage.Output, CacheRead: call.Usage.CacheRead, CacheWrite: call.Usage.CacheWrite, CacheWrite1h: call.Usage.CacheWrite1h, Reasoning: call.Usage.Reasoning, Effort: wentAt, Millis: time.Since(began).Milliseconds(), Status: call.Status, + TierAsked: tierAsked, TierSent: wentTier, TierServed: call.Usage.Tier, TTFT: try.TTFT, FirstText: try.FirstText, FirstReasoning: try.FirstReasoning, ReasoningHidden: try.ReasoningHidden, Flow: try.Flow, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind, RequestID: call.Usage.RequestID, Endpoint: endpointOf(r, from, call.To, c.p, c.model), Archive: call.archiveName(), HandedOn: true} failedWith(&rec, call.Status, call.Error, call.Usage.ErrType) @@ -2927,6 +2932,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro Requested: call.Model, Served: call.Usage.Served, Upstream: call.Usage.Upstream, Input: call.Usage.Input, Output: call.Usage.Output, CacheRead: call.Usage.CacheRead, CacheWrite: call.Usage.CacheWrite, CacheWrite1h: call.Usage.CacheWrite1h, Reasoning: call.Usage.Reasoning, Effort: wentAt, Millis: call.Millis, Status: call.Status, + TierAsked: tierAsked, TierSent: wentTier, TierServed: call.Usage.Tier, TTFT: call.TTFT, FirstText: call.FirstText, FirstReasoning: call.FirstReasoning, ReasoningHidden: call.ReasoningHidden, Flow: call.Flow, Sent: sentMs, Own: ownMs, Retried: retriedMs, Queued: queuedMs, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind, RequestID: call.Usage.RequestID, ResponseID: call.Usage.ResponseID, Endpoint: endpointOf(r, from, call.To, lastTried, model), Stop: call.Usage.Stop, Archive: call.archiveName()} if tries > 1 { @@ -3258,6 +3264,10 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid // before it is signed body = p.WithExtraBody(body, cmp.Or(sessionOf(in), conversationID(in, body))) } + if !countsTokens(path) { + // the tier it goes at, the user's own fields in it (#1784) + noteWireTier(ctx, to, body) + } req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.Base(to)+path, bytes.NewReader(body)) if err != nil { return nil, err @@ -4882,7 +4892,7 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr ended := false // the upstream said its reply ended see, held := written(zenSee(zen, col.add)) err = readSSE(rd, func(_, data string) error { - u.add(Usage{Upstream: upstreamOf([]byte(data))}) + u.add(Usage{Upstream: upstreamOf([]byte(data)), Tier: upstreamTier([]byte(data))}) ended = ended || upstreamStop([]byte(data)) != "" || (actual == provider.Anthropic || actual == provider.Responses) && upstreamEnds(data) || geminiKin(actual) && geminiEnds([]byte(data)) diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go index 32021b1e6..fe675ef28 100644 --- a/internal/gateway/ir.go +++ b/internal/gateway/ir.go @@ -324,6 +324,9 @@ type Usage struct { // (stop_reason, finish_reason, a Responses status): "" when it said // none, as a stream that just stops does (upstreamStop) Stop string `json:"stop,omitempty"` + // Tier is the service tier the reply says it ran at (upstreamTier), + // "" when it says none + Tier string `json:"tier,omitempty"` } // prompt is every token the prompt came to, as OpenAI's and Gemini's @@ -358,6 +361,9 @@ func (u *Usage) add(v Usage) { if v.Upstream != "" { u.Upstream = v.Upstream } + if v.Tier != "" { + u.Tier = v.Tier + } if v.RequestID != "" { u.RequestID = v.RequestID } diff --git a/internal/gateway/session_route.go b/internal/gateway/session_route.go index ffd05cb76..b346f49bf 100644 --- a/internal/gateway/session_route.go +++ b/internal/gateway/session_route.go @@ -26,20 +26,25 @@ type SessionRoute struct { Kind string `json:"kind,omitempty"` // a side call's: a title, a subagent… Asked string `json:"asked"` // the model as the agent asked AskedEffort string `json:"asked_effort,omitempty"` // the reasoning it asked for + AskedTier string `json:"asked_tier,omitempty"` // the service tier it asked for Group string `json:"group,omitempty"` // the routing group's id, when it asked one Rule *RuleHit `json:"rule,omitempty"` // the group's rules, as the Routing page has them Nested []NestedRule `json:"nested,omitempty"` // Model and Effort: the try under way, or the last, as provider/model // and the reasoning it was sent at - Model string `json:"model,omitempty"` - Effort string `json:"effort,omitempty"` - Served string `json:"served,omitempty"` // the model the reply says answered - Tries []RouteTry `json:"tries"` - Done bool `json:"done"` - Status int `json:"status,omitempty"` - Error string `json:"error,omitempty"` - Millis int64 `json:"ms,omitempty"` - TTFT int64 `json:"ttft_ms,omitempty"` + Model string `json:"model,omitempty"` + Effort string `json:"effort,omitempty"` + // Tier and TierServed: the service tier that try went out at, and the + // one its reply said it ran at, when it said one (#1784) + Tier string `json:"tier,omitempty"` + TierServed string `json:"tier_served,omitempty"` + Served string `json:"served,omitempty"` // the model the reply says answered + Tries []RouteTry `json:"tries"` + Done bool `json:"done"` + Status int `json:"status,omitempty"` + Error string `json:"error,omitempty"` + Millis int64 `json:"ms,omitempty"` + TTFT int64 `json:"ttft_ms,omitempty"` } // RouteTry is one member trying the request: each failed one was fallen @@ -47,14 +52,18 @@ type SessionRoute struct { type RouteTry struct { Model string `json:"model"` // provider/model Effort string `json:"effort,omitempty"` - Done bool `json:"done"` - Status int `json:"status,omitempty"` - Fail string `json:"fail,omitempty"` // why it failed, as the trace tells it - Millis int64 `json:"ms,omitempty"` + // Tier: the service tier it went out at; TierServed: the one its + // reply said it ran at + Tier string `json:"tier,omitempty"` + TierServed string `json:"tier_served,omitempty"` + Done bool `json:"done"` + Status int `json:"status,omitempty"` + Fail string `json:"fail,omitempty"` // why it failed, as the trace tells it + Millis int64 `json:"ms,omitempty"` } func sessionRouteOf(r Route) SessionRoute { - out := SessionRoute{ID: r.ID, Time: r.Time, Kind: r.Kind, Asked: r.Model, AskedEffort: r.Effort, Rule: r.Rule, Nested: r.Nested, + out := SessionRoute{ID: r.ID, Time: r.Time, Kind: r.Kind, Asked: r.Model, AskedEffort: r.Effort, AskedTier: r.Tier, Rule: r.Rule, Nested: r.Nested, Served: r.Served, Tries: []RouteTry{}, Done: r.Done, Status: r.Status, Error: r.Error, Millis: r.Millis, TTFT: r.TTFT} if r.Group != nil { out.Group = r.Group.ID @@ -75,10 +84,11 @@ func sessionRouteOf(r Route) SessionRoute { if p := providerOf(t.ID); p != "" && model != "" { model = p + "/" + model } - out.Tries = append(out.Tries, RouteTry{Model: model, Effort: t.Effort, Done: t.Done, Status: t.Status, Fail: t.Fail, Millis: t.Millis}) + out.Tries = append(out.Tries, RouteTry{Model: model, Effort: t.Effort, Tier: t.Tier, TierServed: t.TierServed, Done: t.Done, Status: t.Status, Fail: t.Fail, Millis: t.Millis}) } if n := len(out.Tries); n > 0 { out.Model, out.Effort = out.Tries[n-1].Model, out.Tries[n-1].Effort + out.Tier, out.TierServed = out.Tries[n-1].Tier, out.Tries[n-1].TierServed } return out } diff --git a/internal/gateway/sniff.go b/internal/gateway/sniff.go index 73c9172bf..4e6d62fe8 100644 --- a/internal/gateway/sniff.go +++ b/internal/gateway/sniff.go @@ -130,6 +130,9 @@ func (s *usageSniffer) parse(b []byte) { if st := upstreamStop(b); st != "" { s.u.Stop = st } + if t := upstreamTier(b); t != "" { + s.u.Tier = t + } switch s.proto { case provider.Gemini: // a Gemini stream names no type and sends no [DONE]: its end is a diff --git a/internal/gateway/tier_accounts_test.go b/internal/gateway/tier_accounts_test.go index b963cf606..7839883ab 100644 --- a/internal/gateway/tier_accounts_test.go +++ b/internal/gateway/tier_accounts_test.go @@ -1,8 +1,10 @@ package gateway import ( + "cmp" "context" "encoding/base64" + "encoding/csv" "encoding/json" "io" "net/http" @@ -10,19 +12,23 @@ import ( "net/url" "os" "path/filepath" + "slices" "strings" "sync" "testing" "time" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" ) // tierAccounts signs Codex in to a Plus ChatGPT account, first, with a Pro // one saved beside it, against a fake ChatGPT backend whose model lists // 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. -func tierAccounts(t *testing.T, proOut *bool) func() []string { +// 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 { t.Helper() home := t.TempDir() t.Setenv("HOME", home) @@ -75,10 +81,14 @@ func tierAccounts(t *testing.T, proOut *bool) func() []string { io.WriteString(w, `{"error":{"message":"You've hit your usage limit"}}`) return } + said := "" + if echo != nil && *echo { + said = `,"service_tier":"` + cmp.Or(q.Tier, "default") + `"` + } io.WriteString(w, sse( `data: {"type":"response.created","response":{"id":"r1","model":"gpt-6-luna"}}`, `data: {"type":"response.output_text.delta","delta":"pong"}`, - `data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":7,"output_tokens":1}}}`)) + `data: {"type":"response.completed","response":{"id":"r1"`+said+`,"usage":{"input_tokens":7,"output_tokens":1}}}`)) })) t.Cleanup(up.Close) old := provider.CodexBase @@ -107,7 +117,7 @@ func tierAccounts(t *testing.T, proOut *bool) func() []string { // the nearest its plan offers. func TestUltrafastGoesToAnAccountOfferingIt(t *testing.T) { proOut := false - tried := tierAccounts(t, &proOut) + tried := tierAccounts(t, &proOut, nil) s := New() codex := func(tier string) string { t.Helper() @@ -147,7 +157,7 @@ func TestUltrafastGoesToAnAccountOfferingIt(t *testing.T) { // doesn't; a request that asked for no tier is sent fast as before. func TestFastPickKeepsTheClientsUltrafast(t *testing.T) { proOut := false - tried := tierAccounts(t, &proOut) + tried := tierAccounts(t, &proOut, nil) if err := provider.SetFastPick("omp", "codex/gpt-6-luna", true); err != nil { t.Fatal(err) } @@ -183,3 +193,76 @@ func TestFastPickKeepsTheClientsUltrafast(t *testing.T) { t.Errorf("chat: %s", b) } } + +// #1784: the service tier the client asked for, the one each try went out +// at and the one the reply said it ran at are in the route, the usage log +// and its CSV, and the served one only when the reply said one. +func TestTierRecordedPerTry(t *testing.T) { + proOut, echo := true, false + tried := tierAccounts(t, &proOut, &echo) + to, _ := url.Parse(provider.CodexBase) + provider.CodexBase = "https://chatgpt.com/backend-api/codex" + s := New() + s.client = &http.Client{Transport: qoderRoundTrip(func(r *http.Request) (*http.Response, error) { + r.URL.Scheme, r.URL.Host = to.Scheme, to.Host + return http.DefaultTransport.RoundTrip(r) + })} + r := postFrom(t, s, "omp", "/v1/responses", `{"model":"codex/gpt-6-luna","input":"ping","service_tier":"ultrafast"}`) + if got := strings.Join(tried(), ","); got != "acct-pro:ultrafast,acct-plus:priority" { + t.Fatalf("tried %s", got) + } + sr := sessionRouteOf(r) + if sr.AskedTier != "ultrafast" || len(sr.Tries) != 2 || sr.Tries[0].Tier != "ultrafast" || sr.Tries[1].Tier != "priority" || + sr.Tier != "priority" || sr.TierServed != "" || sr.Tries[1].TierServed != "" { + t.Errorf("route: %+v", sr) + } + recs := usage.Load(time.Time{}) + if n := len(recs); n == 0 || recs[n-1].TierAsked != "ultrafast" || recs[n-1].TierSent != "priority" || recs[n-1].TierServed != "" { + t.Fatalf("usage: %+v", recs) + } + + // the reply says the tier it ran at + proOut, echo = false, true + r = postFrom(t, s, "omp", "/v1/responses", `{"model":"codex/gpt-6-luna","input":"ping","service_tier":"ultrafast"}`) + tried() + 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 + 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" { + t.Fatalf("usage: %+v", recs) + } + + // the CSV's last columns + var b strings.Builder + if err := usage.WriteCSV(&b, []usage.Row{{Record: recs[0]}}); err != nil { + t.Fatal(err) + } + cells, err := csv.NewReader(strings.NewReader(b.String())).ReadAll() + if err != nil || len(cells) != 2 { + t.Fatalf("%v %q", err, b.String()) + } + for col, want := range map[string]string{"tier_asked": "ultrafast", "tier_sent": "priority", "tier_served": ""} { + if i := slices.Index(usage.CSVHeader, col); i < 0 || cells[1][i] != want { + t.Errorf("%s: %v", col, cells) + } + } + + // Codex's own sign-in, relayed as it sent it, asking the ChatGPT + // backend for priority + 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() + recs = usage.Load(time.Time{}) + if n := len(recs); rec.Code != 200 || recs[n-1].TierAsked != "priority" || recs[n-1].TierSent != "priority" || recs[n-1].TierServed != "priority" { + t.Fatalf("codex: %d %+v", rec.Code, recs[len(recs)-1]) + } +} diff --git a/internal/gateway/tier_record.go b/internal/gateway/tier_record.go new file mode 100644 index 000000000..62dc39d64 --- /dev/null +++ b/internal/gateway/tier_record.go @@ -0,0 +1,92 @@ +package gateway + +// The service tier a request asked for, what went out on each try and +// what the vendor said it ran at, for the usage log, its CSV and the +// route (#1784). Fast's and Ultrafast's priority processing bills at +// more than the default, and the tier a request went at could change on +// the way: a fast pick asks for priority, and an account whose plan +// doesn't offer Ultrafast is asked for priority in its place. + +import ( + "bytes" + "context" + "encoding/json" + "strings" + + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/provider" +) + +// 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. +func bodyTier(proto provider.Protocol, body []byte) string { + switch proto { + case provider.Anthropic: + if gjson.GetBytes(body, "speed").String() == "fast" { + return "fast" + } + fallthrough + case provider.Chat, provider.Responses: + if t := gjson.GetBytes(body, "service_tier"); t.Type == gjson.String { + return tierWord(t.String()) + } + } + return "" +} + +// tierWord is a tier as the log keeps it: short, and nothing else. +func tierWord(t string) string { + t = strings.TrimSpace(t) + if len(t) > 32 { + return "" + } + return t +} + +// noteWireTier leaves, where the request's context has a place for it +// (wireAt), the tier body goes out to the vendor at: the last request a +// try sent is the one that answered or failed. +func noteWireTier(ctx context.Context, to provider.Protocol, body []byte) { + if w, _ := ctx.Value(wireAtKey{}).(*wireAt); w != nil { + w.tier = bodyTier(to, body) + } +} + +// upstreamTier is the service tier a reply (a JSON body, or one event of +// its stream) says it ran at: a top-level service_tier (a Chat body and +// its chunks, a Responses body), a Responses stream's response.service_tier, +// an Anthropic usage's service_tier. "" when it says none, which is never +// read as the tier that was asked. +func upstreamTier(b []byte) string { + if !bytes.Contains(b, []byte(`"service_tier"`)) { + return "" + } + var v struct { + Tier json.RawMessage `json:"service_tier"` + Response struct { + Tier json.RawMessage `json:"service_tier"` + } `json:"response"` + Usage struct { + Tier json.RawMessage `json:"service_tier"` + } `json:"usage"` + Message struct { + Usage struct { + Tier json.RawMessage `json:"service_tier"` + } `json:"usage"` + } `json:"message"` + } + if json.Unmarshal(b, &v) != nil { + return "" + } + for _, raw := range []json.RawMessage{v.Tier, v.Response.Tier, v.Usage.Tier, v.Message.Usage.Tier} { + var s string + if json.Unmarshal(raw, &s) == nil { + if s = tierWord(s); s != "" { + return s + } + } + } + return "" +} diff --git a/internal/gateway/tier_record_test.go b/internal/gateway/tier_record_test.go new file mode 100644 index 000000000..e389e4443 --- /dev/null +++ b/internal/gateway/tier_record_test.go @@ -0,0 +1,49 @@ +package gateway + +import ( + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// #1784: the served tier is read only where a reply says it, in the shapes +// OpenAI's and Anthropic's APIs document, and never taken from the ask. +func TestUpstreamTierShapes(t *testing.T) { + for _, c := range []struct{ body, want string }{ + {`{"id":"c1","object":"chat.completion.chunk","service_tier":"default","choices":[]}`, "default"}, + {`{"type":"response.completed","response":{"id":"r1","service_tier":"priority","usage":{}}}`, "priority"}, + {`{"id":"r1","object":"response","service_tier":"flex"}`, "flex"}, + {`{"type":"message_start","message":{"id":"m1","usage":{"input_tokens":3,"service_tier":"priority"}}}`, "priority"}, + {`{"type":"message_delta","usage":{"output_tokens":3,"service_tier":"standard"}}`, "standard"}, + {`{"type":"response.completed","response":{"id":"r1","usage":{}}}`, ""}, + {`{"service_tier":null}`, ""}, + {`{"service_tier":"` + strings.Repeat("x", 40) + `"}`, ""}, + {`not json "service_tier"`, ""}, + } { + if got := upstreamTier([]byte(c.body)); got != c.want { + t.Errorf("%s: %q, want %q", c.body, got, c.want) + } + } + + s := &usageSniffer{} + s.parse([]byte(`{"type":"message_start","message":{"usage":{"input_tokens":3,"service_tier":"priority"}}}`)) + if s.u.Tier != "priority" { + t.Errorf("sniffer: %+v", s.u) + } + + for _, c := range []struct { + proto provider.Protocol + body, want string + }{ + {provider.Anthropic, `{"speed":"fast"}`, "fast"}, + {provider.Anthropic, `{"service_tier":"standard_only"}`, "standard_only"}, + {provider.Responses, `{"service_tier":"ultrafast"}`, "ultrafast"}, + {provider.Chat, `{"service_tier":1}`, ""}, + {provider.Gemini, `{"service_tier":"priority"}`, ""}, + } { + if got := bodyTier(c.proto, []byte(c.body)); got != c.want { + t.Errorf("%s %s: %q", c.proto, c.body, got) + } + } +} diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index af9f3a2d2..8669a9564 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -46,6 +46,7 @@ type Route struct { For *CallFor `json:"for,omitempty"` // the request it was made for, as Call's Model string `json:"model"` // as the agent asked Effort string `json:"effort,omitempty"` // the reasoning the agent asked for; "" for none + Tier string `json:"tier,omitempty"` // the service tier the agent asked for (bodyTier); "" for none Provider string `json:"provider"` // the provider the model resolved to Group *GroupRef `json:"group,omitempty"` // the routing group the agent asked for Rule *RuleHit `json:"rule,omitempty"` // the group's rules for it, when it has any @@ -287,10 +288,15 @@ type Try struct { // Upstream: the provider an aggregator said answered behind it // (OpenRouter's DeepInfra, Novita …) Upstream string `json:"upstream,omitempty"` - Fail string `json:"fail,omitempty"` // why it failed, as rest tells it - Error string `json:"error,omitempty"` - Rest *Rest `json:"rest,omitempty"` // how long it now sits out; none when it was the last to try - Again int64 `json:"again,omitempty"` // ms waited before it was tried again, the last one left + // Tier: the service tier it went out at, once a fast pick or an + // account without Ultrafast had changed it; TierServed: the one its + // reply said it ran at, when it said one (#1784) + Tier string `json:"tier,omitempty"` + TierServed string `json:"tierServed,omitempty"` + Fail string `json:"fail,omitempty"` // why it failed, as rest tells it + Error string `json:"error,omitempty"` + Rest *Rest `json:"rest,omitempty"` // how long it now sits out; none when it was the last to try + Again int64 `json:"again,omitempty"` // ms waited before it was tried again, the last one left // Replan: every member had failed in a way that passes, so after // Again the Replan of them that may answer by then were asked again, // in turn, within the group's Patience (seconds) for the request diff --git a/internal/gateway/wire_effort.go b/internal/gateway/wire_effort.go index 1d906ba1c..19ae13d8a 100644 --- a/internal/gateway/wire_effort.go +++ b/internal/gateway/wire_effort.go @@ -23,6 +23,9 @@ func thinkingBackOn(p provider.Provider, model string, req *Request) *Request { type wireAt struct { effort string set bool + // tier: the service tier the try's request went out at, whichever + // path sent it (noteWireTier) + tier string } type wireAtKey struct{} diff --git a/internal/usage/ledger.go b/internal/usage/ledger.go index 61fe2409d..731b7c5c4 100644 --- a/internal/usage/ledger.go +++ b/internal/usage/ledger.go @@ -506,7 +506,7 @@ var CSVHeader = []string{"time", "agent", "requested_model", "provider", "host", "effort", "input_tokens", "output_tokens", "cache_write_tokens", "cache_read_tokens", "reasoning_tokens", "cost_usd", "duration_ms", "ttft_ms", "status", "error", "session", "kind", "provider_key_id", "provider_key_name", "provider_account", "route_id", "request_id", "endpoint", "error_message", "error_type", "source", "rejected", "session_provider", "session_account", "session_official_login", "caller_key_id", "caller_key_name", "response_id", "upstream", - "cache_write_5m_tokens", "cache_write_1h_tokens", "tries", "handed_on"} + "cache_write_5m_tokens", "cache_write_1h_tokens", "tries", "handed_on", "tier_asked", "tier_sent", "tier_served"} // WriteCSV writes rows as CSV, a header first (cache_write_tokens is every // cache write, as it always was, and the last two columns split it into @@ -517,6 +517,9 @@ var CSVHeader = []string{"time", "agent", "requested_model", "provider", "host", // gateway made at the request the row ends, when more than one, and // handed_on "true" for the row of a try that failed and handed the request // on: the request's outcome is the row with the same route_id after it. +// tier_asked, tier_sent and tier_served are the service tier the client +// asked for, the one sent on the row's try and the one the reply said it +// ran at, each empty when there was none (Record.TierAsked). func WriteCSV(w io.Writer, rows []Row) error { cw := csv.NewWriter(w) cw.Write(CSVHeader) @@ -542,7 +545,8 @@ func WriteCSV(w io.Writer, rows []Row) error { strconv.FormatBool(r.Swapped), r.Effort, n(r.Input), n(r.Output), n(r.CacheWrite), n(r.CacheRead), n(r.Reasoning), cost, strconv.FormatInt(r.Millis, 10), ttft, n(r.Status), strconv.FormatBool(r.Failed()), r.Session, r.Kind, r.ProviderKeyID, r.ProviderKeyName, r.Account(), routeID, r.RequestID, r.Endpoint, r.Error, r.ErrType, r.Source, strconv.FormatBool(r.IsRejected()), r.SessionProvider, r.SessionAccount, strconv.FormatBool(r.SessionOfficialLogin), r.CallerKeyID, r.CallerKeyName, r.ResponseID, r.Upstream, - n(r.CacheWrite - min(r.CacheWrite1h, r.CacheWrite)), n(min(r.CacheWrite1h, r.CacheWrite)), tries, strconv.FormatBool(r.HandedOn)}) + n(r.CacheWrite - min(r.CacheWrite1h, r.CacheWrite)), n(min(r.CacheWrite1h, r.CacheWrite)), tries, strconv.FormatBool(r.HandedOn), + r.TierAsked, r.TierSent, r.TierServed}) } cw.Flush() return cw.Error() diff --git a/internal/usage/ledger_test.go b/internal/usage/ledger_test.go index 259f18632..d37113947 100644 --- a/internal/usage/ledger_test.go +++ b/internal/usage/ledger_test.go @@ -90,8 +90,8 @@ func TestLedger(t *testing.T) { t.Fatal(err) } want := strings.Join(CSVHeader, ",") + "\n" + - rows[1].Time.Format(time.RFC3339) + ",codex,relay/sol,relay,relay.example,sol,sol-2026-01-01,false,,10,1,0,0,0,0.000028,100,,200,false,,,,,,,,,,,,false,,,false,,,,,0,0,,false\n" + - rows[2].Time.Format(time.RFC3339) + ",codex,fast,relay,relay.example,sol,luna,true,high,2000,500,1000,4000,0,0.012500,3200,400,200,false,s1,,,,,123,,,,,,false,,,false,,,,,1000,0,,false\n" + rows[1].Time.Format(time.RFC3339) + ",codex,relay/sol,relay,relay.example,sol,sol-2026-01-01,false,,10,1,0,0,0,0.000028,100,,200,false,,,,,,,,,,,,false,,,false,,,,,0,0,,false,,,\n" + + rows[2].Time.Format(time.RFC3339) + ",codex,fast,relay,relay.example,sol,luna,true,high,2000,500,1000,4000,0,0.012500,3200,400,200,false,s1,,,,,123,,,,,,false,,,false,,,,,1000,0,,false,,,\n" if b.String() != want { t.Fatalf("csv:\n%s\nwant:\n%s", b.String(), want) } @@ -261,7 +261,7 @@ func TestLedgerWithSessionLogCalls(t *testing.T) { if err := WriteCSV(&b, rows[2:4]); err != nil { t.Fatal(err) } - for _, want := range []string{",req_log,,,,log,false,,,false,,,,,500,0,,false\n", ",true,s2,,,,,,req_lim,,You've hit your limit,rate_limit,log,false,,,false,,,,,0,0,,false\n"} { + for _, want := range []string{",req_log,,,,log,false,,,false,,,,,500,0,,false,,,\n", ",true,s2,,,,,,req_lim,,You've hit your limit,rate_limit,log,false,,,false,,,,,0,0,,false,,,\n"} { if !strings.Contains(b.String(), want) { t.Fatalf("csv lacks %q:\n%s", want, b.String()) } diff --git a/internal/usage/usage.go b/internal/usage/usage.go index c9ae18605..e3010e176 100644 --- a/internal/usage/usage.go +++ b/internal/usage/usage.go @@ -76,7 +76,19 @@ type Record struct { // Effort is the reasoning the model was asked for — a routing group's // pick for the turn, or the agent's own — as it takes it; "" for none Effort string `json:"effort,omitempty"` - Millis int64 `json:"ms"` + // The service tier, as OpenAI's service_tier words it ("priority", + // "ultrafast", "flex", "default"; "fast" for Claude's speed "fast"): + // TierAsked what the client's request asked for, TierSent what went + // out to the vendor on this try, after a fast pick or a group member + // set Fast asked for priority and an account whose plan doesn't offer + // Ultrafast was asked for priority in its place, and TierServed what + // the vendor's reply said it ran at. Each is "" when there was none: + // TierServed is never taken from what was asked or sent, only from a + // reply that names it (#1784) + TierAsked string `json:"tier_asked,omitempty"` + TierSent string `json:"tier_sent,omitempty"` + TierServed string `json:"tier_served,omitempty"` + Millis int64 `json:"ms"` // TTFT: ms from the request to its reply's first content — text, // reasoning or a tool call — and FirstText to its first text, counted // as Millis is, so Millis-TTFT is how long the reply took to write;