forked from QuantumNous/new-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusedata_rankings.go
More file actions
66 lines (58 loc) 路 1.87 KB
/
Copy pathusedata_rankings.go
File metadata and controls
66 lines (58 loc) 路 1.87 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
package model
import (
"fmt"
"github.com/QuantumNous/new-api/common"
"gorm.io/gorm"
)
type RankingQuotaTotal struct {
ModelName string `json:"model_name"`
TotalTokens int64 `json:"total_tokens"`
}
type RankingQuotaBucket struct {
ModelName string `json:"model_name"`
Bucket int64 `json:"bucket"`
Tokens int64 `json:"tokens"`
}
func GetRankingQuotaTotals(startTime int64, endTime int64) ([]RankingQuotaTotal, error) {
var rows []RankingQuotaTotal
query := DB.Table("quota_data").
Select("model_name, sum(token_used) as total_tokens").
Where("model_name <> ''").
Group("model_name").
Having("sum(token_used) > 0").
Order("total_tokens DESC")
query = applyRankingQuotaTimeRange(query, startTime, endTime)
err := query.Find(&rows).Error
return rows, err
}
func GetRankingQuotaBuckets(startTime int64, endTime int64, bucketSize int64) ([]RankingQuotaBucket, error) {
if bucketSize <= 0 {
bucketSize = 3600
}
bucketExpr := rankingBucketExpr(bucketSize)
var rows []RankingQuotaBucket
query := DB.Table("quota_data").
Select(fmt.Sprintf("model_name, %s as bucket, sum(token_used) as tokens", bucketExpr)).
Where("model_name <> ''").
Group(fmt.Sprintf("model_name, %s", bucketExpr)).
Having("sum(token_used) > 0").
Order("bucket ASC")
query = applyRankingQuotaTimeRange(query, startTime, endTime)
err := query.Find(&rows).Error
return rows, err
}
func rankingBucketExpr(bucketSize int64) string {
if common.UsingMainDatabase(common.DatabaseTypeMySQL) {
return fmt.Sprintf("FLOOR(created_at / %d) * %d", bucketSize, bucketSize)
}
return fmt.Sprintf("(created_at / %d) * %d", bucketSize, bucketSize)
}
func applyRankingQuotaTimeRange(query *gorm.DB, startTime int64, endTime int64) *gorm.DB {
if startTime > 0 {
query = query.Where("created_at >= ?", startTime)
}
if endTime > 0 {
query = query.Where("created_at <= ?", endTime)
}
return query
}