channel-billing.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. client, err := service.NewProxyHttpClient(channel.GetSetting().Proxy)
  122. if err != nil {
  123. return nil, err
  124. }
  125. res, err := client.Do(req)
  126. if err != nil {
  127. return nil, err
  128. }
  129. if res.StatusCode != http.StatusOK {
  130. return nil, fmt.Errorf("status code: %d", res.StatusCode)
  131. }
  132. body, err := io.ReadAll(res.Body)
  133. if err != nil {
  134. return nil, err
  135. }
  136. err = res.Body.Close()
  137. if err != nil {
  138. return nil, err
  139. }
  140. return body, nil
  141. }
  142. func updateChannelCloseAIBalance(channel *model.Channel) (float64, error) {
  143. url := fmt.Sprintf("%s/dashboard/billing/credit_grants", channel.GetBaseURL())
  144. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  145. if err != nil {
  146. return 0, err
  147. }
  148. response := OpenAICreditGrants{}
  149. err = json.Unmarshal(body, &response)
  150. if err != nil {
  151. return 0, err
  152. }
  153. channel.UpdateBalance(response.TotalAvailable)
  154. return response.TotalAvailable, nil
  155. }
  156. func updateChannelOpenAISBBalance(channel *model.Channel) (float64, error) {
  157. url := fmt.Sprintf("https://api.openai-sb.com/sb-api/user/status?api_key=%s", channel.Key)
  158. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  159. if err != nil {
  160. return 0, err
  161. }
  162. response := OpenAISBUsageResponse{}
  163. err = json.Unmarshal(body, &response)
  164. if err != nil {
  165. return 0, err
  166. }
  167. if response.Data == nil {
  168. return 0, errors.New(response.Msg)
  169. }
  170. balance, err := strconv.ParseFloat(response.Data.Credit, 64)
  171. if err != nil {
  172. return 0, err
  173. }
  174. channel.UpdateBalance(balance)
  175. return balance, nil
  176. }
  177. func updateChannelAIProxyBalance(channel *model.Channel) (float64, error) {
  178. url := "https://aiproxy.io/api/report/getUserOverview"
  179. headers := http.Header{}
  180. headers.Add("Api-Key", channel.Key)
  181. body, err := GetResponseBody("GET", url, channel, headers)
  182. if err != nil {
  183. return 0, err
  184. }
  185. response := AIProxyUserOverviewResponse{}
  186. err = json.Unmarshal(body, &response)
  187. if err != nil {
  188. return 0, err
  189. }
  190. if !response.Success {
  191. return 0, fmt.Errorf("code: %d, message: %s", response.ErrorCode, response.Message)
  192. }
  193. channel.UpdateBalance(response.Data.TotalPoints)
  194. return response.Data.TotalPoints, nil
  195. }
  196. func updateChannelAPI2GPTBalance(channel *model.Channel) (float64, error) {
  197. url := "https://api.api2gpt.com/dashboard/billing/credit_grants"
  198. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  199. if err != nil {
  200. return 0, err
  201. }
  202. response := API2GPTUsageResponse{}
  203. err = json.Unmarshal(body, &response)
  204. if err != nil {
  205. return 0, err
  206. }
  207. channel.UpdateBalance(response.TotalRemaining)
  208. return response.TotalRemaining, nil
  209. }
  210. func updateChannelSiliconFlowBalance(channel *model.Channel) (float64, error) {
  211. url := "https://api.siliconflow.cn/v1/user/info"
  212. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  213. if err != nil {
  214. return 0, err
  215. }
  216. response := SiliconFlowUsageResponse{}
  217. err = json.Unmarshal(body, &response)
  218. if err != nil {
  219. return 0, err
  220. }
  221. if response.Code != 20000 {
  222. return 0, fmt.Errorf("code: %d, message: %s", response.Code, response.Message)
  223. }
  224. balance, err := strconv.ParseFloat(response.Data.TotalBalance, 64)
  225. if err != nil {
  226. return 0, err
  227. }
  228. channel.UpdateBalance(balance)
  229. return balance, nil
  230. }
  231. func updateChannelDeepSeekBalance(channel *model.Channel) (float64, error) {
  232. url := "https://api.deepseek.com/user/balance"
  233. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  234. if err != nil {
  235. return 0, err
  236. }
  237. response := DeepSeekUsageResponse{}
  238. err = json.Unmarshal(body, &response)
  239. if err != nil {
  240. return 0, err
  241. }
  242. index := -1
  243. for i, balanceInfo := range response.BalanceInfos {
  244. if balanceInfo.Currency == "CNY" {
  245. index = i
  246. break
  247. }
  248. }
  249. if index == -1 {
  250. return 0, errors.New("currency CNY not found")
  251. }
  252. balance, err := strconv.ParseFloat(response.BalanceInfos[index].TotalBalance, 64)
  253. if err != nil {
  254. return 0, err
  255. }
  256. channel.UpdateBalance(balance)
  257. return balance, nil
  258. }
  259. func updateChannelAIGC2DBalance(channel *model.Channel) (float64, error) {
  260. url := "https://api.aigc2d.com/dashboard/billing/credit_grants"
  261. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  262. if err != nil {
  263. return 0, err
  264. }
  265. response := APGC2DGPTUsageResponse{}
  266. err = json.Unmarshal(body, &response)
  267. if err != nil {
  268. return 0, err
  269. }
  270. channel.UpdateBalance(response.TotalAvailable)
  271. return response.TotalAvailable, nil
  272. }
  273. func updateChannelOpenRouterBalance(channel *model.Channel) (float64, error) {
  274. url := "https://openrouter.ai/api/v1/credits"
  275. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  276. if err != nil {
  277. return 0, err
  278. }
  279. response := OpenRouterCreditResponse{}
  280. err = json.Unmarshal(body, &response)
  281. if err != nil {
  282. return 0, err
  283. }
  284. balance := response.Data.TotalCredits - response.Data.TotalUsage
  285. channel.UpdateBalance(balance)
  286. return balance, nil
  287. }
  288. func updateChannelMoonshotBalance(channel *model.Channel) (float64, error) {
  289. url := "https://api.moonshot.cn/v1/users/me/balance"
  290. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  291. if err != nil {
  292. return 0, err
  293. }
  294. type MoonshotBalanceData struct {
  295. AvailableBalance float64 `json:"available_balance"`
  296. VoucherBalance float64 `json:"voucher_balance"`
  297. CashBalance float64 `json:"cash_balance"`
  298. }
  299. type MoonshotBalanceResponse struct {
  300. Code int `json:"code"`
  301. Data MoonshotBalanceData `json:"data"`
  302. Scode string `json:"scode"`
  303. Status bool `json:"status"`
  304. }
  305. response := MoonshotBalanceResponse{}
  306. err = json.Unmarshal(body, &response)
  307. if err != nil {
  308. return 0, err
  309. }
  310. if !response.Status || response.Code != 0 {
  311. return 0, fmt.Errorf("failed to update moonshot balance, status: %v, code: %d, scode: %s", response.Status, response.Code, response.Scode)
  312. }
  313. availableBalanceCny := response.Data.AvailableBalance
  314. availableBalanceUsd := decimal.NewFromFloat(availableBalanceCny).Div(decimal.NewFromFloat(setting.Price)).InexactFloat64()
  315. channel.UpdateBalance(availableBalanceUsd)
  316. return availableBalanceUsd, nil
  317. }
  318. func updateChannelBalance(channel *model.Channel) (float64, error) {
  319. baseURL := constant.ChannelBaseURLs[channel.Type]
  320. if channel.GetBaseURL() == "" {
  321. channel.BaseURL = &baseURL
  322. }
  323. switch channel.Type {
  324. case constant.ChannelTypeOpenAI:
  325. if channel.GetBaseURL() != "" {
  326. baseURL = channel.GetBaseURL()
  327. }
  328. case constant.ChannelTypeAzure:
  329. return 0, errors.New("尚未实现")
  330. case constant.ChannelTypeCustom:
  331. baseURL = channel.GetBaseURL()
  332. //case common.ChannelTypeOpenAISB:
  333. // return updateChannelOpenAISBBalance(channel)
  334. case constant.ChannelTypeAIProxy:
  335. return updateChannelAIProxyBalance(channel)
  336. case constant.ChannelTypeAPI2GPT:
  337. return updateChannelAPI2GPTBalance(channel)
  338. case constant.ChannelTypeAIGC2D:
  339. return updateChannelAIGC2DBalance(channel)
  340. case constant.ChannelTypeSiliconFlow:
  341. return updateChannelSiliconFlowBalance(channel)
  342. case constant.ChannelTypeDeepSeek:
  343. return updateChannelDeepSeekBalance(channel)
  344. case constant.ChannelTypeOpenRouter:
  345. return updateChannelOpenRouterBalance(channel)
  346. case constant.ChannelTypeMoonshot:
  347. return updateChannelMoonshotBalance(channel)
  348. default:
  349. return 0, errors.New("尚未实现")
  350. }
  351. url := fmt.Sprintf("%s/v1/dashboard/billing/subscription", baseURL)
  352. body, err := GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  353. if err != nil {
  354. return 0, err
  355. }
  356. subscription := OpenAISubscriptionResponse{}
  357. err = json.Unmarshal(body, &subscription)
  358. if err != nil {
  359. return 0, err
  360. }
  361. now := time.Now()
  362. startDate := fmt.Sprintf("%s-01", now.Format("2006-01"))
  363. endDate := now.Format("2006-01-02")
  364. if !subscription.HasPaymentMethod {
  365. startDate = now.AddDate(0, 0, -100).Format("2006-01-02")
  366. }
  367. url = fmt.Sprintf("%s/v1/dashboard/billing/usage?start_date=%s&end_date=%s", baseURL, startDate, endDate)
  368. body, err = GetResponseBody("GET", url, channel, GetAuthHeader(channel.Key))
  369. if err != nil {
  370. return 0, err
  371. }
  372. usage := OpenAIUsageResponse{}
  373. err = json.Unmarshal(body, &usage)
  374. if err != nil {
  375. return 0, err
  376. }
  377. balance := subscription.HardLimitUSD - usage.TotalUsage/100
  378. channel.UpdateBalance(balance)
  379. return balance, nil
  380. }
  381. func UpdateChannelBalance(c *gin.Context) {
  382. id, err := strconv.Atoi(c.Param("id"))
  383. if err != nil {
  384. common.ApiError(c, err)
  385. return
  386. }
  387. channel, err := model.CacheGetChannel(id)
  388. if err != nil {
  389. common.ApiError(c, err)
  390. return
  391. }
  392. if channel.ChannelInfo.IsMultiKey {
  393. c.JSON(http.StatusOK, gin.H{
  394. "success": false,
  395. "message": "多密钥渠道不支持余额查询",
  396. })
  397. return
  398. }
  399. balance, err := updateChannelBalance(channel)
  400. if err != nil {
  401. common.ApiError(c, err)
  402. return
  403. }
  404. c.JSON(http.StatusOK, gin.H{
  405. "success": true,
  406. "message": "",
  407. "balance": balance,
  408. })
  409. }
  410. func updateAllChannelsBalance() error {
  411. channels, err := model.GetAllChannels(0, 0, true, false)
  412. if err != nil {
  413. return err
  414. }
  415. for _, channel := range channels {
  416. if channel.Status != common.ChannelStatusEnabled {
  417. continue
  418. }
  419. if channel.ChannelInfo.IsMultiKey {
  420. continue // skip multi-key channels
  421. }
  422. // TODO: support Azure
  423. //if channel.Type != common.ChannelTypeOpenAI && channel.Type != common.ChannelTypeCustom {
  424. // continue
  425. //}
  426. balance, err := updateChannelBalance(channel)
  427. if err != nil {
  428. continue
  429. } else {
  430. // err is nil & balance <= 0 means quota is used up
  431. if balance <= 0 {
  432. service.DisableChannel(*types.NewChannelError(channel.Id, channel.Type, channel.Name, channel.ChannelInfo.IsMultiKey, "", channel.GetAutoBan()), "余额不足")
  433. }
  434. }
  435. time.Sleep(common.RequestInterval)
  436. }
  437. return nil
  438. }
  439. func UpdateAllChannelsBalance(c *gin.Context) {
  440. // TODO: make it async
  441. err := updateAllChannelsBalance()
  442. if err != nil {
  443. common.ApiError(c, err)
  444. return
  445. }
  446. c.JSON(http.StatusOK, gin.H{
  447. "success": true,
  448. "message": "",
  449. })
  450. return
  451. }
  452. func AutomaticallyUpdateChannels(frequency int) {
  453. for {
  454. time.Sleep(time.Duration(frequency) * time.Minute)
  455. common.SysLog("updating all channels")
  456. _ = updateAllChannelsBalance()
  457. common.SysLog("channels update done")
  458. }
  459. }