channel-billing.go 8.8 KB

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