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 <790348264@qq.com>
  • Loading branch information
2 people authored and Equim-chan committed Apr 4, 2023
1 parent 08ea7bb commit 79a2726
Show file tree
Hide file tree
Showing 6 changed files with 35 additions and 39 deletions.
61 changes: 26 additions & 35 deletions service/src/chatgpt/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +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 { messageStore } from '../store'
import type { BalanceResponse, RequestOptions } from './types'

const { HttpsProxyAgent } = httpsProxyAgent

Expand Down Expand Up @@ -128,6 +126,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,49 +136,40 @@ async function fetchBalance() {

const API_BASE_URL = isNotEmptyString(OPENAI_API_BASE_URL)
? OPENAI_API_BASE_URL
: 'https://api.openai.com/v1'
: 'https://api.openai.com'

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 balance.toFixed(3)
}
catch {
return '-'
}
}
const [startDate, endDate] = formatDate()

async function fetchMonthlyUsage() {
const OPENAI_API_KEY = process.env.OPENAI_API_KEY
const OPENAI_API_BASE_URL = process.env.OPENAI_API_BASE_URL
// 每月使用量
const urlUsage = `${API_BASE_URL}/v1/dashboard/billing/usage?start_date=${startDate}&end_date=${endDate}`

if (!isNotEmptyString(OPENAI_API_KEY))
return '-'

const API_BASE_URL = isNotEmptyString(OPENAI_API_BASE_URL)
? OPENAI_API_BASE_URL
: 'https://api.openai.com/v1'

const now = new Date()
const startOfMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1))
const startOfNextMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1))
const headers = {
'Authorization': `Bearer ${OPENAI_API_KEY}`,
'Content-Type': 'application/json',
}

try {
const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${OPENAI_API_KEY}` }
const params = {
'start_date': startOfMonth.toISOString().substring(0, 10),
'end_date': startOfNextMonth.toISOString().substring(0, 10),
}
const response = await axios.get(`${API_BASE_URL}/dashboard/billing/usage`, { headers, params })
const monthlyUsage = (response.data.total_usage ?? 0) / 100
return monthlyUsage.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 '-'
}
}

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 monthlyUsage = await fetchMonthlyUsage()
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 @@ -8,3 +8,7 @@ export interface RequestOptions {
temperature?: number
topP?: number
}

export interface BalanceResponse {
total_usage: number
}
3 changes: 2 additions & 1 deletion src/components/common/Setting/About.vue
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ onMounted(() => {
</div>
<p>{{ $t("setting.api") }}:{{ config?.apiModel ?? '-' }}</p>
<p v-if="isChatGPTAPI">
{{ $t("setting.monthlyUsage") }}:${{ config?.monthlyUsage ?? '-' }}
{{ $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
2 changes: 1 addition & 1 deletion src/locales/en-US.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export default {
socks: 'Socks',
httpsProxy: 'HTTPS Proxy',
balance: 'API Balance',
monthlyUsage: 'Monthly usage',
monthlyUsage: 'Monthly Usage',
},
store: {
siderButton: 'Prompt Store',
Expand Down
2 changes: 1 addition & 1 deletion src/locales/zh-CN.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export default {
socks: 'Socks',
httpsProxy: 'HTTPS Proxy',
balance: 'API余额',
monthlyUsage: '本月用量',
monthlyUsage: '本月使用量',
},
store: {
siderButton: '提示词商店',
Expand Down
2 changes: 1 addition & 1 deletion src/locales/zh-TW.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export default {
socks: 'Socks',
httpsProxy: 'HTTPS Proxy',
balance: 'API余額',
monthlyUsage: '本月用量',
monthlyUsage: '本月使用量',
},
store: {
siderButton: '提示詞商店',
Expand Down

0 comments on commit 79a2726

Please # to comment.