gateway: a plugin's deferred usage is billed with its step, never told as the prompt
The Cursor plugin collects a tool step's late usage event with the conversation's next step. It used to add it to that step's prompt_tokens, which agents read as how full their context is: pi saw 366940 tokens (181270 + 185670) on a 300k window where 185670 were in use, and compacted. The plugin now reports it apart, as usage.magpie_deferred (yetone/magpie#1053). The gateway parses the field into Usage.Deferred and adds it only where it bills: the usage records (6 sites in serve), the OTel attempt span and route pricing, as a tier before the request's own, so promptCounted still reads the request's own prompt. What a client is told (Usage.chat, the Anthropic encoding) stays the request's own. A reply without the field is handled as before. docs/subsystems/provider-plugins.md describes the field. Verified: go test -tags nogui ./... (50 packages ok, sandbox HOME, caches pinned); gofmt; go vet on darwin, linux (nogui) and windows; go build on the same three. The new tests were broken by hand and each went red: billed() ignoring Deferred, cUsage dropping the field, routeUsage without the tier, Usage.add forgetting it, the decoder ignoring a usage with only a deferred part, the usage records and the OTel span not using billed(). Not tried: a real Cursor account on this checkout; the plugin side was run against real Cursor (composer-2.5, forced late events), where the deferred totals matched the dashboard's events token for token. Picked from geoqiao/magpie cursor-deferred-usage (595d6384c), as PRs here are collaborators-only. Rebased over the service-tier logging (#1784), keeping its TierAsked/TierSent/TierServed beside billed() at the three usage.Record sites, and Usage's Tier beside Deferred. Run on this tree: go test -tags nogui -timeout 40m ./internal/gateway and ./internal/provider (sandbox HOME); gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows. billed() forced to ignore Deferred: 3 tests and 5 subtests of deferred_usage_test.go go red.
This commit is contained in:
@@ -30,6 +30,12 @@ For a moved subscription, its built-in upstream implementation does not run. Plu
|
||||
|
||||
Quota aggregation in [`quotas.go`](../../internal/provider/quotas.go) suppresses a key's GLM Coding Plan card only when its comparable reset windows match a ZCode subscription card: built-in or moved `zcode`, or independently installed `zcode-plugin`. [`PlanQuotas`](../../internal/provider/planquota.go) identifies GLM plans by their quota endpoint, including custom provider ids. Matching reset schedules from unrelated vendors do not hide cards. Within this pair, resets remain a heuristic for the shared account; a plan's `User` is a key label or mask, not a login identity. Errors, conflicting resets, or no comparable resets keep the plan visible. This applies to the Usage page, tray, quota reports, alerts, and quota waits; it does not change plugin ownership or upstream requests.
|
||||
|
||||
## Usage a plugin collects late
|
||||
|
||||
A plugin that learns a step's usage only after the step has ended reports it with a later step, in `usage.magpie_deferred` (`prompt_tokens`, `completion_tokens`, `cached_tokens`, `cache_write_tokens`) beside that step's own usage fields. The Cursor plugin does this: a tool step's usage event shows seconds after the step, so the step says 0 and the conversation's next step collects the event ([#1053](https://github.com/yetone/magpie/issues/1053)).
|
||||
|
||||
The gateway parses the field into `Usage.Deferred` ([`cUsage`](../../internal/gateway/chat.go)) and adds it only where it bills: the usage records, the OTel attempt spans and route pricing, which prices it as a tier before the request's own ([`routeUsage`](../../internal/gateway/trace.go), [`Usage.billed`](../../internal/gateway/ir.go)). What a client is told stays the request's own, because agents read `prompt_tokens` as how full their context is: the passthrough forwards the plugin's bytes as they are, whose standard fields are the step's own, and a translated reply is encoded from the own count alone. `promptCounted` also reads the request's own. A reply without the field is handled as before. With an older magpie the field is ignored and the owed step goes unbilled in the ledger. [`deferred_usage_test.go`](../../internal/gateway/deferred_usage_test.go) covers the passthrough, the translated reply, the ledger, the OTel span and the pricing tiers.
|
||||
|
||||
## A plugin's daily check-in
|
||||
|
||||
A plugin can press its vendor's daily check-in (签到) itself: its `auth` hook gains `checkin(getAuth, provider)`, beside `usage`. The host lists the provider with `checkin: true` (`plugin.Provider.Checkin`) and answers `checkin({provider, account})` (`plugin.AccountCheckin`) by refreshing the account as `usage` does and calling the hook with the account's auth.
|
||||
|
||||
@@ -771,6 +771,16 @@ type cUsage struct {
|
||||
CachedTokens int `json:"cached_tokens"`
|
||||
CacheReadInputTokens int `json:"cache_read_input_tokens"`
|
||||
CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
|
||||
// what a plugin's step collected of its conversation's earlier steps,
|
||||
// which their own replies couldn't count (the Cursor plugin's usage
|
||||
// events that showed late, yetone/magpie#1053): billed with the step,
|
||||
// never its prompt, which a client reads as how full its context is
|
||||
MagpieDeferred *struct {
|
||||
PromptTokens int `json:"prompt_tokens"`
|
||||
CompletionTokens int `json:"completion_tokens"`
|
||||
CachedTokens int `json:"cached_tokens"`
|
||||
CacheWriteTokens int `json:"cache_write_tokens"`
|
||||
} `json:"magpie_deferred,omitempty"`
|
||||
}
|
||||
|
||||
func (u cUsage) usage() Usage {
|
||||
@@ -797,6 +807,10 @@ func (u cUsage) usage() Usage {
|
||||
if u.CompletionTokensDetails != nil {
|
||||
out.Reasoning = u.CompletionTokensDetails.ReasoningTokens
|
||||
}
|
||||
if d := u.MagpieDeferred; d != nil && d.PromptTokens+d.CompletionTokens > 0 {
|
||||
out.Deferred = &Usage{Input: max(d.PromptTokens-d.CachedTokens-d.CacheWriteTokens, 0), Output: d.CompletionTokens,
|
||||
CacheRead: d.CachedTokens, CacheWrite: d.CacheWriteTokens}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -1015,7 +1029,7 @@ func (d *chatDecoder) decode(data string, emit func(Event)) error {
|
||||
emit(Event{Kind: KStop, Stop: stopFromChat(c.FinishReason)})
|
||||
}
|
||||
}
|
||||
if ch.Usage != nil && (ch.Usage.PromptTokens > 0 || ch.Usage.CompletionTokens > 0) {
|
||||
if ch.Usage != nil && (ch.Usage.PromptTokens > 0 || ch.Usage.CompletionTokens > 0 || ch.Usage.MagpieDeferred != nil) {
|
||||
emit(Event{Kind: KUsage, Usage: ch.Usage.usage()})
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
// The Cursor plugin's step that collected an earlier step's late usage
|
||||
// event (yetone/magpie#1053) tells it apart, as magpie_deferred: the
|
||||
// step's prompt_tokens stay its own, which a client reads as how full its
|
||||
// context is (pi read 366940 = 181270 + 185670 of a 300k window, where
|
||||
// 185670 was used), and magpie bills both.
|
||||
const deferredJSON = `{"id":"c","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":185670,"completion_tokens":2240,"total_tokens":187910,"prompt_tokens_details":{"cached_tokens":181266,"cache_write_tokens":4400},"magpie_deferred":{"prompt_tokens":181270,"completion_tokens":1913,"cached_tokens":177533,"cache_write_tokens":3735}}}`
|
||||
|
||||
var deferredStream = "data: " + deferredJSON + "\n\ndata: [DONE]\n\n"
|
||||
|
||||
func TestSniffChatDeferredUsage(t *testing.T) {
|
||||
s := newSniffer(provider.Chat, "text/event-stream")
|
||||
s.write([]byte(deferredStream))
|
||||
got := s.usage()
|
||||
if d := got.Deferred; d == nil || *d != (Usage{Input: 2, Output: 1913, CacheRead: 177533, CacheWrite: 3735}) {
|
||||
t.Fatalf("deferred %+v", got.Deferred)
|
||||
}
|
||||
got.Deferred = nil
|
||||
if own := (Usage{Input: 4, Output: 2240, CacheRead: 181266, CacheWrite: 4400, ResponseID: "c", Stop: "tool_calls"}); got != own {
|
||||
t.Fatalf("own %+v want %+v", got, own)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeferredUsageIsBilledNotPrompt(t *testing.T) {
|
||||
s := newSniffer(provider.Chat, "text/event-stream")
|
||||
s.write([]byte(deferredStream))
|
||||
u := s.usage()
|
||||
b := u.billed()
|
||||
if b.Deferred != nil || b.Input != 6 || b.Output != 2240+1913 || b.CacheRead != 181266+177533 || b.CacheWrite != 4400+3735 {
|
||||
t.Fatalf("billed %+v", b)
|
||||
}
|
||||
if u.prompt() != 185670 {
|
||||
t.Fatalf("the request's own prompt %d", u.prompt())
|
||||
}
|
||||
rs := routeUsage("cursor", "claude-opus-5-5", u)
|
||||
if len(rs) != 2 {
|
||||
t.Fatalf("tiers %+v", rs)
|
||||
}
|
||||
// the route's prompt, as its context is read, is the request's own
|
||||
if n := promptCounted(rs); n != 185670 {
|
||||
t.Fatalf("promptCounted %d", n)
|
||||
}
|
||||
var in, out int
|
||||
for _, r := range rs {
|
||||
in += r.Input + r.CacheRead + r.CacheWrite
|
||||
out += r.Output
|
||||
}
|
||||
if in != 185670+181270 || out != 2240+1913 {
|
||||
t.Fatalf("priced %d in %d out", in, out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatDecoderKeepsDeferredUsage(t *testing.T) {
|
||||
d := &chatDecoder{}
|
||||
var u Usage
|
||||
for _, line := range []string{`{"id":"c","choices":[{"index":0,"delta":{"content":""}}]}`, deferredJSON} {
|
||||
if err := d.decode(line, func(ev Event) {
|
||||
if ev.Kind == KUsage {
|
||||
u.add(ev.Usage)
|
||||
}
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if u.prompt() != 185670 || u.Deferred == nil || u.Deferred.prompt() != 181270 {
|
||||
t.Fatalf("usage %+v deferred %+v", u, u.Deferred)
|
||||
}
|
||||
// a client of another API is told the request's own, as before
|
||||
if c := u.chat(); c["prompt_tokens"] != 185670 {
|
||||
t.Fatalf("told %v", c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoDeferredUsageAsBefore(t *testing.T) {
|
||||
s := newSniffer(provider.Chat, "text/event-stream")
|
||||
s.write([]byte("data: {\"choices\":[],\"usage\":{\"prompt_tokens\":100,\"completion_tokens\":20,\"prompt_tokens_details\":{\"cached_tokens\":60}}}\n\n"))
|
||||
u := s.usage()
|
||||
if u.Deferred != nil || u.billed() != u || len(routeUsage("p", "m", u)) != 1 {
|
||||
t.Fatalf("%+v", u)
|
||||
}
|
||||
}
|
||||
|
||||
// a real step of the Cursor plugin, its tool steps' events collected late
|
||||
// (STEP_WAIT shortened): its own prompt 1371, and 2619 of earlier steps
|
||||
const realDeferredChunk = `{"id":"chatcmpl-71dd4976e7f654f774cd7619","object":"chat.completion.chunk","created":1791866687,"model":"composer-2.5","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":1371,"completion_tokens":48,"total_tokens":1419,"prompt_tokens_details":{"cached_tokens":1328,"cache_write_tokens":0},"magpie_deferred":{"prompt_tokens":2619,"completion_tokens":106,"cached_tokens":2533,"cache_write_tokens":0}}}`
|
||||
|
||||
// Claude Code on Cursor: the chat reply is translated, and Claude Code is
|
||||
// told the step's own prompt, while magpie bills the earlier steps' too
|
||||
func TestTranslatedReplyTellsOwnUsageBillsDeferred(t *testing.T) {
|
||||
d := &chatDecoder{}
|
||||
var c collector
|
||||
if err := d.decode(realDeferredChunk, c.add); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res := c.finish()
|
||||
if res.Usage.prompt() != 1371 || res.Usage.Deferred == nil || res.Usage.Deferred.prompt() != 2619 || res.Usage.Deferred.Output != 106 {
|
||||
t.Fatalf("usage %+v deferred %+v", res.Usage, res.Usage.Deferred)
|
||||
}
|
||||
a := res.Usage.anthropic()
|
||||
if a.InputTokens+a.CacheReadInputTokens+a.CacheCreationInputTokens != 1371 || a.OutputTokens != 48 {
|
||||
t.Fatalf("told Claude Code %+v", a)
|
||||
}
|
||||
if b := res.Usage.billed(); b.prompt() != 1371+2619 || b.Output != 48+106 {
|
||||
t.Fatalf("billed %+v", b)
|
||||
}
|
||||
}
|
||||
|
||||
// Through the whole gateway: a client is told the request's own usage and
|
||||
// never magpie_deferred's, while the ledger and the OTel span carry both.
|
||||
// own 0 is a step whose event showed late: only its deferred is in the reply.
|
||||
func TestDeferredUsageThroughTheGateway(t *testing.T) {
|
||||
const deferred = `"magpie_deferred":{"prompt_tokens":181270,"completion_tokens":1913,"cached_tokens":177533,"cache_write_tokens":3735}`
|
||||
own := `"usage":{"prompt_tokens":185670,"completion_tokens":2240,"prompt_tokens_details":{"cached_tokens":181266,"cache_write_tokens":4400},` + deferred + `}`
|
||||
none := `"usage":{"prompt_tokens":0,"completion_tokens":0,` + deferred + `}`
|
||||
chat := func(usage string) string {
|
||||
return `{"id":"c","model":"m1","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"tool_calls"}],` + usage + `}`
|
||||
}
|
||||
stream := func(usage string) string {
|
||||
return sse(`data: {"id":"c","model":"m1","choices":[{"index":0,"delta":{"content":"ok"}}]}`,
|
||||
`data: {"id":"c","model":"m1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],`+usage+`}`, "data: [DONE]")
|
||||
}
|
||||
for _, c := range []struct {
|
||||
name, ctype, reply, path, request string
|
||||
in, out, read, write int
|
||||
}{
|
||||
{"chat reply", "application/json", chat(own), "/v1/chat/completions", `{"model":"m1","messages":[{"role":"user","content":"hi"}]}`, 6, 4153, 358799, 8135},
|
||||
{"chat stream", "", stream(own), "/v1/chat/completions", `{"model":"m1","stream":true,"messages":[{"role":"user","content":"hi"}]}`, 6, 4153, 358799, 8135},
|
||||
{"translated for Claude Code", "", stream(own), "/v1/messages", `{"model":"m1","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`, 6, 4153, 358799, 8135},
|
||||
{"own is 0", "application/json", chat(none), "/v1/chat/completions", `{"model":"m1","messages":[{"role":"user","content":"hi"}]}`, 2, 1913, 177533, 3735},
|
||||
{"own is 0, streamed", "", stream(none), "/v1/chat/completions", `{"model":"m1","stream":true,"messages":[{"role":"user","content":"hi"}]}`, 2, 1913, 177533, 3735},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
setup(t, provider.Chat, &fake{ctype: c.ctype, reply: c.reply})
|
||||
received := make(chan string, 1)
|
||||
collector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
received <- string(b)
|
||||
io.WriteString(w, `{}`)
|
||||
}))
|
||||
defer collector.Close()
|
||||
t.Setenv("MAGPIE_OTEL_ENABLED", "true")
|
||||
t.Setenv("MAGPIE_OTEL_ENDPOINT", collector.URL)
|
||||
t.Setenv("MAGPIE_OTEL_HEADERS", "")
|
||||
t.Setenv("MAGPIE_OTEL_METRICS", "false")
|
||||
fastOTel(t)
|
||||
stop := usage.StartOTel()
|
||||
t.Cleanup(stop)
|
||||
code, body := post(t, c.path, c.request)
|
||||
if code != 200 {
|
||||
t.Fatalf("gateway: %d %s", code, body)
|
||||
}
|
||||
stop()
|
||||
if c.path == "/v1/messages" && strings.Contains(body, "magpie_deferred") {
|
||||
t.Errorf("Claude Code was told magpie_deferred: %s", body)
|
||||
}
|
||||
if r := lastUsage(t); r.Input != c.in || r.Output != c.out || r.CacheRead != c.read || r.CacheWrite != c.write {
|
||||
t.Errorf("ledger %+v", r)
|
||||
}
|
||||
select {
|
||||
case exported := <-received:
|
||||
// the span carries what the ledger does
|
||||
if !strings.Contains(exported, fmt.Sprintf(`"intValue":"%d"`, c.out)) || !strings.Contains(exported, fmt.Sprintf(`"intValue":"%d"`, c.read)) {
|
||||
t.Errorf("span: %s", exported)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Error("gateway usage was not exported")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// a step with nothing of its own and an earlier step's usage still tells
|
||||
// the gateway (chatDecoder gave up on a usage of 0 prompt and 0 completion)
|
||||
func TestChatDecoderKeepsDeferredUsageWithNoOwn(t *testing.T) {
|
||||
d := &chatDecoder{}
|
||||
var got []Usage
|
||||
line := `{"id":"c","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":0,"completion_tokens":0,"magpie_deferred":{"prompt_tokens":1148,"completion_tokens":50,"cached_tokens":1100,"cache_write_tokens":0}}}`
|
||||
if err := d.decode(line, func(ev Event) {
|
||||
if ev.Kind == KUsage {
|
||||
got = append(got, ev.Usage)
|
||||
}
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 1 || got[0].prompt() != 0 || got[0].Deferred == nil || got[0].Deferred.prompt() != 1148 || got[0].Deferred.Output != 50 {
|
||||
t.Fatalf("usage %+v", got)
|
||||
}
|
||||
}
|
||||
@@ -2449,8 +2449,8 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
rec := usage.Record{RouteID: tr.ID, Time: began, Agent: call.Agent, Via: call.Via, Provider: call.Provider, Host: where, Model: c.model,
|
||||
ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: providerAccount,
|
||||
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,
|
||||
Input: call.Usage.billed().Input, Output: call.Usage.billed().Output, CacheRead: call.Usage.billed().CacheRead,
|
||||
CacheWrite: call.Usage.billed().CacheWrite, CacheWrite1h: call.Usage.billed().CacheWrite1h, Reasoning: call.Usage.billed().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}
|
||||
@@ -2493,8 +2493,8 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
rec := usage.Record{RouteID: tr.ID, Time: began, Agent: call.Agent, Via: call.Via, Provider: call.Provider, Host: where, Model: c.model,
|
||||
ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: providerAccount,
|
||||
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,
|
||||
Input: call.Usage.billed().Input, Output: call.Usage.billed().Output, CacheRead: call.Usage.billed().CacheRead,
|
||||
CacheWrite: call.Usage.billed().CacheWrite, CacheWrite1h: call.Usage.billed().CacheWrite1h, Reasoning: call.Usage.billed().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}
|
||||
@@ -2930,8 +2930,8 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
rec := usage.Record{RouteID: tr.ID, Time: start, Agent: call.Agent, Via: call.Via, Provider: call.Provider, Host: where, Model: model,
|
||||
ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: providerAccount,
|
||||
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,
|
||||
Input: call.Usage.billed().Input, Output: call.Usage.billed().Output, CacheRead: call.Usage.billed().CacheRead,
|
||||
CacheWrite: call.Usage.billed().CacheWrite, CacheWrite1h: call.Usage.billed().CacheWrite1h, Reasoning: call.Usage.billed().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()}
|
||||
|
||||
@@ -327,6 +327,25 @@ type Usage struct {
|
||||
// Tier is the service tier the reply says it ran at (upstreamTier),
|
||||
// "" when it says none
|
||||
Tier string `json:"tier,omitempty"`
|
||||
// Deferred is what the reply counted of earlier requests of its
|
||||
// conversation, which their own replies couldn't (cUsage's
|
||||
// MagpieDeferred): billed with this one, never told as its prompt
|
||||
Deferred *Usage `json:"deferred,omitempty"`
|
||||
}
|
||||
|
||||
// billed is what the request is billed for: its own count, and what it
|
||||
// counted of earlier ones (Deferred).
|
||||
func (u Usage) billed() Usage {
|
||||
if d := u.Deferred; d != nil {
|
||||
u.Input += d.Input
|
||||
u.Output += d.Output
|
||||
u.CacheRead += d.CacheRead
|
||||
u.CacheWrite += d.CacheWrite
|
||||
u.CacheWrite1h += d.CacheWrite1h
|
||||
u.Reasoning += d.Reasoning
|
||||
u.Deferred = nil
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
// prompt is every token the prompt came to, as OpenAI's and Gemini's
|
||||
@@ -376,6 +395,9 @@ func (u *Usage) add(v Usage) {
|
||||
if v.Stop != "" {
|
||||
u.Stop = v.Stop
|
||||
}
|
||||
if v.Deferred != nil {
|
||||
u.Deferred = v.Deferred
|
||||
}
|
||||
}
|
||||
|
||||
// Result is a whole reply, for non-streaming clients.
|
||||
|
||||
@@ -111,7 +111,7 @@ func (t *otelRequest) attempt(call Call, attempt Try, providerID, effort string,
|
||||
return
|
||||
}
|
||||
span := &usage.OTelSpan{TraceID: t.root.TraceID, SpanID: otelID(8), ParentID: t.root.SpanID, End: time.Now()}
|
||||
u := call.Usage
|
||||
u := call.Usage.billed()
|
||||
rec := usage.Record{OTel: span, RouteID: t.routeID, Time: attempt.Start, Agent: call.Agent,
|
||||
Provider: providerID, Model: attempt.Model, Requested: call.Model, Served: u.Served, Effort: effort,
|
||||
Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite, Reasoning: u.Reasoning,
|
||||
|
||||
@@ -544,10 +544,18 @@ func swapped(sent, served string) bool { return usage.Swapped(sent, served) }
|
||||
|
||||
// routeUsage retains only what pricing needs, without another copy of the
|
||||
// request's metadata. Unknown token counts have no price, including failures.
|
||||
// What the reply counted of earlier requests (Deferred) is priced as a tier
|
||||
// of its own before the request's, which stays last: the prompt is read
|
||||
// from the last (promptCounted), and is the request's own.
|
||||
func routeUsage(id, model string, u Usage) []RouteUsage {
|
||||
if u.Input+u.Output == 0 {
|
||||
return nil
|
||||
var out []RouteUsage
|
||||
if d := u.Deferred; d != nil && d.Input+d.Output+d.CacheRead+d.CacheWrite > 0 {
|
||||
out = append(out, RouteUsage{Provider: id, Model: model, Input: d.Input, Output: d.Output,
|
||||
CacheRead: d.CacheRead, CacheWrite: d.CacheWrite, Reasoning: d.Reasoning})
|
||||
}
|
||||
return []RouteUsage{{Provider: id, Model: model, Input: u.Input, Output: u.Output,
|
||||
CacheRead: u.CacheRead, CacheWrite: u.CacheWrite, Reasoning: u.Reasoning}}
|
||||
if u.Input+u.Output == 0 {
|
||||
return out
|
||||
}
|
||||
return append(out, RouteUsage{Provider: id, Model: model, Input: u.Input, Output: u.Output,
|
||||
CacheRead: u.CacheRead, CacheWrite: u.CacheWrite, Reasoning: u.Reasoning})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user