channel-billing.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. package controller
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "one-api/common"
  9. "one-api/constant"
  10. "one-api/model"
  11. "one-api/service"
  12. "one-api/setting"
  13. "one-api/types"
  14. "strconv"
  15. "time"
  16. "github.com/shopspring/decimal"
  17. "github.com/gin-gonic/gin"
  18. )
  19. // https://github.com/songquanpeng/one-api/issues/79
  20. type OpenAISubscriptionResponse struct {
  21. Object string `json:"object"`
  22. HasPaymentMethod bool `json:"has_payment_method"`
  23. SoftLimitUSD float64 `json:"soft_limit_usd"`
  24. HardLimitUSD float64 `json:"hard_limit_usd"`
  25. SystemHardLimitUSD float64 `json:"system_hard_limit_usd"`
  26. AccessUntil int64 `json:"access_until"`
  27. }
  28. type OpenAIUsageDailyCost struct {
  29. Timestamp float64 `json:"timestamp"`
  30. LineItems []struct {
  31. Name string `json:"name"`
  32. Cost float64 `json:"cost"`
  33. }
  34. }
  35. type OpenAICreditGrants struct {
  36. Object string `json:"object"`
  37. TotalGranted float64 `json:"total_granted"`
  38. TotalUsed float64 `json:"total_used"`
  39. TotalAvailable float64 `json:"total_available"`
  40. }
  41. type OpenAIUsageResponse struct {
  42. Object string `json:"object"`
  43. //DailyCosts []OpenAIUsageDailyCost `json:"daily_costs"`
  44. TotalUsage float64 `json:"total_usage"` // unit: 0.01 dollar
  45. }
  46. type OpenAISBUsageResponse struct {
  47. Msg string `json:"msg"`
  48. Data *struct {
  49. Credit string `json:"credit"`
  50. } `json:"data"`
  51. }
  52. type AIProxyUserOverviewResponse struct {
  53. Success bool `json:"success"`
  54. Message string `json:"message"`
  55. ErrorCode int `json:"error_code"`
  56. Data struct {
  57. TotalPoints float64 `json:"totalPoints"`
  58. } `json:"data"`
  59. }
  60. type API2GPTUsageResponse struct {
  61. Object string `json:"object"`
  62. TotalGranted float64 `json:"total_granted"`
  63. TotalUsed float64 `json:"total_used"`
  64. TotalRemaining float64 `json:"total_remaining"`
  65. }
  66. type APGC2DGPTUsageResponse struct {
  67. //Grants interface{} `json:"grants"`
  68. Object string `json:"object"`
  69. TotalAvailable float64 `json:"total_available"`
  70. TotalGranted float64 `json:"total_granted"`
  71. TotalUsed float64 `json:"total_used"`
  72. }
  73. type SiliconFlowUsageResponse struct {
  74. Code int `json:"code"`
  75. Message string `json:"message"`
  76. Status bool `json:"status"`
  77. Data struct {
  78. ID string `json:"id"`
  79. Name string `json:"name"`
  80. Image string `json:"image"`
  81. Email string `json:"email"`
  82. IsAdmin bool `json:"isAdmin"`
  83. Balance string `json:"balance"`
  84. Status string `json:"status"`
  85. Introduction string `json:"introduction"`
  86. Role string `json:"role"`
  87. ChargeBalance string `json:"chargeBalance"`
  88. TotalBalance string `json:"totalBalance"`
  89. Category string `json:"category"`
  90. } `json:"data"`
  91. }
  92. type DeepSeekUsageResponse struct {
  93. IsAvailable bool `json:"is_available"`
  94. BalanceInfos []struct {
  95. Currency string `json:"currency"`
  96. TotalBalance string `json:"total_balance"`
  97. GrantedBalance string `json:"granted_balance"`
  98. ToppedUpBalance string `json:"topped_up_balance"`
  99. } `json:"balance_infos"`
  100. }
  101. type OpenRouterCreditResponse struct {
  102. Data struct {
  103. TotalCredits float64 `json:"total_credits"`
  104. TotalUsage float64 `json:"total_usage"`
  105. } `json:"data"`
  106. }
  107. // GetAuthHeader get auth header
  108. func GetAuthHeader(token string) http.Header {
  109. h := http.Header{}
  110. h.Add("Authorization", fmt.Sprintf("Bearer %s", token))
  111. return h
  112. }
  113. func GetResponseBody(method, url string, channel *model.Channel, headers http.Header) ([]byte, error) {
  114. req, err := http.NewRequest(method, url, nil)
  115. if err != nil {
  116. return nil, err
  117. }
  118. for k := range headers {
  119. req.Header.Add(k, headers.Get(k))
  120. }
  121. res, err := service.GetHttpClient().Do(req)
  122. if err != nil {
  123. return nil, err
  124. }
  125. if res.StatusCode != http.StatusOK {
  126. return nil, fmt.Errorf("status code: %d", res.StatusCode)
  127. }
  128. body, err := io.ReadAll(res.Body)
  129. if err != nil {
  130. return nil, err
  131. }
  132. err = res.Body.Close()
  133. if err != nil {
  134. return nil, err
  135. }
  136. return body, nil
  137. }
  138. func updateChannelCloseAIBalance(channel *model.Channel) (float64, error) {
  139. url := fmt.Sprintf("%s/dashboard/billing/credit_grants", channel.GetBaseURL())
  140. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  141. if err != nil {
  142. return 0, err
  143. }
  144. response := OpenAICreditGrants{}
  145. err = json.Unmarshal(body, &response)
  146. if err != nil {
  147. return 0, err
  148. }
  149. channel.UpdateBalance(response.TotalAvailable)
  150. return response.TotalAvailable, nil
  151. }
  152. func updateChannelOpenAISBBalance(channel *model.Channel) (float64, error) {
  153. url := fmt.Sprintf("https://api.openai-sb.com/sb-api/user/status?api_key=%s", channel.Key)
  154. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  155. if err != nil {
  156. return 0, err
  157. }
  158. response := OpenAISBUsageResponse{}
  159. err = json.Unmarshal(body, &response)
  160. if err != nil {
  161. return 0, err
  162. }
  163. if response.Data == nil {
  164. return 0, errors.New(response.Msg)
  165. }
  166. balance, err := strconv.ParseFloat(response.Data.Credit, 64)
  167. if err != nil {
  168. return 0, err
  169. }
  170. channel.UpdateBalance(balance)
  171. return balance, nil
  172. }
  173. func updateChannelAIProxyBalance(channel *model.Channel) (float64, error) {
  174. url := "https://aiproxy.io/api/report/getUserOverview"
  175. headers := http.Header{}
  176. headers.Add("Api-Key", channel.Key)
  177. body, err := GetResponseBody("GET", url, channel, headers)
  178. if err != nil {
  179. return 0, err
  180. }
  181. response := AIProxyUserOverviewResponse{}
  182. err = json.Unmarshal(body, &response)
  183. if err != nil {
  184. return 0, err
  185. }
  186. if !response.Success {
  187. return 0, fmt.Errorf("code: %d, message: %s", response.ErrorCode, response.Message)
  188. }
  189. channel.UpdateBalance(response.Data.TotalPoints)
  190. return response.Data.TotalPoints, nil
  191. }
  192. func updateChannelAPI2GPTBalance(channel *model.Channel) (float64, error) {
  193. url := "https://api.api2gpt.com/dashboard/billing/credit_grants"
  194. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  195. if err != nil {
  196. return 0, err
  197. }
  198. response := API2GPTUsageResponse{}
  199. err = json.Unmarshal(body, &response)
  200. if err != nil {
  201. return 0, err
  202. }
  203. channel.UpdateBalance(response.TotalRemaining)
  204. return response.TotalRemaining, nil
  205. }
  206. func updateChannelSiliconFlowBalance(channel *model.Channel) (float64, error) {
  207. url := "https://api.siliconflow.cn/v1/user/info"
  208. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  209. if err != nil {
  210. return 0, err
  211. }
  212. response := SiliconFlowUsageResponse{}
  213. err = json.Unmarshal(body, &response)
  214. if err != nil {
  215. return 0, err
  216. }
  217. if response.Code != 20000 {
  218. return 0, fmt.Errorf("code: %d, message: %s", response.Code, response.Message)
  219. }
  220. balance, err := strconv.ParseFloat(response.Data.TotalBalance, 64)
  221. if err != nil {
  222. return 0, err
  223. }
  224. channel.UpdateBalance(balance)
  225. return balance, nil
  226. }
  227. func updateChannelDeepSeekBalance(channel *model.Channel) (float64, error) {
  228. url := "https://api.deepseek.com/user/balance"
  229. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  230. if err != nil {
  231. return 0, err
  232. }
  233. response := DeepSeekUsageResponse{}
  234. err = json.Unmarshal(body, &response)
  235. if err != nil {
  236. return 0, err
  237. }
  238. index := -1
  239. for i, balanceInfo := range response.BalanceInfos {
  240. if balanceInfo.Currency == "CNY" {
  241. index = i
  242. break
  243. }
  244. }
  245. if index == -1 {
  246. return 0, errors.New("currency CNY not found")
  247. }
  248. balance, err := strconv.ParseFloat(response.BalanceInfos[index].TotalBalance, 64)
  249. if err != nil {
  250. return 0, err
  251. }
  252. channel.UpdateBalance(balance)
  253. return balance, nil
  254. }
  255. func updateChannelAIGC2DBalance(channel *model.Channel) (float64, error) {
  256. url := "https://api.aigc2d.com/dashboard/billing/credit_grants"
  257. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  258. if err != nil {
  259. return 0, err
  260. }
  261. response := APGC2DGPTUsageResponse{}
  262. err = json.Unmarshal(body, &response)
  263. if err != nil {
  264. return 0, err
  265. }
  266. channel.UpdateBalance(response.TotalAvailable)
  267. return response.TotalAvailable, nil
  268. }
  269. func updateChannelOpenRouterBalance(channel *model.Channel) (float64, error) {
  270. url := "https://openrouter.ai/api/v1/credits"
  271. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  272. if err != nil {
  273. return 0, err
  274. }
  275. response := OpenRouterCreditResponse{}
  276. err = json.Unmarshal(body, &response)
  277. if err != nil {
  278. return 0, err
  279. }
  280. balance := response.Data.TotalCredits - response.Data.TotalUsage
  281. channel.UpdateBalance(balance)
  282. return balance, nil
  283. }
  284. func updateChannelMoonshotBalance(channel *model.Channel) (float64, error) {
  285. url := "https://api.moonshot.cn/v1/users/me/balance"
  286. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  287. if err != nil {
  288. return 0, err
  289. }
  290. type MoonshotBalanceData struct {
  291. AvailableBalance float64 `json:"available_balance"`
  292. VoucherBalance float64 `json:"voucher_balance"`
  293. CashBalance float64 `json:"cash_balance"`
  294. }
  295. type MoonshotBalanceResponse struct {
  296. Code int `json:"code"`
  297. Data MoonshotBalanceData `json:"data"`
  298. Scode string `json:"scode"`
  299. Status bool `json:"status"`
  300. }
  301. response := MoonshotBalanceResponse{}
  302. err = json.Unmarshal(body, &response)
  303. if err != nil {
  304. return 0, err
  305. }
  306. if !response.Status || response.Code != 0 {
  307. return 0, fmt.Errorf("failed to update moonshot balance, status: %v, code: %d, scode: %s", response.Status, response.Code, response.Scode)
  308. }
  309. availableBalanceCny := response.Data.AvailableBalance
  310. availableBalanceUsd := decimal.NewFromFloat(availableBalanceCny).Div(decimal.NewFromFloat(setting.Price)).InexactFloat64()
  311. channel.UpdateBalance(availableBalanceUsd)
  312. return availableBalanceUsd, nil
  313. }
  314. func updateChannelBalance(channel *model.Channel) (float64, error) {
  315. baseURL := constant.ChannelBaseURLs[channel.Type]
  316. if channel.GetBaseURL() == "" {
  317. channel.BaseURL = &baseURL
  318. }
  319. switch channel.Type {
  320. case constant.ChannelTypeOpenAI:
  321. if channel.GetBaseURL() != "" {
  322. baseURL = channel.GetBaseURL()
  323. }
  324. case constant.ChannelTypeAzure:
  325. return 0, errors.New("尚未实现")
  326. case constant.ChannelTypeCustom:
  327. baseURL = channel.GetBaseURL()
  328. //case common.ChannelTypeOpenAISB:
  329. // return updateChannelOpenAISBBalance(channel)
  330. case constant.ChannelTypeAIProxy:
  331. return updateChannelAIProxyBalance(channel)
  332. case constant.ChannelTypeAPI2GPT:
  333. return updateChannelAPI2GPTBalance(channel)
  334. case constant.ChannelTypeAIGC2D:
  335. return updateChannelAIGC2DBalance(channel)
  336. case constant.ChannelTypeSiliconFlow:
  337. return updateChannelSiliconFlowBalance(channel)
  338. case constant.ChannelTypeDeepSeek:
  339. return updateChannelDeepSeekBalance(channel)
  340. case constant.ChannelTypeOpenRouter:
  341. return updateChannelOpenRouterBalance(channel)
  342. case constant.ChannelTypeMoonshot:
  343. return updateChannelMoonshotBalance(channel)
  344. default:
  345. return 0, errors.New("尚未实现")
  346. }
  347. url := fmt.Sprintf("%s/v1/dashboard/billing/subscription", baseURL)
  348. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  349. if err != nil {
  350. return 0, err
  351. }
  352. subscription := OpenAISubscriptionResponse{}
  353. err = json.Unmarshal(body, &subscription)
  354. if err != nil {
  355. return 0, err
  356. }
  357. now := time.Now()
  358. startDate := fmt.Sprintf("%s-01", now.Format("2006-01"))
  359. endDate := now.Format("2006-01-02")
  360. if !subscription.HasPaymentMethod {
  361. startDate = now.AddDate(0, 0, -100).Format("2006-01-02")
  362. }
  363. url = fmt.Sprintf("%s/v1/dashboard/billing/usage?start_date=%s&end_date=%s", baseURL, startDate, endDate)
  364. body, err = GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  365. if err != nil {
  366. return 0, err
  367. }
  368. usage := OpenAIUsageResponse{}
  369. err = json.Unmarshal(body, &usage)
  370. if err != nil {
  371. return 0, err
  372. }
  373. balance := subscription.HardLimitUSD - usage.TotalUsage/100
  374. channel.UpdateBalance(balance)
  375. return balance, nil
  376. }
  377. func UpdateChannelBalance(c *gin.Context) {
  378. id, err := strconv.Atoi(c.Param("id"))
  379. if err != nil {
  380. common.ApiError(c, err)
  381. return
  382. }
  383. channel, err := model.CacheGetChannel(id)
  384. if err != nil {
  385. common.ApiError(c, err)
  386. return
  387. }
  388. if channel.ChannelInfo.IsMultiKey {
  389. c.JSON(http.StatusOK, gin.H{
  390. "success": false,
  391. "message": "多密钥渠道不支持余额查询",
  392. })
  393. return
  394. }
  395. balance, err := updateChannelBalance(channel)
  396. if err != nil {
  397. common.ApiError(c, err)
  398. return
  399. }
  400. c.JSON(http.StatusOK, gin.H{
  401. "success": true,
  402. "message": "",
  403. "balance": balance,
  404. })
  405. }
  406. func updateAllChannelsBalance() error {
  407. channels, err := model.GetAllChannels(0, 0, true, false)
  408. if err != nil {
  409. return err
  410. }
  411. for _, channel := range channels {
  412. if channel.Status != common.ChannelStatusEnabled {
  413. continue
  414. }
  415. if channel.ChannelInfo.IsMultiKey {
  416. continue // skip multi-key channels
  417. }
  418. // TODO: support Azure
  419. //if channel.Type != common.ChannelTypeOpenAI && channel.Type != common.ChannelTypeCustom {
  420. // continue
  421. //}
  422. balance, err := updateChannelBalance(channel)
  423. if err != nil {
  424. continue
  425. } else {
  426. // err is nil & balance <= 0 means quota is used up
  427. if balance <= 0 {
  428. service.DisableChannel(*types.NewChannelError(channel.Id, channel.Type, channel.Name, channel.ChannelInfo.IsMultiKey, "", channel.GetAutoBan()), "余额不足")
  429. }
  430. }
  431. time.Sleep(common.RequestInterval)
  432. }
  433. return nil
  434. }
  435. func UpdateAllChannelsBalance(c *gin.Context) {
  436. // TODO: make it async
  437. err := updateAllChannelsBalance()
  438. if err != nil {
  439. common.ApiError(c, err)
  440. return
  441. }
  442. c.JSON(http.StatusOK, gin.H{
  443. "success": true,
  444. "message": "",
  445. })
  446. return
  447. }
  448. func AutomaticallyUpdateChannels(frequency int) {
  449. for {
  450. time.Sleep(time.Duration(frequency) * time.Minute)
  451. common.SysLog("updating all channels")
  452. _ = updateAllChannelsBalance()
  453. common.SysLog("channels update done")
  454. }
  455. }