channel-billing.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. package controller
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "one-api/common"
  9. "one-api/model"
  10. "strconv"
  11. "time"
  12. "github.com/gin-gonic/gin"
  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. type OpenAISBUsageResponse struct {
  35. Msg string `json:"msg"`
  36. Data *struct {
  37. Credit string `json:"credit"`
  38. } `json:"data"`
  39. }
  40. type AIProxyUserOverviewResponse struct {
  41. Success bool `json:"success"`
  42. Message string `json:"message"`
  43. ErrorCode int `json:"error_code"`
  44. Data struct {
  45. TotalPoints float64 `json:"totalPoints"`
  46. } `json:"data"`
  47. }
  48. // GetAuthHeader get auth header
  49. func GetAuthHeader(token string) http.Header {
  50. h := http.Header{}
  51. h.Add("Authorization", fmt.Sprintf("Bearer %s", token))
  52. return h
  53. }
  54. func GetResponseBody(method, url string, channel *model.Channel, headers http.Header) ([]byte, error) {
  55. client := &http.Client{}
  56. req, err := http.NewRequest(method, url, nil)
  57. if err != nil {
  58. return nil, err
  59. }
  60. for k := range headers {
  61. req.Header.Add(k, headers.Get(k))
  62. }
  63. res, err := client.Do(req)
  64. if err != nil {
  65. return nil, err
  66. }
  67. body, err := io.ReadAll(res.Body)
  68. if err != nil {
  69. return nil, err
  70. }
  71. err = res.Body.Close()
  72. if err != nil {
  73. return nil, err
  74. }
  75. return body, nil
  76. }
  77. func updateChannelOpenAISBBalance(channel *model.Channel) (float64, error) {
  78. url := fmt.Sprintf("https://api.openai-sb.com/sb-api/user/status?api_key=%s", channel.Key)
  79. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  80. if err != nil {
  81. return 0, err
  82. }
  83. response := OpenAISBUsageResponse{}
  84. err = json.Unmarshal(body, &response)
  85. if err != nil {
  86. return 0, err
  87. }
  88. if response.Data == nil {
  89. return 0, errors.New(response.Msg)
  90. }
  91. balance, err := strconv.ParseFloat(response.Data.Credit, 64)
  92. if err != nil {
  93. return 0, err
  94. }
  95. channel.UpdateBalance(balance)
  96. return balance, nil
  97. }
  98. func updateChannelAIProxyBalance(channel *model.Channel) (float64, error) {
  99. url := "https://aiproxy.io/api/report/getUserOverview"
  100. headers := http.Header{}
  101. headers.Add("Api-Key", channel.Key)
  102. body, err := GetResponseBody("GET", url, channel, headers)
  103. if err != nil {
  104. return 0, err
  105. }
  106. response := AIProxyUserOverviewResponse{}
  107. err = json.Unmarshal(body, &response)
  108. if err != nil {
  109. return 0, err
  110. }
  111. if !response.Success {
  112. return 0, fmt.Errorf("code: %d, message: %s", response.ErrorCode, response.Message)
  113. }
  114. channel.UpdateBalance(response.Data.TotalPoints)
  115. return response.Data.TotalPoints, nil
  116. }
  117. func updateChannelBalance(channel *model.Channel) (float64, error) {
  118. baseURL := common.ChannelBaseURLs[channel.Type]
  119. switch channel.Type {
  120. case common.ChannelTypeOpenAI:
  121. if channel.BaseURL != "" {
  122. baseURL = channel.BaseURL
  123. }
  124. case common.ChannelTypeAzure:
  125. return 0, errors.New("尚未实现")
  126. case common.ChannelTypeCustom:
  127. baseURL = channel.BaseURL
  128. case common.ChannelTypeOpenAISB:
  129. return updateChannelOpenAISBBalance(channel)
  130. case common.ChannelTypeAIProxy:
  131. return updateChannelAIProxyBalance(channel)
  132. default:
  133. return 0, errors.New("尚未实现")
  134. }
  135. url := fmt.Sprintf("%s/v1/dashboard/billing/subscription", baseURL)
  136. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  137. if err != nil {
  138. return 0, err
  139. }
  140. subscription := OpenAISubscriptionResponse{}
  141. err = json.Unmarshal(body, &subscription)
  142. if err != nil {
  143. return 0, err
  144. }
  145. now := time.Now()
  146. startDate := fmt.Sprintf("%s-01", now.Format("2006-01"))
  147. endDate := now.Format("2006-01-02")
  148. if !subscription.HasPaymentMethod {
  149. startDate = now.AddDate(0, 0, -100).Format("2006-01-02")
  150. }
  151. url = fmt.Sprintf("%s/v1/dashboard/billing/usage?start_date=%s&end_date=%s", baseURL, startDate, endDate)
  152. body, err = GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  153. if err != nil {
  154. return 0, err
  155. }
  156. usage := OpenAIUsageResponse{}
  157. err = json.Unmarshal(body, &usage)
  158. if err != nil {
  159. return 0, err
  160. }
  161. balance := subscription.HardLimitUSD - usage.TotalUsage/100
  162. channel.UpdateBalance(balance)
  163. return balance, nil
  164. }
  165. func UpdateChannelBalance(c *gin.Context) {
  166. id, err := strconv.Atoi(c.Param("id"))
  167. if err != nil {
  168. c.JSON(http.StatusOK, gin.H{
  169. "success": false,
  170. "message": err.Error(),
  171. })
  172. return
  173. }
  174. channel, err := model.GetChannelById(id, true)
  175. if err != nil {
  176. c.JSON(http.StatusOK, gin.H{
  177. "success": false,
  178. "message": err.Error(),
  179. })
  180. return
  181. }
  182. balance, err := updateChannelBalance(channel)
  183. if err != nil {
  184. c.JSON(http.StatusOK, gin.H{
  185. "success": false,
  186. "message": err.Error(),
  187. })
  188. return
  189. }
  190. c.JSON(http.StatusOK, gin.H{
  191. "success": true,
  192. "message": "",
  193. "balance": balance,
  194. })
  195. return
  196. }
  197. func updateAllChannelsBalance() error {
  198. channels, err := model.GetAllChannels(0, 0, true)
  199. if err != nil {
  200. return err
  201. }
  202. for _, channel := range channels {
  203. if channel.Status != common.ChannelStatusEnabled {
  204. continue
  205. }
  206. // TODO: support Azure
  207. if channel.Type != common.ChannelTypeOpenAI && channel.Type != common.ChannelTypeCustom {
  208. continue
  209. }
  210. balance, err := updateChannelBalance(channel)
  211. if err != nil {
  212. continue
  213. } else {
  214. // err is nil & balance <= 0 means quota is used up
  215. if balance <= 0 {
  216. disableChannel(channel.Id, channel.Name, "余额不足")
  217. }
  218. }
  219. }
  220. return nil
  221. }
  222. func UpdateAllChannelsBalance(c *gin.Context) {
  223. // TODO: make it async
  224. err := updateAllChannelsBalance()
  225. if err != nil {
  226. c.JSON(http.StatusOK, gin.H{
  227. "success": false,
  228. "message": err.Error(),
  229. })
  230. return
  231. }
  232. c.JSON(http.StatusOK, gin.H{
  233. "success": true,
  234. "message": "",
  235. })
  236. return
  237. }