forked from QuantumNous/new-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrankings.go
More file actions
597 lines (538 loc) · 17.2 KB
/
Copy pathrankings.go
File metadata and controls
597 lines (538 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
package service
import (
"fmt"
"math"
"sort"
"sync"
"time"
"github.com/QuantumNous/new-api/model"
)
const (
rankingCacheTTL = 5 * time.Minute
rankingLeaderboardLimit = 20
rankingHistoryLimit = 10
rankingVendorLimit = 5
rankingMoverLimit = 6
rankingOthersLabel = "Others"
rankingUnknownVendor = "Unknown"
)
type RankingsResponse struct {
Models []RankedModel `json:"models"`
Vendors []RankedVendor `json:"vendors"`
TopMovers []RankingMover `json:"top_movers"`
TopDroppers []RankingMover `json:"top_droppers"`
ModelsHistory ModelHistorySeries `json:"models_history"`
VendorShareHistory VendorShareSeries `json:"vendor_share_history"`
}
type RankedModel struct {
Rank int `json:"rank"`
PreviousRank *int `json:"previous_rank,omitempty"`
ModelName string `json:"model_name"`
Vendor string `json:"vendor"`
VendorIcon string `json:"vendor_icon,omitempty"`
Category string `json:"category"`
TotalTokens int64 `json:"total_tokens"`
Share float64 `json:"share"`
GrowthPct float64 `json:"growth_pct"`
}
type RankedVendor struct {
Rank int `json:"rank"`
Vendor string `json:"vendor"`
VendorIcon string `json:"vendor_icon,omitempty"`
TotalTokens int64 `json:"total_tokens"`
Share float64 `json:"share"`
GrowthPct float64 `json:"growth_pct"`
ModelsCount int `json:"models_count"`
TopModel string `json:"top_model"`
}
type RankingMover struct {
ModelName string `json:"model_name"`
Vendor string `json:"vendor"`
VendorIcon string `json:"vendor_icon,omitempty"`
RankDelta int `json:"rank_delta"`
CurrentRank int `json:"current_rank"`
GrowthPct float64 `json:"growth_pct"`
}
type ModelHistoryPoint struct {
Ts string `json:"ts"`
Label string `json:"label"`
Model string `json:"model"`
Vendor string `json:"vendor"`
Tokens int64 `json:"tokens"`
}
type ModelHistoryModel struct {
Name string `json:"name"`
Vendor string `json:"vendor"`
Total int64 `json:"total"`
}
type ModelHistorySeries struct {
Points []ModelHistoryPoint `json:"points"`
Models []ModelHistoryModel `json:"models"`
Buckets int `json:"buckets"`
}
type VendorSharePoint struct {
Ts string `json:"ts"`
Label string `json:"label"`
Vendor string `json:"vendor"`
Share float64 `json:"share"`
Tokens int64 `json:"tokens"`
}
type VendorShareVendor struct {
Name string `json:"name"`
Total int64 `json:"total"`
Share float64 `json:"share"`
}
type VendorShareSeries struct {
Points []VendorSharePoint `json:"points"`
Vendors []VendorShareVendor `json:"vendors"`
Buckets int `json:"buckets"`
}
type rankingPeriodConfig struct {
id string
duration time.Duration
bucketSize int64
labelLayout string
hasPrevious bool
}
type rankingCacheItem struct {
expiresAt time.Time
data *RankingsResponse
}
type rankingModelMeta struct {
vendor string
vendorIcon string
}
type vendorAggregate struct {
name string
icon string
totalTokens int64
previousTokens int64
models map[string]struct{}
topModel string
topModelTokens int64
}
var (
rankingCacheMu sync.Mutex
rankingCache = map[string]rankingCacheItem{}
)
func GetRankingsSnapshot(period string) (*RankingsResponse, error) {
config, err := rankingConfig(period)
if err != nil {
return nil, err
}
now := time.Now()
rankingCacheMu.Lock()
if item, ok := rankingCache[config.id]; ok && now.Before(item.expiresAt) {
rankingCacheMu.Unlock()
return item.data, nil
}
rankingCacheMu.Unlock()
data, err := buildRankingsSnapshot(config, now)
if err != nil {
return nil, err
}
rankingCacheMu.Lock()
rankingCache[config.id] = rankingCacheItem{
expiresAt: now.Add(rankingCacheTTL),
data: data,
}
rankingCacheMu.Unlock()
return data, nil
}
func rankingConfig(period string) (rankingPeriodConfig, error) {
switch period {
case "", "week":
return rankingPeriodConfig{id: "week", duration: 7 * 24 * time.Hour, bucketSize: 24 * 3600, labelLayout: "Jan 2", hasPrevious: true}, nil
case "today":
return rankingPeriodConfig{id: "today", duration: 24 * time.Hour, bucketSize: 3600, labelLayout: "15:04", hasPrevious: true}, nil
case "month":
return rankingPeriodConfig{id: "month", duration: 30 * 24 * time.Hour, bucketSize: 24 * 3600, labelLayout: "Jan 2", hasPrevious: true}, nil
case "year":
return rankingPeriodConfig{id: "year", duration: 365 * 24 * time.Hour, bucketSize: 7 * 24 * 3600, labelLayout: "Jan 2", hasPrevious: true}, nil
default:
return rankingPeriodConfig{}, fmt.Errorf("invalid ranking period: %s", period)
}
}
func buildRankingsSnapshot(config rankingPeriodConfig, now time.Time) (*RankingsResponse, error) {
startTime, endTime := rankingTimeRange(config, now)
currentTotals, err := model.GetRankingQuotaTotals(startTime, endTime)
if err != nil {
return nil, err
}
currentBuckets, err := model.GetRankingQuotaBuckets(startTime, endTime, config.bucketSize)
if err != nil {
return nil, err
}
var previousTotals []model.RankingQuotaTotal
if config.hasPrevious {
previousStart, previousEnd := previousRankingTimeRange(config, startTime)
previousTotals, err = model.GetRankingQuotaTotals(previousStart, previousEnd)
if err != nil {
return nil, err
}
}
meta := buildRankingModelMeta()
totalTokens := sumRankingTokens(currentTotals)
previousRankByModel := rankingRankMap(previousTotals)
previousTokensByModel := rankingTokenMap(previousTotals)
rankedModels := buildRankedModels(currentTotals, totalTokens, previousRankByModel, previousTokensByModel, meta, config.hasPrevious)
vendors := buildRankedVendors(currentTotals, previousTotals, totalTokens, meta, config.hasPrevious)
modelHistory := buildModelHistory(currentBuckets, currentTotals, meta, config)
vendorHistory := buildVendorShareHistory(currentBuckets, vendors, totalTokens, meta, config)
movers, droppers := buildRankingMovers(rankedModels)
return &RankingsResponse{
Models: limitRankedModels(rankedModels, rankingLeaderboardLimit),
Vendors: vendors,
TopMovers: movers,
TopDroppers: droppers,
ModelsHistory: modelHistory,
VendorShareHistory: vendorHistory,
}, nil
}
func rankingTimeRange(config rankingPeriodConfig, now time.Time) (int64, int64) {
endTime := now.Unix()
if config.duration <= 0 {
return 0, endTime
}
return now.Add(-config.duration).Unix(), endTime
}
func previousRankingTimeRange(config rankingPeriodConfig, currentStart int64) (int64, int64) {
previousEnd := currentStart - 1
previousStart := time.Unix(currentStart, 0).Add(-config.duration).Unix()
return previousStart, previousEnd
}
func buildRankingModelMeta() map[string]rankingModelMeta {
vendorByID := make(map[int]model.PricingVendor)
for _, vendor := range model.GetVendors() {
vendorByID[vendor.ID] = vendor
}
meta := make(map[string]rankingModelMeta)
for _, pricing := range model.GetPricing() {
item := rankingModelMeta{vendor: rankingUnknownVendor}
if vendor, ok := vendorByID[pricing.VendorID]; ok {
item.vendor = vendor.Name
item.vendorIcon = vendor.Icon
} else if pricing.OwnerBy != "" {
item.vendor = pricing.OwnerBy
}
meta[pricing.ModelName] = item
}
return meta
}
func modelMeta(modelName string, meta map[string]rankingModelMeta) rankingModelMeta {
if item, ok := meta[modelName]; ok && item.vendor != "" {
return item
}
return rankingModelMeta{vendor: rankingUnknownVendor}
}
func buildRankedModels(totals []model.RankingQuotaTotal, totalTokens int64, previousRanks map[string]int, previousTokens map[string]int64, meta map[string]rankingModelMeta, showGrowth bool) []RankedModel {
rows := make([]RankedModel, 0, len(totals))
for idx, item := range totals {
modelMeta := modelMeta(item.ModelName, meta)
var previousRank *int
if rank, ok := previousRanks[item.ModelName]; ok {
rankCopy := rank
previousRank = &rankCopy
}
growth := 0.0
if showGrowth {
growth = rankingGrowthPct(item.TotalTokens, previousTokens[item.ModelName])
}
rows = append(rows, RankedModel{
Rank: idx + 1,
PreviousRank: previousRank,
ModelName: item.ModelName,
Vendor: modelMeta.vendor,
VendorIcon: modelMeta.vendorIcon,
Category: "all",
TotalTokens: item.TotalTokens,
Share: rankingShare(item.TotalTokens, totalTokens),
GrowthPct: growth,
})
}
return rows
}
func buildRankedVendors(currentTotals []model.RankingQuotaTotal, previousTotals []model.RankingQuotaTotal, totalTokens int64, meta map[string]rankingModelMeta, showGrowth bool) []RankedVendor {
aggregates := make(map[string]*vendorAggregate)
for _, item := range currentTotals {
modelMeta := modelMeta(item.ModelName, meta)
agg := ensureVendorAggregate(aggregates, modelMeta)
agg.totalTokens += item.TotalTokens
agg.models[item.ModelName] = struct{}{}
if item.TotalTokens > agg.topModelTokens {
agg.topModel = item.ModelName
agg.topModelTokens = item.TotalTokens
}
}
for _, item := range previousTotals {
modelMeta := modelMeta(item.ModelName, meta)
agg := ensureVendorAggregate(aggregates, modelMeta)
agg.previousTokens += item.TotalTokens
}
rows := make([]RankedVendor, 0, len(aggregates))
for _, agg := range aggregates {
if agg.totalTokens <= 0 {
continue
}
growth := 0.0
if showGrowth {
growth = rankingGrowthPct(agg.totalTokens, agg.previousTokens)
}
rows = append(rows, RankedVendor{
Vendor: agg.name,
VendorIcon: agg.icon,
TotalTokens: agg.totalTokens,
Share: rankingShare(agg.totalTokens, totalTokens),
GrowthPct: growth,
ModelsCount: len(agg.models),
TopModel: agg.topModel,
})
}
sort.Slice(rows, func(i, j int) bool {
if rows[i].TotalTokens == rows[j].TotalTokens {
return rows[i].Vendor < rows[j].Vendor
}
return rows[i].TotalTokens > rows[j].TotalTokens
})
for idx := range rows {
rows[idx].Rank = idx + 1
}
return rows
}
func ensureVendorAggregate(aggregates map[string]*vendorAggregate, meta rankingModelMeta) *vendorAggregate {
name := meta.vendor
if name == "" {
name = rankingUnknownVendor
}
agg, ok := aggregates[name]
if !ok {
agg = &vendorAggregate{
name: name,
icon: meta.vendorIcon,
models: make(map[string]struct{}),
}
aggregates[name] = agg
}
if agg.icon == "" && meta.vendorIcon != "" {
agg.icon = meta.vendorIcon
}
return agg
}
func buildModelHistory(buckets []model.RankingQuotaBucket, totals []model.RankingQuotaTotal, meta map[string]rankingModelMeta, config rankingPeriodConfig) ModelHistorySeries {
topModels := make(map[string]struct{})
models := make([]ModelHistoryModel, 0, minInt(len(totals), rankingHistoryLimit)+1)
otherTotal := int64(0)
for idx, item := range totals {
if idx < rankingHistoryLimit {
topModels[item.ModelName] = struct{}{}
modelMeta := modelMeta(item.ModelName, meta)
models = append(models, ModelHistoryModel{Name: item.ModelName, Vendor: modelMeta.vendor, Total: item.TotalTokens})
continue
}
otherTotal += item.TotalTokens
}
if otherTotal > 0 {
models = append(models, ModelHistoryModel{Name: rankingOthersLabel, Vendor: "Various", Total: otherTotal})
}
bucketSet := make(map[int64]struct{})
tokensByBucketAndModel := make(map[int64]map[string]int64)
for _, item := range buckets {
modelName := item.ModelName
if _, ok := topModels[modelName]; !ok {
modelName = rankingOthersLabel
}
bucketSet[item.Bucket] = struct{}{}
if _, ok := tokensByBucketAndModel[item.Bucket]; !ok {
tokensByBucketAndModel[item.Bucket] = make(map[string]int64)
}
tokensByBucketAndModel[item.Bucket][modelName] += item.Tokens
}
sortedBuckets := sortedRankingBuckets(bucketSet)
points := make([]ModelHistoryPoint, 0, len(sortedBuckets)*len(models))
for _, bucket := range sortedBuckets {
for _, historyModel := range models {
tokens := tokensByBucketAndModel[bucket][historyModel.Name]
if tokens <= 0 {
continue
}
points = append(points, ModelHistoryPoint{
Ts: rankingBucketTs(bucket),
Label: rankingBucketLabel(bucket, config),
Model: historyModel.Name,
Vendor: historyModel.Vendor,
Tokens: tokens,
})
}
}
return ModelHistorySeries{
Points: points,
Models: models,
Buckets: len(sortedBuckets),
}
}
func buildVendorShareHistory(buckets []model.RankingQuotaBucket, vendors []RankedVendor, totalTokens int64, meta map[string]rankingModelMeta, config rankingPeriodConfig) VendorShareSeries {
topVendors := make(map[string]struct{})
vendorRows := make([]VendorShareVendor, 0, minInt(len(vendors), rankingVendorLimit)+1)
otherTotal := int64(0)
for idx, vendor := range vendors {
if idx < rankingVendorLimit {
topVendors[vendor.Vendor] = struct{}{}
vendorRows = append(vendorRows, VendorShareVendor{Name: vendor.Vendor, Total: vendor.TotalTokens, Share: vendor.Share})
continue
}
otherTotal += vendor.TotalTokens
}
if otherTotal > 0 {
vendorRows = append(vendorRows, VendorShareVendor{Name: rankingOthersLabel, Total: otherTotal, Share: rankingShare(otherTotal, totalTokens)})
}
bucketSet := make(map[int64]struct{})
tokensByBucketAndVendor := make(map[int64]map[string]int64)
totalsByBucket := make(map[int64]int64)
for _, item := range buckets {
modelMeta := modelMeta(item.ModelName, meta)
vendorName := modelMeta.vendor
if _, ok := topVendors[vendorName]; !ok {
vendorName = rankingOthersLabel
}
bucketSet[item.Bucket] = struct{}{}
if _, ok := tokensByBucketAndVendor[item.Bucket]; !ok {
tokensByBucketAndVendor[item.Bucket] = make(map[string]int64)
}
tokensByBucketAndVendor[item.Bucket][vendorName] += item.Tokens
totalsByBucket[item.Bucket] += item.Tokens
}
sortedBuckets := sortedRankingBuckets(bucketSet)
points := make([]VendorSharePoint, 0, len(sortedBuckets)*len(vendorRows))
for _, bucket := range sortedBuckets {
for _, vendor := range vendorRows {
tokens := tokensByBucketAndVendor[bucket][vendor.Name]
if tokens <= 0 {
continue
}
points = append(points, VendorSharePoint{
Ts: rankingBucketTs(bucket),
Label: rankingBucketLabel(bucket, config),
Vendor: vendor.Name,
Share: rankingShare(tokens, totalsByBucket[bucket]),
Tokens: tokens,
})
}
}
return VendorShareSeries{
Points: points,
Vendors: vendorRows,
Buckets: len(sortedBuckets),
}
}
func buildRankingMovers(models []RankedModel) ([]RankingMover, []RankingMover) {
movers := make([]RankingMover, 0)
droppers := make([]RankingMover, 0)
for _, item := range models {
if item.PreviousRank == nil {
continue
}
delta := *item.PreviousRank - item.Rank
if delta == 0 {
continue
}
row := RankingMover{
ModelName: item.ModelName,
Vendor: item.Vendor,
VendorIcon: item.VendorIcon,
RankDelta: delta,
CurrentRank: item.Rank,
GrowthPct: item.GrowthPct,
}
if delta > 0 {
movers = append(movers, row)
} else {
droppers = append(droppers, row)
}
}
sort.Slice(movers, func(i, j int) bool {
if movers[i].RankDelta == movers[j].RankDelta {
return movers[i].GrowthPct > movers[j].GrowthPct
}
return movers[i].RankDelta > movers[j].RankDelta
})
sort.Slice(droppers, func(i, j int) bool {
if droppers[i].RankDelta == droppers[j].RankDelta {
return droppers[i].GrowthPct < droppers[j].GrowthPct
}
return droppers[i].RankDelta < droppers[j].RankDelta
})
return limitRankingMovers(movers, rankingMoverLimit), limitRankingMovers(droppers, rankingMoverLimit)
}
func sortedRankingBuckets(bucketSet map[int64]struct{}) []int64 {
buckets := make([]int64, 0, len(bucketSet))
for bucket := range bucketSet {
buckets = append(buckets, bucket)
}
sort.Slice(buckets, func(i, j int) bool {
return buckets[i] < buckets[j]
})
return buckets
}
func rankingBucketTs(bucket int64) string {
return time.Unix(bucket, 0).UTC().Format(time.RFC3339)
}
func rankingBucketLabel(bucket int64, config rankingPeriodConfig) string {
return time.Unix(bucket, 0).Format(config.labelLayout)
}
func rankingRankMap(totals []model.RankingQuotaTotal) map[string]int {
ranks := make(map[string]int, len(totals))
for idx, item := range totals {
ranks[item.ModelName] = idx + 1
}
return ranks
}
func rankingTokenMap(totals []model.RankingQuotaTotal) map[string]int64 {
tokens := make(map[string]int64, len(totals))
for _, item := range totals {
tokens[item.ModelName] = item.TotalTokens
}
return tokens
}
func sumRankingTokens(totals []model.RankingQuotaTotal) int64 {
total := int64(0)
for _, item := range totals {
total += item.TotalTokens
}
return total
}
func rankingShare(value int64, total int64) float64 {
if total <= 0 || value <= 0 {
return 0
}
return roundRankingFloat(float64(value) / float64(total))
}
func rankingGrowthPct(current int64, previous int64) float64 {
if previous <= 0 {
if current > 0 {
return 100
}
return 0
}
return roundRankingFloat((float64(current-previous) / float64(previous)) * 100)
}
func roundRankingFloat(value float64) float64 {
return math.Round(value*10000) / 10000
}
func limitRankedModels(rows []RankedModel, limit int) []RankedModel {
if limit <= 0 || len(rows) <= limit {
return rows
}
return rows[:limit]
}
func limitRankingMovers(rows []RankingMover, limit int) []RankingMover {
if limit <= 0 || len(rows) <= limit {
return rows
}
return rows[:limit]
}
func minInt(a int, b int) int {
if a < b {
return a
}
return b
}