OpenAI bills gpt-6-astra, gpt-6.1-sol and gpt-6-luna over 272K input at 2× input and cache and 1.5× output, for the whole request. A price now has tiers: `magpie model price <m> 10,50,1,12.5 --tier 272k 20,75,2,25` (--tier can repeat). A tier applies when input + cache reads + cache writes is over its size, so 272,000 is not over and 272,001 is. The built-in prices take tiers only where models.dev lists one (cost.tiers of type "context"), and it does list one for those three. The ledger, each request and OTLP are costed at the tier the call reached. Session and day totals sum many calls, so they stay at the base price.
Anthropic bills a cache write kept for an hour at 2× input and one kept for 5 minutes at 1.25×. Its usage reports which is which in cache_creation.ephemeral_5m/1h_input_tokens. The gateway (API and Claude subscription) and Claude Code's transcripts now keep that split. A price's fifth part is the 1-hour write. When it isn't given, it is 2× input: that is Anthropic's rule, and only Anthropic reports 1-hour writes. Claude list prices carry the 2× too. cache_write_tokens is still the total, and the usage CSV adds cache_write_5m_tokens and cache_write_1h_tokens at the end. The app shows the split on a request's Cache and on the usage tooltips. Old prices and old records, which have no 1-hour part, read as before. The sessions cache (18) and the call cache (calls-v8) are re-read once.
In the GUI, the price boxes were number inputs and dropped what they didn't parse ("0,25"). They are now decimal text boxes that take both "0.25" and "0,25". A model's price row has a 1-hour box (empty means 2× input) and a quiet Long-context price row. That row shows the list's tier greyed in, or sits behind a link when the list has none. A bad size is refused by name. en/zh/ja/de.
Tests:
- New: TestPriceTiers, TestCostSplit, TestPriceJSON, TestModelPriceTiers, TestModelPriceTierCmd, TestAnthropicCacheWriteSplit and TestClaudeCacheWriteSplit. The ledger CSV test expects the new columns.
- model-price-tiers.test.cjs is new; model-price-edit and provider-price-rate are updated. All of them fail against the old assets and pass in WebKit. Chromium couldn't be launched here.
- go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass.
322 lines
11 KiB
Go
322 lines
11 KiB
Go
package usage
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/binary"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type otelAttribute struct {
|
|
Key string `json:"key"`
|
|
Value map[string]any `json:"value"`
|
|
}
|
|
|
|
func otelString(key, value string) otelAttribute {
|
|
return otelAttribute{key, map[string]any{"stringValue": value}}
|
|
}
|
|
func otelInt(key string, value int64) otelAttribute {
|
|
return otelAttribute{key, map[string]any{"intValue": strconv.FormatInt(value, 10)}}
|
|
}
|
|
|
|
// Only this allowlist leaves the machine: never record JSON, account/key
|
|
// names, session titles, raw errors, prompts, completions or tool arguments.
|
|
// The one exception is traces' input and output, sent only when the user
|
|
// turned bodies on (#538).
|
|
func otelAttributes(r Record) []otelAttribute {
|
|
op := r.Operation
|
|
if op == "" {
|
|
op = "chat"
|
|
}
|
|
a := []otelAttribute{otelString("gen_ai.operation.name", op), otelString("gen_ai.provider.name", r.Provider), otelString("gen_ai.request.model", r.Model), otelString("magpie.agent", r.Agent)}
|
|
if r.Served != "" {
|
|
a = append(a, otelString("gen_ai.response.model", r.Served))
|
|
}
|
|
if r.Failed() {
|
|
errType := "stream_error"
|
|
if r.Status >= 400 {
|
|
errType = strconv.Itoa(r.Status)
|
|
}
|
|
a = append(a, otelString("error.type", errType))
|
|
}
|
|
return a
|
|
}
|
|
|
|
func otelEnvelope(signal string, data any) map[string]any {
|
|
return map[string]any{"resource" + signal: []any{map[string]any{
|
|
"resource": map[string]any{"attributes": []otelAttribute{otelString("service.name", "magpie")}},
|
|
"scope" + signal: []any{map[string]any{"scope": map[string]any{"name": "github.com/yetone/magpie"}, map[string]string{"Spans": "spans", "Metrics": "metrics"}[signal]: data}},
|
|
}}}
|
|
}
|
|
|
|
// OTelSpan carries explicit IDs for gateway requests and agent-session observations.
|
|
type OTelSpan struct {
|
|
TraceID, SpanID, ParentID string
|
|
Root bool
|
|
End time.Time
|
|
Name, Type, SessionID, TraceName string
|
|
Session, Inferred, Update bool
|
|
}
|
|
|
|
func (e *otelExporter) traces(records []Record) any {
|
|
spans := make([]any, 0, len(records))
|
|
priceOf := pricer()
|
|
for _, r := range records {
|
|
var traceID [16]byte
|
|
if r.OTel == nil {
|
|
if r.RouteID != 0 {
|
|
copy(traceID[:8], e.salt[:])
|
|
binary.BigEndian.PutUint64(traceID[8:], uint64(r.RouteID))
|
|
} else {
|
|
rand.Read(traceID[:])
|
|
}
|
|
}
|
|
var spanID [8]byte
|
|
if r.OTel == nil {
|
|
rand.Read(spanID[:])
|
|
}
|
|
a := append(otelAttributes(r), otelInt("http.response.status_code", int64(r.Status)),
|
|
otelInt("gen_ai.usage.input_tokens", int64(r.Input+r.CacheRead+r.CacheWrite)), otelInt("gen_ai.usage.output_tokens", int64(r.Output)),
|
|
otelInt("gen_ai.usage.cache_read.input_tokens", int64(r.CacheRead)), otelInt("gen_ai.usage.cache_creation.input_tokens", int64(r.CacheWrite)),
|
|
otelInt("gen_ai.usage.reasoning.output_tokens", int64(r.Reasoning)), otelInt("magpie.ttft_ms", r.TTFT), otelInt("magpie.first_text_ms", r.FirstText))
|
|
if r.RouteID != 0 {
|
|
a = append(a, otelInt("magpie.route.id", r.RouteID))
|
|
}
|
|
if r.Requested != "" {
|
|
a = append(a, otelString("magpie.requested_model", r.Requested))
|
|
}
|
|
if r.Effort != "" {
|
|
a = append(a, otelString("magpie.reasoning_effort", r.Effort))
|
|
}
|
|
if r.BodyIn != "" {
|
|
a = append(a, otelString("langfuse.observation.input", r.BodyIn))
|
|
}
|
|
if r.BodyOut != "" {
|
|
a = append(a, otelString("langfuse.observation.output", otelReplyText(r.BodyOut)))
|
|
}
|
|
status := 0
|
|
if r.Failed() {
|
|
status = 2
|
|
}
|
|
op := r.Operation
|
|
if op == "" {
|
|
op = "chat"
|
|
}
|
|
span := map[string]any{"traceId": hex.EncodeToString(traceID[:]), "spanId": hex.EncodeToString(spanID[:]),
|
|
"name": op + " " + r.Model, "kind": 3, "flags": 1,
|
|
"startTimeUnixNano": strconv.FormatInt(r.Time.UnixNano(), 10), "endTimeUnixNano": strconv.FormatInt(r.Time.Add(time.Duration(r.Millis)*time.Millisecond).UnixNano(), 10),
|
|
"attributes": a, "status": map[string]any{"code": status}}
|
|
if r.OTel != nil {
|
|
span["traceId"], span["spanId"] = r.OTel.TraceID, r.OTel.SpanID
|
|
if !r.OTel.End.IsZero() {
|
|
span["endTimeUnixNano"] = strconv.FormatInt(r.OTel.End.UnixNano(), 10)
|
|
}
|
|
if r.OTel.ParentID != "" {
|
|
span["parentSpanId"] = r.OTel.ParentID
|
|
}
|
|
if r.OTel.Root {
|
|
span["name"], span["kind"] = "gateway "+r.Model, 2
|
|
a = []otelAttribute{otelString("magpie.agent", r.Agent), otelString("magpie.requested_model", r.Model), otelInt("http.response.status_code", int64(r.Status))}
|
|
if r.RouteID != 0 {
|
|
a = append(a, otelInt("magpie.route.id", r.RouteID))
|
|
}
|
|
if r.Status >= 400 {
|
|
a = append(a, otelString("error.type", strconv.Itoa(r.Status)))
|
|
}
|
|
a = append(a, otelString("langfuse.observation.type", "span"))
|
|
} else {
|
|
a = append(a, otelString("langfuse.observation.type", "generation"))
|
|
}
|
|
if r.OTel.Session {
|
|
span["name"], span["kind"] = r.OTel.Name, 1
|
|
if r.OTel.Type != "generation" {
|
|
a = []otelAttribute{otelString("magpie.agent", r.Agent)}
|
|
if r.Status >= 400 {
|
|
a = append(a, otelString("error.type", "agent_operation_failed"))
|
|
}
|
|
}
|
|
a = append(a, otelString("langfuse.session.id", r.OTel.SessionID), otelString("langfuse.trace.name", r.OTel.TraceName))
|
|
// Replace the gateway-specific observation type, keeping the wire allowlist explicit.
|
|
filtered := a[:0]
|
|
for _, attr := range a {
|
|
if attr.Key != "langfuse.observation.type" {
|
|
filtered = append(filtered, attr)
|
|
}
|
|
}
|
|
a = append(filtered, otelString("langfuse.observation.type", r.OTel.Type))
|
|
if r.OTel.Inferred {
|
|
a = append(a, otelString("magpie.timing.source", "inferred"))
|
|
} else {
|
|
a = append(a, otelString("magpie.timing.source", "recorded"))
|
|
}
|
|
if r.OTel.Type != "generation" {
|
|
if r.BodyIn != "" {
|
|
a = append(a, otelString("langfuse.observation.input", r.BodyIn))
|
|
}
|
|
if r.BodyOut != "" {
|
|
a = append(a, otelString("langfuse.observation.output", r.BodyOut))
|
|
}
|
|
}
|
|
}
|
|
span["attributes"] = a
|
|
}
|
|
// Price only model calls, never their gateway/conversation parents or
|
|
// tools. Cache reads/writes belong to input cost; reasoning is already
|
|
// included in output tokens. Use the ledger's effective tariff, including
|
|
// explicit free models, and leave unknown prices for Langfuse to infer.
|
|
generation := r.OTel == nil || !r.OTel.Root && (!r.OTel.Session || r.OTel.Type == "generation")
|
|
if generation && !r.IsRejected() {
|
|
if pr := priceOf(r); pr != nil {
|
|
// the call's tier, by its whole input, for both halves
|
|
f := pr.At(r.Input + r.CacheRead + r.CacheWrite)
|
|
cost, err := json.Marshal(map[string]float64{
|
|
"input": f.CostSplit(r.Input, 0, r.CacheRead, r.CacheWrite, r.CacheWrite1h),
|
|
"output": f.Cost(0, r.Output, 0, 0),
|
|
"total": r.CostAt(*pr),
|
|
})
|
|
if err == nil {
|
|
a = append(a, otelString("langfuse.observation.cost_details", string(cost)))
|
|
span["attributes"] = a
|
|
}
|
|
}
|
|
}
|
|
spans = append(spans, span)
|
|
}
|
|
return otelEnvelope("Spans", spans)
|
|
}
|
|
|
|
type otelHistogram struct {
|
|
Attributes []otelAttribute `json:"attributes"`
|
|
Start string `json:"startTimeUnixNano"`
|
|
Time string `json:"timeUnixNano"`
|
|
Count uint64 `json:"count,string"`
|
|
Sum float64 `json:"sum"`
|
|
Bounds []float64 `json:"explicitBounds"`
|
|
Buckets []uint64 `json:"bucketCounts"`
|
|
}
|
|
|
|
// OTLP uint64 bucket counts use decimal strings, like count and timestamps.
|
|
func (h otelHistogram) MarshalJSON() ([]byte, error) {
|
|
type wire otelHistogram
|
|
buckets := make([]string, len(h.Buckets))
|
|
for i, n := range h.Buckets {
|
|
buckets[i] = strconv.FormatUint(n, 10)
|
|
}
|
|
return json.Marshal(struct {
|
|
wire
|
|
Buckets []string `json:"bucketCounts"`
|
|
}{wire(h), buckets})
|
|
}
|
|
|
|
func otelMetrics(records []Record, start, end time.Time) any {
|
|
type metric struct {
|
|
name, unit string
|
|
bounds []float64
|
|
points map[string]*otelHistogram
|
|
}
|
|
metrics := []metric{
|
|
{"gen_ai.client.operation.duration", "s", []float64{.01, .02, .04, .08, .16, .32, .64, 1.28, 2.56, 5.12, 10.24, 20.48, 40.96, 81.92}, map[string]*otelHistogram{}},
|
|
{"gen_ai.client.token.usage", "{token}", []float64{1, 4, 16, 64, 256, 1024, 4096, 16384, 65536, 262144, 1048576}, map[string]*otelHistogram{}},
|
|
}
|
|
add := func(m *metric, attrs []otelAttribute, value float64) {
|
|
key, _ := json.Marshal(attrs)
|
|
h := m.points[string(key)]
|
|
if h == nil {
|
|
h = &otelHistogram{Attributes: attrs, Start: strconv.FormatInt(start.UnixNano(), 10), Time: strconv.FormatInt(end.UnixNano(), 10), Bounds: m.bounds, Buckets: make([]uint64, len(m.bounds)+1)}
|
|
m.points[string(key)] = h
|
|
}
|
|
h.Count++
|
|
h.Sum += value
|
|
i := sort.SearchFloat64s(m.bounds, value)
|
|
h.Buckets[i]++
|
|
}
|
|
for _, r := range records {
|
|
a := otelAttributes(r)
|
|
add(&metrics[0], a, float64(r.Millis)/1000)
|
|
for _, token := range []struct {
|
|
kind string
|
|
count int
|
|
}{{"input", r.Input + r.CacheRead + r.CacheWrite}, {"output", r.Output}} {
|
|
add(&metrics[1], append(append([]otelAttribute(nil), a...), otelString("gen_ai.token.type", token.kind)), float64(token.count))
|
|
}
|
|
}
|
|
out := make([]any, 0, len(metrics))
|
|
for _, m := range metrics {
|
|
keys := make([]string, 0, len(m.points))
|
|
for key := range m.points {
|
|
keys = append(keys, key)
|
|
}
|
|
sort.Strings(keys)
|
|
points := make([]*otelHistogram, 0, len(keys))
|
|
for _, key := range keys {
|
|
points = append(points, m.points[key])
|
|
}
|
|
out = append(out, map[string]any{"name": m.name, "unit": m.unit, "histogram": map[string]any{"aggregationTemporality": 1, "dataPoints": points}})
|
|
}
|
|
return otelEnvelope("Metrics", out)
|
|
}
|
|
|
|
// otelReplyText is a streamed reply's text, put together from its events
|
|
// (Chat Completions' choices[].delta.content, Responses'
|
|
// response.output_text.delta, Anthropic's content_block_delta), so the
|
|
// trace shows what the model wrote rather than a few hundred SSE events; a
|
|
// reply that isn't a stream, or one with no text in it (only tool calls),
|
|
// goes as it came.
|
|
func otelReplyText(body string) string {
|
|
if !strings.Contains(body, "data:") {
|
|
return body
|
|
}
|
|
body, cut := strings.CutSuffix(body, BodyCut)
|
|
var text strings.Builder
|
|
for _, line := range strings.Split(body, "\n") {
|
|
data, ok := strings.CutPrefix(strings.TrimSpace(line), "data:")
|
|
if !ok {
|
|
continue
|
|
}
|
|
var ev struct {
|
|
Type string `json:"type"`
|
|
Delta json.RawMessage `json:"delta"`
|
|
Choices []struct {
|
|
Delta struct {
|
|
Content string `json:"content"`
|
|
} `json:"delta"`
|
|
} `json:"choices"`
|
|
}
|
|
if json.Unmarshal([]byte(strings.TrimSpace(data)), &ev) != nil {
|
|
continue
|
|
}
|
|
for _, c := range ev.Choices {
|
|
text.WriteString(c.Delta.Content)
|
|
}
|
|
switch ev.Type {
|
|
case "response.output_text.delta":
|
|
var d string
|
|
if json.Unmarshal(ev.Delta, &d) == nil {
|
|
text.WriteString(d)
|
|
}
|
|
case "content_block_delta":
|
|
var d struct {
|
|
Text string `json:"text"`
|
|
}
|
|
if json.Unmarshal(ev.Delta, &d) == nil {
|
|
text.WriteString(d.Text)
|
|
}
|
|
}
|
|
}
|
|
if text.Len() == 0 {
|
|
text.Reset()
|
|
text.WriteString(body)
|
|
}
|
|
if cut {
|
|
text.WriteString(BodyCut)
|
|
}
|
|
return text.String()
|
|
}
|
|
|
|
// BodyCut ends a body the gateway captured only the start of.
|
|
const BodyCut = "\n… (cut here by magpie)"
|