channel-billing.go 6.8 KB

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