@@ -5,11 +5,10 @@ import { ChatGPTAPI, ChatGPTUnofficialProxyAPI } from 'chatgpt'
5
5
import { SocksProxyAgent } from 'socks-proxy-agent'
6
6
import httpsProxyAgent from 'https-proxy-agent'
7
7
import fetch from 'node-fetch'
8
- import axios from 'axios'
9
8
import { sendResponse } from '../utils'
10
9
import { isNotEmptyString } from '../utils/is'
11
10
import type { ApiModel , ChatContext , ChatGPTUnofficialProxyAPIOptions , ModelConfig } from '../types'
12
- import type { RequestOptions } from './types'
11
+ import type { BalanceResponse , RequestOptions } from './types'
13
12
14
13
const { HttpsProxyAgent } = httpsProxyAgent
15
14
@@ -126,6 +125,8 @@ async function chatReplyProcess(options: RequestOptions) {
126
125
}
127
126
128
127
async function fetchBalance ( ) {
128
+ // 计算起始日期和结束日期
129
+
129
130
const OPENAI_API_KEY = process . env . OPENAI_API_KEY
130
131
const OPENAI_API_BASE_URL = process . env . OPENAI_API_BASE_URL
131
132
@@ -136,17 +137,38 @@ async function fetchBalance() {
136
137
? OPENAI_API_BASE_URL
137
138
: 'https://api.openai.com'
138
139
140
+ const [ startDate , endDate ] = formatDate ( )
141
+
142
+ // 每月使用量
143
+ const urlUsage = `${ API_BASE_URL } /v1/dashboard/billing/usage?start_date=${ startDate } &end_date=${ endDate } `
144
+
145
+ const headers = {
146
+ 'Authorization' : `Bearer ${ OPENAI_API_KEY } ` ,
147
+ 'Content-Type' : 'application/json' ,
148
+ }
149
+
139
150
try {
140
- const headers = { 'Content-Type' : 'application/json' , 'Authorization' : `Bearer ${ OPENAI_API_KEY } ` }
141
- const response = await axios . get ( `${ API_BASE_URL } /dashboard/billing/credit_grants` , { headers } )
142
- const balance = response . data . total_available ?? 0
143
- return Promise . resolve ( balance . toFixed ( 3 ) )
151
+ // 获取已使用量
152
+ const useResponse = await fetch ( urlUsage , { headers } )
153
+ const usageData = await useResponse . json ( ) as BalanceResponse
154
+ const usage = Math . round ( usageData . total_usage ) / 100
155
+ return Promise . resolve ( usage ? `$${ usage } ` : '-' )
144
156
}
145
157
catch {
146
158
return Promise . resolve ( '-' )
147
159
}
148
160
}
149
161
162
+ function formatDate ( ) : string [ ] {
163
+ const today = new Date ( )
164
+ const year = today . getFullYear ( )
165
+ const month = today . getMonth ( ) + 1
166
+ const lastDay = new Date ( year , month , 0 )
167
+ const formattedFirstDay = `${ year } -${ month . toString ( ) . padStart ( 2 , '0' ) } -01`
168
+ const formattedLastDay = `${ year } -${ month . toString ( ) . padStart ( 2 , '0' ) } -${ lastDay . getDate ( ) . toString ( ) . padStart ( 2 , '0' ) } `
169
+ return [ formattedFirstDay , formattedLastDay ]
170
+ }
171
+
150
172
async function chatConfig ( ) {
151
173
const balance = await fetchBalance ( )
152
174
const reverseProxy = process . env . API_REVERSE_PROXY ?? '-'
0 commit comments