pricing.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package model
  2. import (
  3. "one-api/common"
  4. "sync"
  5. "time"
  6. )
  7. type Pricing struct {
  8. Available bool `json:"available"`
  9. ModelName string `json:"model_name"`
  10. QuotaType int `json:"quota_type"`
  11. ModelRatio float64 `json:"model_ratio"`
  12. ModelPrice float64 `json:"model_price"`
  13. OwnerBy string `json:"owner_by"`
  14. CompletionRatio float64 `json:"completion_ratio"`
  15. EnableGroup []string `json:"enable_group,omitempty"`
  16. }
  17. var (
  18. pricingMap []Pricing
  19. lastGetPricingTime time.Time
  20. updatePricingLock sync.Mutex
  21. )
  22. func GetPricing(group string) []Pricing {
  23. updatePricingLock.Lock()
  24. defer updatePricingLock.Unlock()
  25. if time.Since(lastGetPricingTime) > time.Minute*1 || len(pricingMap) == 0 {
  26. updatePricing()
  27. }
  28. if group != "" {
  29. userPricingMap := make([]Pricing, 0)
  30. models := GetGroupModels(group)
  31. for _, pricing := range pricingMap {
  32. if !common.StringsContains(models, pricing.ModelName) {
  33. pricing.Available = false
  34. }
  35. userPricingMap = append(userPricingMap, pricing)
  36. }
  37. return userPricingMap
  38. }
  39. return pricingMap
  40. }
  41. func updatePricing() {
  42. //modelRatios := common.GetModelRatios()
  43. enabledModels := GetEnabledModels()
  44. allModels := make(map[string]int)
  45. for i, model := range enabledModels {
  46. allModels[model] = i
  47. }
  48. pricingMap = make([]Pricing, 0)
  49. for model, _ := range allModels {
  50. pricing := Pricing{
  51. Available: true,
  52. ModelName: model,
  53. }
  54. modelPrice, findPrice := common.GetModelPrice(model, false)
  55. if findPrice {
  56. pricing.ModelPrice = modelPrice
  57. pricing.QuotaType = 1
  58. } else {
  59. pricing.ModelRatio = common.GetModelRatio(model)
  60. pricing.CompletionRatio = common.GetCompletionRatio(model)
  61. pricing.QuotaType = 0
  62. }
  63. pricingMap = append(pricingMap, pricing)
  64. }
  65. lastGetPricingTime = time.Now()
  66. }