channel-billing.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. "one-api/service"
  11. "strconv"
  12. "time"
  13. "github.com/gin-gonic/gin"
  14. )
  15. // https://github.com/songquanpeng/one-api/issues/79
  16. type OpenAISubscriptionResponse struct {
  17. Object string `json:"object"`
  18. HasPaymentMethod bool `json:"has_payment_method"`
  19. SoftLimitUSD float64 `json:"soft_limit_usd"`
  20. HardLimitUSD float64 `json:"hard_limit_usd"`
  21. SystemHardLimitUSD float64 `json:"system_hard_limit_usd"`
  22. AccessUntil int64 `json:"access_until"`
  23. }
  24. type OpenAIUsageDailyCost struct {
  25. Timestamp float64 `json:"timestamp"`
  26. LineItems []struct {
  27. Name string `json:"name"`
  28. Cost float64 `json:"cost"`
  29. }
  30. }
  31. type OpenAICreditGrants struct {
  32. Object string `json:"object"`
  33. TotalGranted float64 `json:"total_granted"`
  34. TotalUsed float64 `json:"total_used"`
  35. TotalAvailable float64 `json:"total_available"`
  36. }
  37. type OpenAIUsageResponse struct {
  38. Object string `json:"object"`
  39. //DailyCosts []OpenAIUsageDailyCost `json:"daily_costs"`
  40. TotalUsage float64 `json:"total_usage"` // unit: 0.01 dollar
  41. }
  42. type OpenAISBUsageResponse struct {
  43. Msg string `json:"msg"`
  44. Data *struct {
  45. Credit string `json:"credit"`
  46. } `json:"data"`
  47. }
  48. type AIProxyUserOverviewResponse struct {
  49. Success bool `json:"success"`
  50. Message string `json:"message"`
  51. ErrorCode int `json:"error_code"`
  52. Data struct {
  53. TotalPoints float64 `json:"totalPoints"`
  54. } `json:"data"`
  55. }
  56. type API2GPTUsageResponse struct {
  57. Object string `json:"object"`
  58. TotalGranted float64 `json:"total_granted"`
  59. TotalUsed float64 `json:"total_used"`
  60. TotalRemaining float64 `json:"total_remaining"`
  61. }
  62. type APGC2DGPTUsageResponse struct {
  63. //Grants interface{} `json:"grants"`
  64. Object string `json:"object"`
  65. TotalAvailable float64 `json:"total_available"`
  66. TotalGranted float64 `json:"total_granted"`
  67. TotalUsed float64 `json:"total_used"`
  68. }
  69. // GetAuthHeader get auth header
  70. func GetAuthHeader(token string) http.Header {
  71. h := http.Header{}
  72. h.Add("Authorization", fmt.Sprintf("Bearer %s", token))
  73. return h
  74. }
  75. func GetResponseBody(method, url string, channel *model.Channel, headers http.Header) ([]byte, error) {
  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 := service.GetHttpClient().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.GetBaseURL())
  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.GetBaseURL() == "" {
  185. channel.BaseURL = &baseURL
  186. }
  187. switch channel.Type {
  188. case common.ChannelTypeOpenAI:
  189. if channel.GetBaseURL() != "" {
  190. baseURL = channel.GetBaseURL()
  191. }
  192. case common.ChannelTypeAzure:
  193. return 0, errors.New("尚未实现")
  194. case common.ChannelTypeCustom:
  195. baseURL = channel.GetBaseURL()
  196. //case common.ChannelTypeOpenAISB:
  197. // return updateChannelOpenAISBBalance(channel)
  198. case common.ChannelTypeAIProxy:
  199. return updateChannelAIProxyBalance(channel)
  200. case common.ChannelTypeAPI2GPT:
  201. return updateChannelAPI2GPTBalance(channel)
  202. case common.ChannelTypeAIGC2D:
  203. return updateChannelAIGC2DBalance(channel)
  204. default:
  205. return 0, errors.New("尚未实现")
  206. }
  207. url := fmt.Sprintf("%s/v1/dashboard/billing/subscription", baseURL)
  208. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  209. if err != nil {
  210. return 0, err
  211. }
  212. subscription := OpenAISubscriptionResponse{}
  213. err = json.Unmarshal(body, &subscription)
  214. if err != nil {
  215. return 0, err
  216. }
  217. now := time.Now()
  218. startDate := fmt.Sprintf("%s-01", now.Format("2006-01"))
  219. endDate := now.Format("2006-01-02")
  220. if !subscription.HasPaymentMethod {
  221. startDate = now.AddDate(0, 0, -100).Format("2006-01-02")
  222. }
  223. url = fmt.Sprintf("%s/v1/dashboard/billing/usage?start_date=%s&end_date=%s", baseURL, startDate, endDate)
  224. body, err = GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  225. if err != nil {
  226. return 0, err
  227. }
  228. usage := OpenAIUsageResponse{}
  229. err = json.Unmarshal(body, &usage)
  230. if err != nil {
  231. return 0, err
  232. }
  233. balance := subscription.HardLimitUSD - usage.TotalUsage/100
  234. channel.UpdateBalance(balance)
  235. return balance, nil
  236. }
  237. func UpdateChannelBalance(c *gin.Context) {
  238. id, err := strconv.Atoi(c.Param("id"))
  239. if err != nil {
  240. c.JSON(http.StatusOK, gin.H{
  241. "success": false,
  242. "message": err.Error(),
  243. })
  244. return
  245. }
  246. channel, err := model.GetChannelById(id, true)
  247. if err != nil {
  248. c.JSON(http.StatusOK, gin.H{
  249. "success": false,
  250. "message": err.Error(),
  251. })
  252. return
  253. }
  254. balance, err := updateChannelBalance(channel)
  255. if err != nil {
  256. c.JSON(http.StatusOK, gin.H{
  257. "success": false,
  258. "message": err.Error(),
  259. })
  260. return
  261. }
  262. c.JSON(http.StatusOK, gin.H{
  263. "success": true,
  264. "message": "",
  265. "balance": balance,
  266. })
  267. return
  268. }
  269. func updateAllChannelsBalance() error {
  270. channels, err := model.GetAllChannels(0, 0, true, false)
  271. if err != nil {
  272. return err
  273. }
  274. for _, channel := range channels {
  275. if channel.Status != common.ChannelStatusEnabled {
  276. continue
  277. }
  278. // TODO: support Azure
  279. if channel.Type != common.ChannelTypeOpenAI && channel.Type != common.ChannelTypeCustom {
  280. continue
  281. }
  282. balance, err := updateChannelBalance(channel)
  283. if err != nil {
  284. continue
  285. } else {
  286. // err is nil & balance <= 0 means quota is used up
  287. if balance <= 0 {
  288. service.DisableChannel(channel.Id, channel.Name, "余额不足")
  289. }
  290. }
  291. time.Sleep(common.RequestInterval)
  292. }
  293. return nil
  294. }
  295. func UpdateAllChannelsBalance(c *gin.Context) {
  296. // TODO: make it async
  297. err := updateAllChannelsBalance()
  298. if err != nil {
  299. c.JSON(http.StatusOK, gin.H{
  300. "success": false,
  301. "message": err.Error(),
  302. })
  303. return
  304. }
  305. c.JSON(http.StatusOK, gin.H{
  306. "success": true,
  307. "message": "",
  308. })
  309. return
  310. }
  311. func AutomaticallyUpdateChannels(frequency int) {
  312. for {
  313. time.Sleep(time.Duration(frequency) * time.Minute)
  314. common.SysLog("updating all channels")
  315. _ = updateAllChannelsBalance()
  316. common.SysLog("channels update done")
  317. }
  318. }