channel-billing.go 8.8 KB

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