channel-billing.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. package controller
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/gin-gonic/gin"
  7. "io"
  8. "net/http"
  9. "one-api/common"
  10. "one-api/model"
  11. "strconv"
  12. "time"
  13. )
  14. // https://github.com/songquanpeng/one-api/issues/79
  15. type OpenAISubscriptionResponse struct {
  16. Object string `json:"object"`
  17. HasPaymentMethod bool `json:"has_payment_method"`
  18. SoftLimitUSD float64 `json:"soft_limit_usd"`
  19. HardLimitUSD float64 `json:"hard_limit_usd"`
  20. SystemHardLimitUSD float64 `json:"system_hard_limit_usd"`
  21. }
  22. type OpenAIUsageDailyCost struct {
  23. Timestamp float64 `json:"timestamp"`
  24. LineItems []struct {
  25. Name string `json:"name"`
  26. Cost float64 `json:"cost"`
  27. }
  28. }
  29. type OpenAIUsageResponse struct {
  30. Object string `json:"object"`
  31. //DailyCosts []OpenAIUsageDailyCost `json:"daily_costs"`
  32. TotalUsage float64 `json:"total_usage"` // unit: 0.01 dollar
  33. }
  34. func updateChannelBalance(channel *model.Channel) (float64, error) {
  35. baseURL := common.ChannelBaseURLs[channel.Type]
  36. switch channel.Type {
  37. case common.ChannelTypeAzure:
  38. return 0, errors.New("尚未实现")
  39. case common.ChannelTypeCustom:
  40. baseURL = channel.BaseURL
  41. }
  42. url := fmt.Sprintf("%s/v1/dashboard/billing/subscription", baseURL)
  43. client := &http.Client{}
  44. req, err := http.NewRequest("GET", url, nil)
  45. if err != nil {
  46. return 0, err
  47. }
  48. auth := fmt.Sprintf("Bearer %s", channel.Key)
  49. req.Header.Add("Authorization", auth)
  50. res, err := client.Do(req)
  51. if err != nil {
  52. return 0, err
  53. }
  54. body, err := io.ReadAll(res.Body)
  55. if err != nil {
  56. return 0, err
  57. }
  58. err = res.Body.Close()
  59. if err != nil {
  60. return 0, err
  61. }
  62. subscription := OpenAISubscriptionResponse{}
  63. err = json.Unmarshal(body, &subscription)
  64. if err != nil {
  65. return 0, err
  66. }
  67. now := time.Now()
  68. startDate := fmt.Sprintf("%s-01", now.Format("2006-01"))
  69. //endDate := now.Format("2006-01-02")
  70. url = fmt.Sprintf("%s/v1/dashboard/billing/usage?start_date=%s&end_date=%s", baseURL, startDate, "2023-06-01")
  71. req, err = http.NewRequest("GET", url, nil)
  72. if err != nil {
  73. return 0, err
  74. }
  75. req.Header.Add("Authorization", auth)
  76. res, err = client.Do(req)
  77. if err != nil {
  78. return 0, err
  79. }
  80. body, err = io.ReadAll(res.Body)
  81. if err != nil {
  82. return 0, err
  83. }
  84. err = res.Body.Close()
  85. if err != nil {
  86. return 0, err
  87. }
  88. usage := OpenAIUsageResponse{}
  89. err = json.Unmarshal(body, &usage)
  90. if err != nil {
  91. return 0, err
  92. }
  93. balance := subscription.HardLimitUSD - usage.TotalUsage/100
  94. channel.UpdateBalance(balance)
  95. return balance, nil
  96. }
  97. func UpdateChannelBalance(c *gin.Context) {
  98. id, err := strconv.Atoi(c.Param("id"))
  99. if err != nil {
  100. c.JSON(http.StatusOK, gin.H{
  101. "success": false,
  102. "message": err.Error(),
  103. })
  104. return
  105. }
  106. channel, err := model.GetChannelById(id, true)
  107. if err != nil {
  108. c.JSON(http.StatusOK, gin.H{
  109. "success": false,
  110. "message": err.Error(),
  111. })
  112. return
  113. }
  114. balance, err := updateChannelBalance(channel)
  115. if err != nil {
  116. c.JSON(http.StatusOK, gin.H{
  117. "success": false,
  118. "message": err.Error(),
  119. })
  120. return
  121. }
  122. c.JSON(http.StatusOK, gin.H{
  123. "success": true,
  124. "message": "",
  125. "balance": balance,
  126. })
  127. return
  128. }
  129. func updateAllChannelsBalance() error {
  130. channels, err := model.GetAllChannels(0, 0, true)
  131. if err != nil {
  132. return err
  133. }
  134. for _, channel := range channels {
  135. if channel.Status != common.ChannelStatusEnabled {
  136. continue
  137. }
  138. // TODO: support Azure
  139. if channel.Type != common.ChannelTypeOpenAI && channel.Type != common.ChannelTypeCustom {
  140. continue
  141. }
  142. balance, err := updateChannelBalance(channel)
  143. if err != nil {
  144. continue
  145. } else {
  146. // err is nil & balance <= 0 means quota is used up
  147. if balance <= 0 {
  148. disableChannel(channel.Id, channel.Name, "余额不足")
  149. }
  150. }
  151. }
  152. return nil
  153. }
  154. func UpdateAllChannelsBalance(c *gin.Context) {
  155. // TODO: make it async
  156. err := updateAllChannelsBalance()
  157. if err != nil {
  158. c.JSON(http.StatusOK, gin.H{
  159. "success": false,
  160. "message": err.Error(),
  161. })
  162. return
  163. }
  164. c.JSON(http.StatusOK, gin.H{
  165. "success": true,
  166. "message": "",
  167. })
  168. return
  169. }