fix: 修复API余额查询 (#1174)

* fix: 使API余额查询可用

* chore: 调整计算方式

* perf: 余额描述变更

---------

Co-authored-by: ChenZhaoYu <790348264@qq.com>
main
wangxi 2 years ago committed by GitHub
parent b07f01b0cf
commit 1187d88593
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -5,11 +5,10 @@ import { ChatGPTAPI, ChatGPTUnofficialProxyAPI } from 'chatgpt'
import { SocksProxyAgent } from 'socks-proxy-agent' import { SocksProxyAgent } from 'socks-proxy-agent'
import httpsProxyAgent from 'https-proxy-agent' import httpsProxyAgent from 'https-proxy-agent'
import fetch from 'node-fetch' import fetch from 'node-fetch'
import axios from 'axios'
import { sendResponse } from '../utils' import { sendResponse } from '../utils'
import { isNotEmptyString } from '../utils/is' import { isNotEmptyString } from '../utils/is'
import type { ApiModel, ChatContext, ChatGPTUnofficialProxyAPIOptions, ModelConfig } from '../types' import type { ApiModel, ChatContext, ChatGPTUnofficialProxyAPIOptions, ModelConfig } from '../types'
import type { RequestOptions } from './types' import type { BalanceResponse, RequestOptions } from './types'
const { HttpsProxyAgent } = httpsProxyAgent const { HttpsProxyAgent } = httpsProxyAgent
@ -126,6 +125,8 @@ async function chatReplyProcess(options: RequestOptions) {
} }
async function fetchBalance() { async function fetchBalance() {
// 计算起始日期和结束日期
const OPENAI_API_KEY = process.env.OPENAI_API_KEY const OPENAI_API_KEY = process.env.OPENAI_API_KEY
const OPENAI_API_BASE_URL = process.env.OPENAI_API_BASE_URL const OPENAI_API_BASE_URL = process.env.OPENAI_API_BASE_URL
@ -136,17 +137,38 @@ async function fetchBalance() {
? OPENAI_API_BASE_URL ? OPENAI_API_BASE_URL
: 'https://api.openai.com' : 'https://api.openai.com'
const [startDate, endDate] = formatDate()
// 每月使用量
const urlUsage = `${API_BASE_URL}/v1/dashboard/billing/usage?start_date=${startDate}&end_date=${endDate}`
const headers = {
'Authorization': `Bearer ${OPENAI_API_KEY}`,
'Content-Type': 'application/json',
}
try { try {
const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${OPENAI_API_KEY}` } // 获取已使用量
const response = await axios.get(`${API_BASE_URL}/dashboard/billing/credit_grants`, { headers }) const useResponse = await fetch(urlUsage, { headers })
const balance = response.data.total_available ?? 0 const usageData = await useResponse.json() as BalanceResponse
return Promise.resolve(balance.toFixed(3)) const usage = Math.round(usageData.total_usage) / 100
return Promise.resolve(usage ? `$${usage}` : '-')
} }
catch { catch {
return Promise.resolve('-') return Promise.resolve('-')
} }
} }
function formatDate(): string[] {
const today = new Date()
const year = today.getFullYear()
const month = today.getMonth() + 1
const lastDay = new Date(year, month, 0)
const formattedFirstDay = `${year}-${month.toString().padStart(2, '0')}-01`
const formattedLastDay = `${year}-${month.toString().padStart(2, '0')}-${lastDay.getDate().toString().padStart(2, '0')}`
return [formattedFirstDay, formattedLastDay]
}
async function chatConfig() { async function chatConfig() {
const balance = await fetchBalance() const balance = await fetchBalance()
const reverseProxy = process.env.API_REVERSE_PROXY ?? '-' const reverseProxy = process.env.API_REVERSE_PROXY ?? '-'

@ -6,3 +6,7 @@ export interface RequestOptions {
process?: (chat: ChatMessage) => void process?: (chat: ChatMessage) => void
systemMessage?: string systemMessage?: string
} }
export interface BalanceResponse {
total_usage: number
}

@ -63,6 +63,7 @@ onMounted(() => {
<p>{{ $t("setting.api") }}{{ config?.apiModel ?? '-' }}</p> <p>{{ $t("setting.api") }}{{ config?.apiModel ?? '-' }}</p>
<p v-if="isChatGPTAPI"> <p v-if="isChatGPTAPI">
{{ $t("setting.balance") }}{{ config?.balance ?? '-' }} {{ $t("setting.balance") }}{{ config?.balance ?? '-' }}
<span class="text-xs text-neutral-400">({{ $t('setting.monthlyUsage') }})</span>
</p> </p>
<p v-if="!isChatGPTAPI"> <p v-if="!isChatGPTAPI">
{{ $t("setting.reverseProxy") }}{{ config?.reverseProxy ?? '-' }} {{ $t("setting.reverseProxy") }}{{ config?.reverseProxy ?? '-' }}

@ -69,6 +69,7 @@ export default {
socks: 'Socks', socks: 'Socks',
httpsProxy: 'HTTPS Proxy', httpsProxy: 'HTTPS Proxy',
balance: 'API Balance', balance: 'API Balance',
monthlyUsage: 'Monthly Usage',
}, },
store: { store: {
siderButton: 'Prompt Store', siderButton: 'Prompt Store',

@ -69,6 +69,7 @@ export default {
socks: 'Socks', socks: 'Socks',
httpsProxy: 'HTTPS Proxy', httpsProxy: 'HTTPS Proxy',
balance: 'API余额', balance: 'API余额',
monthlyUsage: '本月使用量',
}, },
store: { store: {
siderButton: '提示词商店', siderButton: '提示词商店',

@ -69,6 +69,7 @@ export default {
socks: 'Socks', socks: 'Socks',
httpsProxy: 'HTTPS Proxy', httpsProxy: 'HTTPS Proxy',
balance: 'API余額', balance: 'API余額',
monthlyUsage: '本月使用量',
}, },
store: { store: {
siderButton: '提示詞商店', siderButton: '提示詞商店',

Loading…
Cancel
Save