quota.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. package service
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/gin-gonic/gin"
  6. "math"
  7. "one-api/common"
  8. "one-api/dto"
  9. "one-api/model"
  10. relaycommon "one-api/relay/common"
  11. "strings"
  12. "time"
  13. )
  14. func PreWssConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usage *dto.RealtimeUsage) error {
  15. if relayInfo.UsePrice {
  16. return nil
  17. }
  18. userQuota, err := model.GetUserQuota(relayInfo.UserId)
  19. if err != nil {
  20. return err
  21. }
  22. modelName := relayInfo.UpstreamModelName
  23. textInputTokens := usage.InputTokenDetails.TextTokens
  24. textOutTokens := usage.OutputTokenDetails.TextTokens
  25. audioInputTokens := usage.InputTokenDetails.AudioTokens
  26. audioOutTokens := usage.OutputTokenDetails.AudioTokens
  27. completionRatio := common.GetCompletionRatio(modelName)
  28. audioRatio := common.GetAudioRatio(relayInfo.UpstreamModelName)
  29. audioCompletionRatio := common.GetAudioCompletionRatio(modelName)
  30. groupRatio := common.GetGroupRatio(relayInfo.Group)
  31. modelRatio := common.GetModelRatio(modelName)
  32. ratio := groupRatio * modelRatio
  33. quota := textInputTokens + int(math.Round(float64(textOutTokens)*completionRatio))
  34. quota += int(math.Round(float64(audioInputTokens)*audioRatio)) + int(math.Round(float64(audioOutTokens)*audioRatio*audioCompletionRatio))
  35. quota = int(math.Round(float64(quota) * ratio))
  36. if ratio != 0 && quota <= 0 {
  37. quota = 1
  38. }
  39. if userQuota < quota {
  40. return errors.New(fmt.Sprintf("用户额度不足,剩余额度为 %d", userQuota))
  41. }
  42. err = model.PostConsumeTokenQuota(relayInfo, 0, quota, 0, false)
  43. if err != nil {
  44. return err
  45. }
  46. common.LogInfo(ctx, "realtime streaming consume quota success, quota: "+fmt.Sprintf("%d", quota))
  47. err = model.CacheUpdateUserQuota(relayInfo.UserId)
  48. if err != nil {
  49. return err
  50. }
  51. return nil
  52. }
  53. func PostWssConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, modelName string,
  54. usage *dto.RealtimeUsage, ratio float64, preConsumedQuota int, userQuota int, modelRatio float64,
  55. groupRatio float64,
  56. modelPrice float64, usePrice bool, extraContent string) {
  57. useTimeSeconds := time.Now().Unix() - relayInfo.StartTime.Unix()
  58. textInputTokens := usage.InputTokenDetails.TextTokens
  59. textOutTokens := usage.OutputTokenDetails.TextTokens
  60. audioInputTokens := usage.InputTokenDetails.AudioTokens
  61. audioOutTokens := usage.OutputTokenDetails.AudioTokens
  62. tokenName := ctx.GetString("token_name")
  63. completionRatio := common.GetCompletionRatio(modelName)
  64. audioRatio := common.GetAudioRatio(relayInfo.UpstreamModelName)
  65. audioCompletionRatio := common.GetAudioCompletionRatio(modelName)
  66. quota := 0
  67. if !usePrice {
  68. quota = int(math.Round(float64(textInputTokens)*ratio + float64(textOutTokens)*ratio*completionRatio))
  69. quota += int(math.Round(float64(audioInputTokens)*ratio*audioRatio + float64(audioOutTokens)*ratio*audioRatio*audioCompletionRatio))
  70. if ratio != 0 && quota <= 0 {
  71. quota = 1
  72. }
  73. } else {
  74. quota = int(modelPrice * common.QuotaPerUnit * groupRatio)
  75. }
  76. totalTokens := usage.TotalTokens
  77. var logContent string
  78. if !usePrice {
  79. logContent = fmt.Sprintf("模型倍率 %.2f,补全倍率 %.2f,音频倍率 %.2f,音频补全倍率 %.2f,分组倍率 %.2f", modelRatio, completionRatio, audioRatio, audioCompletionRatio, groupRatio)
  80. } else {
  81. logContent = fmt.Sprintf("模型价格 %.2f,分组倍率 %.2f", modelPrice, groupRatio)
  82. }
  83. // record all the consume log even if quota is 0
  84. if totalTokens == 0 {
  85. // in this case, must be some error happened
  86. // we cannot just return, because we may have to return the pre-consumed quota
  87. quota = 0
  88. logContent += fmt.Sprintf("(可能是上游超时)")
  89. common.LogError(ctx, fmt.Sprintf("total tokens is 0, cannot consume quota, userId %d, channelId %d, "+
  90. "tokenId %d, model %s, pre-consumed quota %d", relayInfo.UserId, relayInfo.ChannelId, relayInfo.TokenId, modelName, preConsumedQuota))
  91. } else {
  92. //if sensitiveResp != nil {
  93. // logContent += fmt.Sprintf(",敏感词:%s", strings.Join(sensitiveResp.SensitiveWords, ", "))
  94. //}
  95. //quotaDelta := quota - preConsumedQuota
  96. //if quotaDelta != 0 {
  97. // err := model.PostConsumeTokenQuota(relayInfo, userQuota, quotaDelta, preConsumedQuota, true)
  98. // if err != nil {
  99. // common.LogError(ctx, "error consuming token remain quota: "+err.Error())
  100. // }
  101. //}
  102. //err := model.CacheUpdateUserQuota(relayInfo.UserId)
  103. //if err != nil {
  104. // common.LogError(ctx, "error update user quota cache: "+err.Error())
  105. //}
  106. model.UpdateUserUsedQuotaAndRequestCount(relayInfo.UserId, quota)
  107. model.UpdateChannelUsedQuota(relayInfo.ChannelId, quota)
  108. }
  109. logModel := modelName
  110. if strings.HasPrefix(logModel, "gpt-4-gizmo") {
  111. logModel = "gpt-4-gizmo-*"
  112. logContent += fmt.Sprintf(",模型 %s", modelName)
  113. }
  114. if strings.HasPrefix(logModel, "gpt-4o-gizmo") {
  115. logModel = "gpt-4o-gizmo-*"
  116. logContent += fmt.Sprintf(",模型 %s", modelName)
  117. }
  118. if extraContent != "" {
  119. logContent += ", " + extraContent
  120. }
  121. other := GenerateWssOtherInfo(ctx, relayInfo, usage, modelRatio, groupRatio, completionRatio, modelPrice)
  122. model.RecordConsumeLog(ctx, relayInfo.UserId, relayInfo.ChannelId, usage.InputTokens, usage.OutputTokens, logModel,
  123. tokenName, quota, logContent, relayInfo.TokenId, userQuota, int(useTimeSeconds), relayInfo.IsStream, other)
  124. }