task_billing.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. package service
  2. import (
  3. "context"
  4. "fmt"
  5. "strings"
  6. "github.com/QuantumNous/new-api/common"
  7. "github.com/QuantumNous/new-api/constant"
  8. "github.com/QuantumNous/new-api/logger"
  9. "github.com/QuantumNous/new-api/model"
  10. relaycommon "github.com/QuantumNous/new-api/relay/common"
  11. "github.com/QuantumNous/new-api/setting/ratio_setting"
  12. "github.com/gin-gonic/gin"
  13. )
  14. // LogTaskConsumption 记录任务消费日志和统计信息(仅记录,不涉及实际扣费)。
  15. // 实际扣费已由 BillingSession(PreConsumeBilling + SettleBilling)完成。
  16. func LogTaskConsumption(c *gin.Context, info *relaycommon.RelayInfo, modelName string) {
  17. tokenName := c.GetString("token_name")
  18. logContent := fmt.Sprintf("操作 %s", info.Action)
  19. // 支持任务仅按次计费
  20. if common.StringsContains(constant.TaskPricePatches, modelName) {
  21. logContent = fmt.Sprintf("%s,按次计费", logContent)
  22. } else {
  23. if len(info.PriceData.OtherRatios) > 0 {
  24. var contents []string
  25. for key, ra := range info.PriceData.OtherRatios {
  26. if 1.0 != ra {
  27. contents = append(contents, fmt.Sprintf("%s: %.2f", key, ra))
  28. }
  29. }
  30. if len(contents) > 0 {
  31. logContent = fmt.Sprintf("%s, 计算参数:%s", logContent, strings.Join(contents, ", "))
  32. }
  33. }
  34. }
  35. other := make(map[string]interface{})
  36. other["request_path"] = c.Request.URL.Path
  37. other["model_price"] = info.PriceData.ModelPrice
  38. other["group_ratio"] = info.PriceData.GroupRatioInfo.GroupRatio
  39. if info.PriceData.GroupRatioInfo.HasSpecialRatio {
  40. other["user_group_ratio"] = info.PriceData.GroupRatioInfo.GroupSpecialRatio
  41. }
  42. model.RecordConsumeLog(c, info.UserId, model.RecordConsumeLogParams{
  43. ChannelId: info.ChannelId,
  44. ModelName: modelName,
  45. TokenName: tokenName,
  46. Quota: info.PriceData.Quota,
  47. Content: logContent,
  48. TokenId: info.TokenId,
  49. Group: info.UsingGroup,
  50. Other: other,
  51. })
  52. model.UpdateUserUsedQuotaAndRequestCount(info.UserId, info.PriceData.Quota)
  53. model.UpdateChannelUsedQuota(info.ChannelId, info.PriceData.Quota)
  54. }
  55. // ---------------------------------------------------------------------------
  56. // 异步任务计费辅助函数
  57. // ---------------------------------------------------------------------------
  58. // resolveTokenKey 通过 TokenId 运行时获取令牌 Key(用于 Redis 缓存操作)。
  59. // 如果令牌已被删除或查询失败,返回空字符串。
  60. func resolveTokenKey(ctx context.Context, tokenId int, taskID string) string {
  61. token, err := model.GetTokenById(tokenId)
  62. if err != nil {
  63. logger.LogWarn(ctx, fmt.Sprintf("获取令牌 key 失败 (tokenId=%d, task=%s): %s", tokenId, taskID, err.Error()))
  64. return ""
  65. }
  66. return token.Key
  67. }
  68. // taskIsSubscription 判断任务是否通过订阅计费。
  69. func taskIsSubscription(task *model.Task) bool {
  70. return task.PrivateData.BillingSource == BillingSourceSubscription && task.PrivateData.SubscriptionId > 0
  71. }
  72. // taskAdjustFunding 调整任务的资金来源(钱包或订阅),delta > 0 表示扣费,delta < 0 表示退还。
  73. func taskAdjustFunding(task *model.Task, delta int) error {
  74. if taskIsSubscription(task) {
  75. return model.PostConsumeUserSubscriptionDelta(task.PrivateData.SubscriptionId, int64(delta))
  76. }
  77. if delta > 0 {
  78. return model.DecreaseUserQuota(task.UserId, delta)
  79. }
  80. return model.IncreaseUserQuota(task.UserId, -delta, false)
  81. }
  82. // taskAdjustTokenQuota 调整任务的令牌额度,delta > 0 表示扣费,delta < 0 表示退还。
  83. // 需要通过 resolveTokenKey 运行时获取 key(不从 PrivateData 中读取)。
  84. func taskAdjustTokenQuota(ctx context.Context, task *model.Task, delta int) {
  85. if task.PrivateData.TokenId <= 0 || delta == 0 {
  86. return
  87. }
  88. tokenKey := resolveTokenKey(ctx, task.PrivateData.TokenId, task.TaskID)
  89. if tokenKey == "" {
  90. return
  91. }
  92. var err error
  93. if delta > 0 {
  94. err = model.DecreaseTokenQuota(task.PrivateData.TokenId, tokenKey, delta)
  95. } else {
  96. err = model.IncreaseTokenQuota(task.PrivateData.TokenId, tokenKey, -delta)
  97. }
  98. if err != nil {
  99. logger.LogWarn(ctx, fmt.Sprintf("调整令牌额度失败 (delta=%d, task=%s): %s", delta, task.TaskID, err.Error()))
  100. }
  101. }
  102. // RefundTaskQuota 统一的任务失败退款逻辑。
  103. // 当异步任务失败时,将预扣的 quota 退还给用户(支持钱包和订阅),并退还令牌额度。
  104. func RefundTaskQuota(ctx context.Context, task *model.Task, reason string) {
  105. quota := task.Quota
  106. if quota == 0 {
  107. return
  108. }
  109. // 1. 退还资金来源(钱包或订阅)
  110. if err := taskAdjustFunding(task, -quota); err != nil {
  111. logger.LogWarn(ctx, fmt.Sprintf("退还资金来源失败 task %s: %s", task.TaskID, err.Error()))
  112. return
  113. }
  114. // 2. 退还令牌额度
  115. taskAdjustTokenQuota(ctx, task, -quota)
  116. // 3. 记录日志
  117. logContent := fmt.Sprintf("异步任务执行失败 %s,补偿 %s,原因:%s", task.TaskID, logger.LogQuota(quota), reason)
  118. model.RecordLog(task.UserId, model.LogTypeSystem, logContent)
  119. }
  120. // RecalculateTaskQuota 通用的异步差额结算。
  121. // actualQuota 是任务完成后的实际应扣额度,与预扣额度 (task.Quota) 做差额结算。
  122. // reason 用于日志记录(例如 "token重算" 或 "adaptor调整")。
  123. func RecalculateTaskQuota(ctx context.Context, task *model.Task, actualQuota int, reason string) {
  124. if actualQuota <= 0 {
  125. return
  126. }
  127. preConsumedQuota := task.Quota
  128. quotaDelta := actualQuota - preConsumedQuota
  129. if quotaDelta == 0 {
  130. logger.LogInfo(ctx, fmt.Sprintf("任务 %s 预扣费准确(%s,%s)",
  131. task.TaskID, logger.LogQuota(actualQuota), reason))
  132. return
  133. }
  134. logger.LogInfo(ctx, fmt.Sprintf("任务 %s 差额结算:delta=%s(实际:%s,预扣:%s,%s)",
  135. task.TaskID,
  136. logger.LogQuota(quotaDelta),
  137. logger.LogQuota(actualQuota),
  138. logger.LogQuota(preConsumedQuota),
  139. reason,
  140. ))
  141. // 调整资金来源
  142. if err := taskAdjustFunding(task, quotaDelta); err != nil {
  143. logger.LogError(ctx, fmt.Sprintf("差额结算资金调整失败 task %s: %s", task.TaskID, err.Error()))
  144. return
  145. }
  146. // 调整令牌额度
  147. taskAdjustTokenQuota(ctx, task, quotaDelta)
  148. // 更新统计(仅补扣时更新,退还不影响已用统计)
  149. if quotaDelta > 0 {
  150. model.UpdateUserUsedQuotaAndRequestCount(task.UserId, quotaDelta)
  151. model.UpdateChannelUsedQuota(task.ChannelId, quotaDelta)
  152. }
  153. task.Quota = actualQuota
  154. var action string
  155. if quotaDelta > 0 {
  156. action = "补扣费"
  157. } else {
  158. action = "退还"
  159. }
  160. logContent := fmt.Sprintf("异步任务成功%s,预扣费 %s,实际扣费 %s,原因:%s",
  161. action,
  162. logger.LogQuota(preConsumedQuota), logger.LogQuota(actualQuota), reason)
  163. model.RecordLog(task.UserId, model.LogTypeSystem, logContent)
  164. }
  165. // RecalculateTaskQuotaByTokens 根据实际 token 消耗重新计费(异步差额结算)。
  166. // 当任务成功且返回了 totalTokens 时,根据模型倍率和分组倍率重新计算实际扣费额度,
  167. // 与预扣费的差额进行补扣或退还。支持钱包和订阅计费来源。
  168. func RecalculateTaskQuotaByTokens(ctx context.Context, task *model.Task, totalTokens int) {
  169. if totalTokens <= 0 {
  170. return
  171. }
  172. // 获取模型名称
  173. var taskData map[string]interface{}
  174. if err := common.Unmarshal(task.Data, &taskData); err != nil {
  175. return
  176. }
  177. modelName, ok := taskData["model"].(string)
  178. if !ok || modelName == "" {
  179. return
  180. }
  181. // 获取模型价格和倍率
  182. modelRatio, hasRatioSetting, _ := ratio_setting.GetModelRatio(modelName)
  183. // 只有配置了倍率(非固定价格)时才按 token 重新计费
  184. if !hasRatioSetting || modelRatio <= 0 {
  185. return
  186. }
  187. // 获取用户和组的倍率信息
  188. group := task.Group
  189. if group == "" {
  190. user, err := model.GetUserById(task.UserId, false)
  191. if err == nil {
  192. group = user.Group
  193. }
  194. }
  195. if group == "" {
  196. return
  197. }
  198. groupRatio := ratio_setting.GetGroupRatio(group)
  199. userGroupRatio, hasUserGroupRatio := ratio_setting.GetGroupGroupRatio(group, group)
  200. var finalGroupRatio float64
  201. if hasUserGroupRatio {
  202. finalGroupRatio = userGroupRatio
  203. } else {
  204. finalGroupRatio = groupRatio
  205. }
  206. // 计算实际应扣费额度: totalTokens * modelRatio * groupRatio
  207. actualQuota := int(float64(totalTokens) * modelRatio * finalGroupRatio)
  208. reason := fmt.Sprintf("token重算:tokens=%d, modelRatio=%.2f, groupRatio=%.2f", totalTokens, modelRatio, finalGroupRatio)
  209. RecalculateTaskQuota(ctx, task, actualQuota, reason)
  210. }