channel-billing.go 7.9 KB

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