Skip to content

Commit

Permalink
fix: 修复API余额查询 (Chanzhaoyu#1174)
Browse files Browse the repository at this point in the history
* fix: 使API余额查询可用

* chore: 调整计算方式

* perf: 余额描述变更

---------

Co-authored-by: ChenZhaoYu <[email protected]>
  • Loading branch information
LuckyWang6 and Chanzhaoyu committed Apr 4, 2023
1 parent b07f01b commit 1187d88
Show file tree
Hide file tree
Showing 6 changed files with 36 additions and 6 deletions.
34 changes: 28 additions & 6 deletions service/src/chatgpt/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@ import { ChatGPTAPI, ChatGPTUnofficialProxyAPI } from 'chatgpt'
import { SocksProxyAgent } from 'socks-proxy-agent'
import httpsProxyAgent from 'https-proxy-agent'
import fetch from 'node-fetch'
import axios from 'axios'
import { sendResponse } from '../utils'
import { isNotEmptyString } from '../utils/is'
import type { ApiModel, ChatContext, ChatGPTUnofficialProxyAPIOptions, ModelConfig } from '../types'
import type { RequestOptions } from './types'
import type { BalanceResponse, RequestOptions } from './types'

const { HttpsProxyAgent } = httpsProxyAgent

Expand Down Expand Up @@ -126,6 +125,8 @@ async function chatReplyProcess(options: RequestOptions) {
}

async function fetchBalance() {
// 计算起始日期和结束日期

const OPENAI_API_KEY = process.env.OPENAI_API_KEY
const OPENAI_API_BASE_URL = process.env.OPENAI_API_BASE_URL

Expand All @@ -136,17 +137,38 @@ async function fetchBalance() {
? OPENAI_API_BASE_URL
: '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 {
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 balance = response.data.total_available ?? 0
return Promise.resolve(balance.toFixed(3))
// 获取已使用量
const useResponse = await fetch(urlUsage, { headers })
const usageData = await useResponse.json() as BalanceResponse
const usage = Math.round(usageData.total_usage) / 100
return Promise.resolve(usage ? `$${usage}` : '-')
}
catch {
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() {
const balance = await fetchBalance()
const reverseProxy = process.env.API_REVERSE_PROXY ?? '-'
Expand Down
4 changes: 4 additions & 0 deletions service/src/chatgpt/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,7 @@ export interface RequestOptions {
process?: (chat: ChatMessage) => void
systemMessage?: string
}

export interface BalanceResponse {
total_usage: number
}
1 change: 1 addition & 0 deletions src/components/common/Setting/About.vue
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ onMounted(() => {
<p>{{ $t("setting.api") }}:{{ config?.apiModel ?? '-' }}</p>
<p v-if="isChatGPTAPI">
{{ $t("setting.balance") }}:{{ config?.balance ?? '-' }}
<span class="text-xs text-neutral-400">({{ $t('setting.monthlyUsage') }})</span>
</p>
<p v-if="!isChatGPTAPI">
{{ $t("setting.reverseProxy") }}:{{ config?.reverseProxy ?? '-' }}
Expand Down
1 change: 1 addition & 0 deletions src/locales/en-US.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ export default {
socks: 'Socks',
httpsProxy: 'HTTPS Proxy',
balance: 'API Balance',
monthlyUsage: 'Monthly Usage',
},
store: {
siderButton: 'Prompt Store',
Expand Down
1 change: 1 addition & 0 deletions src/locales/zh-CN.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ export default {
socks: 'Socks',
httpsProxy: 'HTTPS Proxy',
balance: 'API余额',
monthlyUsage: '本月使用量',
},
store: {
siderButton: '提示词商店',
Expand Down
1 change: 1 addition & 0 deletions src/locales/zh-TW.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ export default {
socks: 'Socks',
httpsProxy: 'HTTPS Proxy',
balance: 'API余額',
monthlyUsage: '本月使用量',
},
store: {
siderButton: '提示詞商店',
Expand Down

0 comments on commit 1187d88

Please sign in to comment.