violation_fee.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. package service
  2. import (
  3. "fmt"
  4. "strings"
  5. "time"
  6. "github.com/QuantumNous/new-api/common"
  7. "github.com/QuantumNous/new-api/logger"
  8. "github.com/QuantumNous/new-api/model"
  9. relaycommon "github.com/QuantumNous/new-api/relay/common"
  10. "github.com/QuantumNous/new-api/setting/model_setting"
  11. "github.com/QuantumNous/new-api/types"
  12. "github.com/shopspring/decimal"
  13. "github.com/gin-gonic/gin"
  14. )
  15. const (
  16. ViolationFeeCodePrefix = "violation_fee."
  17. CSAMViolationMarker = "Failed check: SAFETY_CHECK_TYPE_CSAM"
  18. )
  19. func IsViolationFeeCode(code types.ErrorCode) bool {
  20. return strings.HasPrefix(string(code), ViolationFeeCodePrefix)
  21. }
  22. func HasCSAMViolationMarker(err *types.NewAPIError) bool {
  23. if err == nil {
  24. return false
  25. }
  26. if strings.Contains(err.Error(), CSAMViolationMarker) {
  27. return true
  28. }
  29. msg := err.ToOpenAIError().Message
  30. return strings.Contains(msg, CSAMViolationMarker)
  31. }
  32. func WrapAsViolationFeeGrokCSAM(err *types.NewAPIError) *types.NewAPIError {
  33. if err == nil {
  34. return nil
  35. }
  36. oai := err.ToOpenAIError()
  37. oai.Type = string(types.ErrorCodeViolationFeeGrokCSAM)
  38. oai.Code = string(types.ErrorCodeViolationFeeGrokCSAM)
  39. return types.WithOpenAIError(oai, err.StatusCode, types.ErrOptionWithSkipRetry())
  40. }
  41. // NormalizeViolationFeeError ensures:
  42. // - if the CSAM marker is present, error.code is set to a stable violation-fee code and skip-retry is enabled.
  43. // - if error.code already has the violation-fee prefix, skip-retry is enabled.
  44. //
  45. // It must be called before retry decision logic.
  46. func NormalizeViolationFeeError(err *types.NewAPIError) *types.NewAPIError {
  47. if err == nil {
  48. return nil
  49. }
  50. if HasCSAMViolationMarker(err) {
  51. return WrapAsViolationFeeGrokCSAM(err)
  52. }
  53. if IsViolationFeeCode(err.GetErrorCode()) {
  54. oai := err.ToOpenAIError()
  55. return types.WithOpenAIError(oai, err.StatusCode, types.ErrOptionWithSkipRetry())
  56. }
  57. return err
  58. }
  59. func shouldChargeViolationFee(err *types.NewAPIError) bool {
  60. if err == nil {
  61. return false
  62. }
  63. if err.GetErrorCode() == types.ErrorCodeViolationFeeGrokCSAM {
  64. return true
  65. }
  66. // In case some callers didn't normalize, keep a safety net.
  67. return HasCSAMViolationMarker(err)
  68. }
  69. func calcViolationFeeQuota(amount, groupRatio float64) int {
  70. if amount <= 0 {
  71. return 0
  72. }
  73. if groupRatio <= 0 {
  74. return 0
  75. }
  76. quota := decimal.NewFromFloat(amount).
  77. Mul(decimal.NewFromFloat(common.QuotaPerUnit)).
  78. Mul(decimal.NewFromFloat(groupRatio)).
  79. Round(0).
  80. IntPart()
  81. if quota <= 0 {
  82. return 0
  83. }
  84. return int(quota)
  85. }
  86. // ChargeViolationFeeIfNeeded charges an additional fee after the normal flow finishes (including refund).
  87. // It uses Grok fee settings as the fee policy.
  88. func ChargeViolationFeeIfNeeded(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, apiErr *types.NewAPIError) bool {
  89. if ctx == nil || relayInfo == nil || apiErr == nil {
  90. return false
  91. }
  92. //if relayInfo.IsPlayground {
  93. // return false
  94. //}
  95. if !shouldChargeViolationFee(apiErr) {
  96. return false
  97. }
  98. settings := model_setting.GetGrokSettings()
  99. if settings == nil || !settings.ViolationDeductionEnabled {
  100. return false
  101. }
  102. groupRatio := relayInfo.PriceData.GroupRatioInfo.GroupRatio
  103. feeQuota := calcViolationFeeQuota(settings.ViolationDeductionAmount, groupRatio)
  104. if feeQuota <= 0 {
  105. return false
  106. }
  107. if err := PostConsumeQuota(relayInfo, feeQuota, 0, true); err != nil {
  108. logger.LogError(ctx, fmt.Sprintf("failed to charge violation fee: %s", err.Error()))
  109. return false
  110. }
  111. model.UpdateUserUsedQuotaAndRequestCount(relayInfo.UserId, feeQuota)
  112. model.UpdateChannelUsedQuota(relayInfo.ChannelId, feeQuota)
  113. useTimeSeconds := time.Now().Unix() - relayInfo.StartTime.Unix()
  114. tokenName := ctx.GetString("token_name")
  115. oai := apiErr.ToOpenAIError()
  116. other := map[string]any{
  117. "violation_fee": true,
  118. "violation_fee_code": string(types.ErrorCodeViolationFeeGrokCSAM),
  119. "fee_quota": feeQuota,
  120. "base_amount": settings.ViolationDeductionAmount,
  121. "group_ratio": groupRatio,
  122. "status_code": apiErr.StatusCode,
  123. "upstream_error_type": oai.Type,
  124. "upstream_error_code": fmt.Sprintf("%v", oai.Code),
  125. "violation_fee_marker": CSAMViolationMarker,
  126. }
  127. model.RecordConsumeLog(ctx, relayInfo.UserId, model.RecordConsumeLogParams{
  128. ChannelId: relayInfo.ChannelId,
  129. ModelName: relayInfo.OriginModelName,
  130. TokenName: tokenName,
  131. Quota: feeQuota,
  132. Content: "Violation fee charged",
  133. TokenId: relayInfo.TokenId,
  134. UseTimeSeconds: int(useTimeSeconds),
  135. IsStream: relayInfo.IsStream,
  136. Group: relayInfo.UsingGroup,
  137. Other: other,
  138. })
  139. return true
  140. }