channel-billing.go 14 KB

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