usage: a Fast call is priced at Fast's price, not the standard one (Archivemylife on X)
Every service tier was priced at standard, so a Fast (priority) call was billed at half its price, and a subscription's API-equivalent value was half too. Sources: - OpenAI, developers.openai.com/api/docs/pricing: gpt-6.1-sol Fast is $4 / $20 / $0.20 cached (2x standard $2 / $10 / $0.10); Ultrafast 6x, Flex 0.5x. "Priority processing was renamed Fast mode on July 30, 2026." - Anthropic, platform.claude.com/docs/en/about-claude/pricing: Claude Opus 5.5 fast mode $8 / $40 (2x), "across the full context window". - models.dev's experimental.modes in magpie's catalog carry the same prices: OpenAI's keyed by provider.body.service_tier, Anthropic's by speed "fast". catalog.TierPrice reads those modes, only where the model's base price is the vendor's own (a relay's or a custom price is left alone). The Ledger's Pricer and the window's apiPricer both price by the billed tier: TierServed when the vendor says (Codex's backend always says auto/default, so servedTierAt keeps it "" and TierSent is used), otherwise TierSent. The tier ask is noted so a catalog change re-keys the request index, and settledCountVersion goes to 6 so stored settled costs are counted again. Run on mica. The full run was at this change on f9492fd8e; it was then rebased ontob1d5912de(two commits, Gemini draw and Antigravity discovery, no file in common). At the pushed head: go vet of gateway, provider, usage and catalog; go test of internal/agent, usage and catalog in full; gateway and provider -run Speed|Reasoning|TTFT| FirstToken|Gemini|Draw|Tier: all ok. Atf9492fd8e: - gofmt -l: clean - go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui, GOOS=windows go build: ok - go test -tags nogui -count=1 -timeout 45m ./...: 103 ok, no FAIL (usage 108s, catalog 4s), log kept whole and grepped - Broken by hand: TestFastCallsPricedAtTheirTier on the old ledger.go and window_holds.go is red (Codex Fast 0.11 vs 0.22, ledger total 1.188 vs 2.123); green on the new. Cases: Codex priority 2x, ultrafast 6x, standard 1x; API priority served priority 2x, served default 1x; flex 0.5x; relay at rate 0.8 unchanged; Claude fast 2x, standard 1x; a 300k-input Fast call. Not tried: - Long-context Fast is the long-context price times the Fast ratio; models.dev lists no long-context Fast price of its own. - The Usage page was not opened against a real Fast row after the fix.
This commit is contained in:
@@ -274,6 +274,7 @@ the key's leaves the call as asked, with a log line (`compactRefused`).
|
||||
- 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`; so does any other try that failed, billed something and handed the request on, to another account or member or the same one again (`failedRow` in `serve`, written once the next try begins): a Claude subscription run that failed after Anthropic's `message_start` had written the conversation to that account's cache, and the next account wrote it again, while the Usage page counted the second alone (hhxk233 and Kayrainforest on X; `relay` keeps the reply start's usage on a failure, `TestClaudeSubscriptionFailedTryKeepsItsTokens`). A try that failed before anything was billed has no record; `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.
|
||||
- A failed call is in `app.log` too, not only the Routing page and the usage ledger (wjh66 on Discord: Codex's "error decoding response body" after "reconnecting 5/5", and the log had nothing of the turn). `record` writes each call whose status is 400 or more, or that carries an error, as one line (`failedCallLine`: agent, model, provider, status, time, the error to 300 characters); the same failure again within a minute is counted into the next line, not written (`failedLogEvery`), so a client asking in a loop can't fill the log. A Codex reply relayed from the ChatGPT backend that ends before its last event also says which side ended it (`codexEndedEarly` in [`codex_backend.go`](../../internal/gateway/codex_backend.go)): the read of OpenAI's stream that failed, with its error, or a clean end; and the client gone, a write to it that failed, or the failure passed on as `response.failed`, with the bytes passed on. reqwest, Codex's HTTP client, says "error decoding response body" for any read of a body whose connection broke, so only this line tells the legs apart. A gateway that ends with requests still in flight logs that they were cut (`srv.Shutdown`'s error; on Windows there is no handover, so an update or quit cuts a stream after `shortDrain`) (`TestCodexReplyBrokenOffLogged`, `TestCodexClientGoneLogged`, `TestFailedCallLineOncePerMinute`).
|
||||
- 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, on Codex's own sign-in (`codexUpstreamOn`) too, which before set only the route's `tier`, so a `/fast` turn there showed nothing (Anotiaww on X). The Routing page's request row shows a try's tier as a quiet tag beside the model (`fast` for `priority`, `Ultrafast`, `flex`; an in-flight row the route's asked tier), with the served tier in its title when the reply said another (`rowTier` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js), `routing-service-tier.test.cjs`). A bridge that doesn't go through `forwardOnce` (the Claude subscription, Cursor's built-in) leaves `tier_sent` empty. Through a Remote magpie the other magpie's word is taken (JackyFill on X: Codex → magpie1 → magpie2 → a ChatGPT account, Fast on in magpie2 alone, was logged `default` on magpie1): a try asked by another magpie (`magpieAsks`) says on its reply's header the tier it sent its vendor (`X-Magpie-Tier-Sent`, `none` for none) and, when that vendor's `auto`/`default` tell nothing, `X-Magpie-Tier-Unsaid: 1` (`stampTier`, from the holdWriter's `writeHeader`). The asking magpie takes them from a remote magpie's reply alone (`tierThere` in `heardReply`; a vendor's `X-Magpie-` headers are never passed) and records them as its try's `tier_sent` (`sentThere`) and an unknown `tier_served` (`servedThere`); a chain of magpies passes the farthest one's on. A reply whose headers a keepalive sent before the try answered carries neither, and the asking magpie keeps its own record. Code: [`tier_record.go`](../../internal/gateway/tier_record.go).
|
||||
- A record is priced at its tier (`Record.billedTier`: `tier_served` when the reply named one, so an OpenAI API call asked `priority` and run at `default` is billed at the default; else `tier_sent`, which is what a ChatGPT backend row has, its `tier_served` being empty). `catalog.TierPrice` reads the price from the model's models.dev `experimental.modes`: the mode whose `provider.body.service_tier` is the tier, or whose `speed` is `fast` for Claude's `fast`, under `openai` or `anthropic`. That price stands only where the row's price is that entry's standard one, so a relay's rate or the user's own price is left as it is. The pricing pages agree: OpenAI's Fast (Priority processing until 2026-07-30) is twice gpt-6.1-sol's standard and Ultrafast six times, Flex half; Anthropic's fast mode is twice Claude Opus 5.5's. A mode lists no long-context price or 1-hour write, so the standard's are scaled by the mode's own ratio. The Usage page, a key's spend limit (`NewCoster`) and a subscription window's API value (`apiPricer`) all price through it (`TestFastCallsPricedAtTheirTier`, Archivemylife on X). Before this, every tier was priced at the standard rate.
|
||||
- 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 group's member may be Ultrafast as well as fast (`Group.Ultra`, a subset of `Fast`, `Group.SetMemberTier`; the member's button steps Standard speed, Fast, Ultrafast where `ultraOK`; `ultra=` in `magpie group`), and a model has its own speed (`settings.ModelTiers`, "<provider>/<model>" to `priority` or `ultrafast`, `provider.SetModelTier`, Model settings and `magpie model tier`; kdajenks on X). The gateway sends it on a direct pick for an agent with no fast pick of its own (`provider.ModelTier`, the branch after `IsFastPick`), through the same `fastPick`, so an account without Ultrafast is sent `priority`. A group member goes as the group says. On a provider the user added by its address (`OwnFast`, a GPT or o-series model on an OpenAI API) the member's button goes on to Ultrafast when OpenAI offers the tier on the model: one of Codex's accounts lists it, or Codex's own `models_cache.json` entry for the slug does (`codexcat.OwnOffers`, the entry `ownTiers` already offers Codex), and the tier is only asked for, as its Fast is: a provider that turns the field away is asked again without it (KoiLx0 on X). A fast member never goes slower than the provider's extraBody asks: its `service_tier` `ultrafast` (forced or not) makes a Fast member go Ultrafast (`extraUltra`), a slower one (`flex`) gives way to the member's Fast, and a forced `!service_tier` still goes as written over all of them (`TestFastMemberOwnProviderExtraTier`, `TestCanUltraOwnProvider`, `group-member-fast.test.cjs`). `TestModelTierSentToEveryAgent`, `TestGroupMemberUltrafast`, `model-speed.test.cjs`.
|
||||
- Codex's service tier (`settings.CodexServiceTier`, a row in Codex's settings, JackyFill on X) sets the `service_tier` of every request of Codex's, whatever Codex's own `/fast` asked: empty is as Codex asks (the default, nothing changed), `default` sends none (standard), `priority` is Codex's Fast and `ultrafast` its Ultra Fast (the request values in Codex's `ServiceTier`; Flex is not offered, since the ChatGPT backend's requests drop it in `codex_request.go`). `codexTiered` ([`codex_tier.go`](../../internal/gateway/codex_tier.go)) rewrites the body as it comes in, on both of Codex's ways in: `codexBackend` (Codex signed in, `/backend-api/codex`) and the main handler's Codex-on-Responses block, which a websocket turn reaches too. Everything after treats it as Codex's own ask: an account whose list lacks Ultrafast is put after a mate that offers it (`tierMate`) or sent `priority`, and a provider that refuses a tier drops it. A model with no provider (`gpt-…`, Codex's own sign-in, whose plan magpie doesn't know) is sent `ultrafast` only where one of magpie's Codex accounts lists it on the model (`UltraModels`), else `priority`. Another agent's request is never touched, and fast picks still apply after. `TestCodexServiceTierSet`, `codex-service-tier.test.cjs`.
|
||||
|
||||
@@ -448,6 +448,21 @@ type mdModel struct {
|
||||
Output []string `json:"output"`
|
||||
} `json:"modalities"`
|
||||
Cost *Price `json:"cost"`
|
||||
// Experimental's modes are the other ways the vendor serves the model
|
||||
// and what each costs: OpenAI's "fast" is service_tier "priority",
|
||||
// its "ultrafast" and "flex" those tiers, Anthropic's "fast" speed
|
||||
// "fast" (TierPrice)
|
||||
Experimental struct {
|
||||
Modes map[string]struct {
|
||||
Cost *Price `json:"cost"`
|
||||
Provider struct {
|
||||
Body struct {
|
||||
ServiceTier string `json:"service_tier"`
|
||||
Speed string `json:"speed"`
|
||||
} `json:"body"`
|
||||
} `json:"provider"`
|
||||
} `json:"modes"`
|
||||
} `json:"experimental"`
|
||||
// Canonical is the model models.dev says this entry is, as
|
||||
// "maker/model": DeepSeek lists V4.1 Flash as deepseek-flash, its
|
||||
// canonical deepseek/deepseek-v4.1-flash, the id everyone else serves
|
||||
@@ -952,6 +967,54 @@ func PriceOf(providerID, modelID string) (Price, bool) {
|
||||
return Price{}, false
|
||||
}
|
||||
|
||||
// TierPrice is what a model's maker bills it at a service tier, as
|
||||
// models.dev lists it under the model's modes, when std is the model's
|
||||
// standard price there: a price a user, a relay or another vendor set is
|
||||
// theirs, and isn't moved. The tier is OpenAI's service_tier word
|
||||
// ("priority", Fast's; "ultrafast"; "flex") or "fast", Claude's speed
|
||||
// (bodyTier). OpenAI's pricing page has gpt-6.1-sol's Fast (Priority
|
||||
// processing until 2026-07-30) at $4/$20/$0.20 cached, twice its standard,
|
||||
// and Ultrafast at six times; Anthropic's has Claude Opus 5.5's fast mode
|
||||
// at $8/$40, twice too, "across the full context window". A mode lists no
|
||||
// long-context price or 1-hour cache write, so std's are scaled by the
|
||||
// mode's own ratio to std, part by part.
|
||||
func TierPrice(std Price, model, tier string) (Price, bool) {
|
||||
tier = strings.ToLower(strings.TrimSpace(tier))
|
||||
if tier == "" || tier == "default" || tier == "auto" {
|
||||
return Price{}, false
|
||||
}
|
||||
all := load()
|
||||
for _, maker := range []string{"openai", "anthropic"} {
|
||||
m, ok := all[maker].Models[model]
|
||||
if !ok || m.Cost == nil || !m.Cost.Same(std) {
|
||||
continue
|
||||
}
|
||||
for _, mode := range m.Experimental.Modes {
|
||||
c, body := mode.Cost, mode.Provider.Body
|
||||
if c == nil || !(strings.EqualFold(body.ServiceTier, tier) || tier == "fast" && body.Speed == "fast") {
|
||||
continue
|
||||
}
|
||||
ratio := func(mode, base float64) float64 {
|
||||
if base <= 0 {
|
||||
return 1
|
||||
}
|
||||
return mode / base
|
||||
}
|
||||
at := Price{Input: c.Input, Output: c.Output, CacheRead: c.CacheRead, CacheWrite: c.CacheWrite, CacheWrite1h: c.CacheWrite1h, Peak: std.Peak}
|
||||
if at.CacheWrite1h == 0 {
|
||||
at.CacheWrite1h = std.CacheWrite1h * ratio(c.CacheWrite, std.CacheWrite)
|
||||
}
|
||||
for _, t := range std.Tiers {
|
||||
at.Tiers = append(at.Tiers, Tier{Above: t.Above, Input: t.Input * ratio(c.Input, std.Input), Output: t.Output * ratio(c.Output, std.Output),
|
||||
CacheRead: t.CacheRead * ratio(c.CacheRead, std.CacheRead), CacheWrite: t.CacheWrite * ratio(c.CacheWrite, std.CacheWrite),
|
||||
CacheWrite1h: t.CacheWrite1h * ratio(c.CacheWrite, std.CacheWrite)})
|
||||
}
|
||||
return at, true
|
||||
}
|
||||
}
|
||||
return Price{}, false
|
||||
}
|
||||
|
||||
// PricedBy is the list price the first of providers (models.dev ids)
|
||||
// pricing a model of this id gives it: by its own key first, then by its
|
||||
// id without a path or case ("openai/GPT-6-Sol" is gpt-6-sol), a Bedrock
|
||||
|
||||
@@ -34,7 +34,7 @@ import (
|
||||
// history again on its first start, the cold start's peak (#2278). Raise
|
||||
// it with any change to what a row counts as; TestSettledCountedAsVersioned
|
||||
// fails until it is raised.
|
||||
const settledCountVersion = "5"
|
||||
const settledCountVersion = "6"
|
||||
|
||||
func heatDiskPath() string {
|
||||
return filepath.Join(filepath.Dir(sessions.CachePath()), "heat-v1.json")
|
||||
|
||||
@@ -586,7 +586,7 @@ var ownPrice catalog.Price
|
||||
// one whose other models alone would stand for this call's, prices
|
||||
// nothing (#4278).
|
||||
func Pricer() func(Record) *catalog.Price {
|
||||
prices := map[[6]string]*catalog.Price{}
|
||||
prices := map[[7]string]*catalog.Price{}
|
||||
// each provider's rate windows as the same read of the prices saw
|
||||
// them: the windows are held once (BasePriceIn), each record's rate
|
||||
// read at its own time (provider.RateAt), so a window that opens
|
||||
@@ -606,7 +606,8 @@ func Pricer() func(Record) *catalog.Price {
|
||||
// a key that bills at its own rate (provider.KeyPriceRates) prices
|
||||
// its calls apart from the provider's other keys
|
||||
key := r.ProviderKeyID
|
||||
k := [6]string{id, r.Model, served, r.SessionProvider, r.Effort, key}
|
||||
tier := r.billedTier()
|
||||
k := [7]string{id, r.Model, served, r.SessionProvider, r.Effort, key, tier}
|
||||
if pr, ok := prices[k]; ok {
|
||||
return atWindow(pr, windows[id], r.Time)
|
||||
}
|
||||
@@ -618,12 +619,60 @@ func Pricer() func(Record) *catalog.Price {
|
||||
}
|
||||
if pr == nil {
|
||||
catalog.Missing() // models.dev may list it by now
|
||||
} else {
|
||||
// Fast and Ultrafast bill at more than the standard price
|
||||
// (Archivemylife on X: a Fast call read at the standard one)
|
||||
pr = tierPriced(pr, tier, served, r.Model)
|
||||
}
|
||||
prices[k] = pr
|
||||
return atWindow(pr, ws, r.Time)
|
||||
}
|
||||
}
|
||||
|
||||
// tierPriced is pr at a call's service tier: the price its maker lists
|
||||
// for the tier when pr is that model's standard price, the model that ran
|
||||
// or the one asked for (catalog.TierPrice), else pr. The rows hold the
|
||||
// tier's price, so the question is noted: a catalog that prices the tier
|
||||
// otherwise names the request index anew.
|
||||
func tierPriced(pr *catalog.Price, tier string, models ...string) *catalog.Price {
|
||||
if pr == nil || tier == "" {
|
||||
return pr
|
||||
}
|
||||
std := priceAnswer(pr, nil)
|
||||
for _, model := range models {
|
||||
if model == "" {
|
||||
continue
|
||||
}
|
||||
tp, ok := catalog.TierPrice(*pr, model, tier)
|
||||
answer := ""
|
||||
if ok {
|
||||
answer = priceAnswer(&tp, nil)
|
||||
}
|
||||
noteAsk(strings.Join([]string{"t", model, tier, std}, askSep), answer)
|
||||
if ok {
|
||||
return &tp
|
||||
}
|
||||
}
|
||||
return pr
|
||||
}
|
||||
|
||||
// billedTier is the service tier a record's call is priced at: the one
|
||||
// its reply named, as OpenAI's API bills it (a priority request it ran at
|
||||
// "default" is billed at the default), else the one sent: the ChatGPT
|
||||
// backend's reply names none that tells (servedTierAt keeps it ""). ""
|
||||
// for the standard tier.
|
||||
func (r Record) billedTier() string {
|
||||
tier := strings.ToLower(strings.TrimSpace(r.TierServed))
|
||||
if tier == "" || tier == "auto" {
|
||||
tier = strings.ToLower(strings.TrimSpace(r.TierSent))
|
||||
}
|
||||
switch tier {
|
||||
case "", "default", "auto", "standard":
|
||||
return ""
|
||||
}
|
||||
return tier
|
||||
}
|
||||
|
||||
// priceAsk is what Pricer prices a record by, less its time: the base
|
||||
// price and rate windows answer it, and every record that asks the same
|
||||
// is priced the same.
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
package usage
|
||||
|
||||
import (
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// Archivemylife on X asked whether a Fast call is counted right. It was
|
||||
// counted at the standard price: OpenAI bills Fast (service_tier
|
||||
// "priority") at twice gpt-6.1-sol's standard and Ultrafast at six times,
|
||||
// Anthropic Claude Opus 5.5's fast speed at twice. A call is now priced at
|
||||
// the tier its reply named, else the one sent (the ChatGPT backend names
|
||||
// none that tells), at the price models.dev lists under the model's
|
||||
// modes, the same as OpenAI's and Anthropic's pricing pages. A price that
|
||||
// isn't the maker's standard one (a relay's rate, a user's own) is left
|
||||
// as it is, and so is a call OpenAI said it ran at the default tier.
|
||||
// The catalog below is models.dev's own bytes for the two models.
|
||||
func TestFastCallsPricedAtTheirTier(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
t.Setenv("HOME", home)
|
||||
t.Setenv("USERPROFILE", home)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
|
||||
os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755)
|
||||
if err := os.WriteFile(catalog.CachePath(), []byte(`{"openai":{"id":"openai","models":{`+
|
||||
`"gpt-6.1-sol":{"id":"gpt-6.1-sol","cost":{"input":2,"output":10,"cache_read":0.1,"cache_write":2.5,"tiers":[{"input":4,"output":15,"cache_read":0.2,"cache_write":5,"tier":{"type":"context","size":272000}}],"context_over_200k":{"input":4,"output":15,"cache_read":0.2,"cache_write":5}},"experimental":{"modes":{"fast":{"cost":{"input":4,"output":20,"cache_read":0.2,"cache_write":5},"provider":{"body":{"service_tier":"priority"}}},"flex":{"cost":{"input":1,"output":5,"cache_read":0.05,"cache_write":1.25},"provider":{"body":{"service_tier":"flex"}}},"pro":{"provider":{"body":{"reasoning":{"mode":"pro"}}}},"ultrafast":{"cost":{"input":12,"output":60,"cache_read":0.6,"cache_write":15},"provider":{"body":{"service_tier":"ultrafast"}}}}}}}},`+
|
||||
`"anthropic":{"id":"anthropic","models":{`+
|
||||
`"claude-opus-5-5":{"id":"claude-opus-5-5","cost":{"input":4,"output":20,"cache_read":0.2,"cache_write":5},"experimental":{"modes":{"fast":{"cost":{"input":8,"output":40,"cache_read":0.4,"cache_write":10},"provider":{"body":{"speed":"fast"},"headers":{"anthropic-beta":"fast-mode-2026-02-01"}}}}}}}}}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
catalog.Reset()
|
||||
t.Cleanup(catalog.Reset)
|
||||
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "sk-relay", Chat: "https://relay.example/v1", PriceRate: 0.8}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
in, out, cached := 40_000, 2_000, 100_000
|
||||
sol := (float64(in)*2 + float64(out)*10 + float64(cached)*0.1) / 1e6
|
||||
opus := (float64(in)*4 + float64(out)*20 + float64(cached)*0.2) / 1e6
|
||||
calls := []struct {
|
||||
name, prov, model, sent, served string
|
||||
want float64
|
||||
}{
|
||||
{"Codex Fast, the backend naming no tier", "codex", "gpt-6.1-sol", "priority", "", 2 * sol},
|
||||
{"Codex Ultrafast", "codex", "gpt-6.1-sol", "ultrafast", "", 6 * sol},
|
||||
{"Codex standard", "codex", "gpt-6.1-sol", "", "", sol},
|
||||
{"API Fast", "openai", "gpt-6.1-sol", "priority", "priority", 2 * sol},
|
||||
{"API Fast run at the default tier", "openai", "gpt-6.1-sol", "priority", "default", sol},
|
||||
{"API Flex", "openai", "gpt-6.1-sol", "flex", "flex", sol / 2},
|
||||
{"a relay's own rate", "relay", "gpt-6.1-sol", "priority", "", 0.8 * sol},
|
||||
{"Claude fast", "anthropic", "claude-opus-5-5", "fast", "", 2 * opus},
|
||||
{"Claude standard", "anthropic", "claude-opus-5-5", "", "", opus},
|
||||
}
|
||||
now := time.Now()
|
||||
for i, c := range calls {
|
||||
Append(Record{Time: now.Add(-time.Duration(len(calls)-i) * time.Minute), Agent: "codex", Provider: c.prov, Model: c.model,
|
||||
TierSent: c.sent, TierServed: c.served, Input: in, Output: out, CacheRead: cached, Status: 200})
|
||||
}
|
||||
rows, sum, _ := Ledger(Month, Filter{})
|
||||
if len(rows) != len(calls) {
|
||||
t.Fatalf("rows %d", len(rows))
|
||||
}
|
||||
var total float64
|
||||
cost, api := NewCoster(), apiPricer()
|
||||
for i, c := range calls {
|
||||
r := rows[len(calls)-1-i]
|
||||
if r.Model != c.model || !r.Priced || math.Abs(r.Cost-c.want) > 1e-9 {
|
||||
t.Errorf("%s: priced=%v cost=%v, want %v", c.name, r.Priced, r.Cost, c.want)
|
||||
}
|
||||
total += c.want
|
||||
rec := Record{Provider: c.prov, Model: c.model, TierSent: c.sent, TierServed: c.served, Input: in, Output: out, CacheRead: cached}
|
||||
if got, ok := cost(rec); !ok || math.Abs(got-c.want) > 1e-9 {
|
||||
t.Errorf("%s: a key limit counts it at %v (%v), want %v", c.name, got, ok, c.want)
|
||||
}
|
||||
// a subscription window's calls at their API price, a Fast one at Fast's
|
||||
if c.prov == "codex" {
|
||||
if pr := api(rec); pr == nil || math.Abs(rec.CostAt(*pr)-c.want) > 1e-9 {
|
||||
t.Errorf("%s: API price %+v, want cost %v", c.name, pr, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
if math.Abs(sum.Cost-total) > 1e-9 {
|
||||
t.Errorf("ledger total %v, want %v", sum.Cost, total)
|
||||
}
|
||||
// a long Fast prompt: models.dev lists no long-context Fast price, so
|
||||
// the standard long-context one ($4 in, $15 out) is scaled by Fast's
|
||||
// own ratio to the standard (2x in, 2x out)
|
||||
long := Record{Provider: "codex", Model: "gpt-6.1-sol", TierSent: "priority", Input: 300_000, Output: 1_000}
|
||||
if got, want := func() float64 { c, _ := cost(long); return c }(), (300_000*8.0+1_000*30.0)/1e6; math.Abs(got-want) > 1e-9 {
|
||||
t.Errorf("a long Fast prompt costs %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
@@ -340,7 +340,7 @@ func baseRates(pr catalog.Price) catalog.Price {
|
||||
func apiPricer() func(Record) *catalog.Price {
|
||||
st := settings.Load()
|
||||
wires := st.Wires()
|
||||
prices := map[[4]string]*catalog.Price{}
|
||||
prices := map[[5]string]*catalog.Price{}
|
||||
one := func(providerID, model string) *catalog.Price {
|
||||
v, ok := provider.MakerPrice(model)
|
||||
if !ok || v.Cost(1e6, 1e6, 0, 0) == 0 {
|
||||
@@ -364,7 +364,8 @@ func apiPricer() func(Record) *catalog.Price {
|
||||
served = ""
|
||||
}
|
||||
id := r.priceID()
|
||||
k := [4]string{id, r.Model, served, r.Effort}
|
||||
tier := r.billedTier()
|
||||
k := [5]string{id, r.Model, served, r.Effort, tier}
|
||||
if pr, ok := prices[k]; ok {
|
||||
return pr
|
||||
}
|
||||
@@ -381,6 +382,8 @@ func apiPricer() func(Record) *catalog.Price {
|
||||
if pr == nil && served != "" {
|
||||
pr = one(id, served)
|
||||
}
|
||||
// a Fast call is worth Fast's API price (Pricer)
|
||||
pr = tierPriced(pr, tier, served, r.Model)
|
||||
prices[k] = pr
|
||||
return pr
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user