pricing.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package model
  2. import (
  3. "one-api/common"
  4. "one-api/dto"
  5. "sync"
  6. "time"
  7. )
  8. var (
  9. pricingMap []dto.ModelPricing
  10. lastGetPricingTime time.Time
  11. updatePricingLock sync.Mutex
  12. )
  13. func GetPricing(user *User, openAIModels []dto.OpenAIModels) []dto.ModelPricing {
  14. updatePricingLock.Lock()
  15. defer updatePricingLock.Unlock()
  16. if time.Since(lastGetPricingTime) > time.Minute*1 || len(pricingMap) == 0 {
  17. updatePricing(openAIModels)
  18. }
  19. if user != nil {
  20. userPricingMap := make([]dto.ModelPricing, 0)
  21. models := GetGroupModels(user.Group)
  22. for _, pricing := range pricingMap {
  23. if !common.StringsContains(models, pricing.ModelName) {
  24. pricing.Available = false
  25. }
  26. userPricingMap = append(userPricingMap, pricing)
  27. }
  28. return userPricingMap
  29. }
  30. return pricingMap
  31. }
  32. func updatePricing(openAIModels []dto.OpenAIModels) {
  33. modelRatios := common.GetModelRatios()
  34. enabledModels := GetEnabledModels()
  35. allModels := make(map[string]string)
  36. for _, openAIModel := range openAIModels {
  37. if common.StringsContains(enabledModels, openAIModel.Id) {
  38. allModels[openAIModel.Id] = openAIModel.OwnedBy
  39. }
  40. }
  41. for model, _ := range modelRatios {
  42. if common.StringsContains(enabledModels, model) {
  43. if _, ok := allModels[model]; !ok {
  44. allModels[model] = "custom"
  45. }
  46. }
  47. }
  48. pricingMap = make([]dto.ModelPricing, 0)
  49. for model, ownerBy := range allModels {
  50. pricing := dto.ModelPricing{
  51. Available: true,
  52. ModelName: model,
  53. OwnerBy: ownerBy,
  54. }
  55. modelPrice, findPrice := common.GetModelPrice(model, false)
  56. if findPrice {
  57. pricing.ModelPrice = modelPrice
  58. pricing.QuotaType = 1
  59. } else {
  60. pricing.ModelRatio = common.GetModelRatio(model)
  61. pricing.CompletionRatio = common.GetCompletionRatio(model)
  62. pricing.QuotaType = 0
  63. }
  64. pricingMap = append(pricingMap, pricing)
  65. }
  66. lastGetPricingTime = time.Now()
  67. }