From 6009c92a44422e95442b28595a90a454282b64d9 Mon Sep 17 00:00:00 2001 From: TBXark Date: Sun, 23 Apr 2023 11:39:25 +0800 Subject: [PATCH] =?UTF-8?q?perf:=20=E4=BC=98=E5=8C=96openai=20key=E8=8E=B7?= =?UTF-8?q?=E5=8F=96=E9=80=BB=E8=BE=91,=E4=BC=98=E5=8C=96=E8=B4=A6?= =?UTF-8?q?=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dist/buildinfo.json | 2 +- dist/index.js | 81 +++++++++++++++++++++------------------------ dist/timestamp | 2 +- src/context.js | 18 ++++++++++ src/i18n/en.js | 2 +- src/i18n/zh-hans.js | 2 +- src/i18n/zh-hant.js | 2 +- src/message.js | 2 +- src/openai.js | 64 ++++++++++------------------------- 9 files changed, 80 insertions(+), 95 deletions(-) diff --git a/dist/buildinfo.json b/dist/buildinfo.json index 8f29a9fd..5fe4bedf 100644 --- a/dist/buildinfo.json +++ b/dist/buildinfo.json @@ -1 +1 @@ -{"sha": "4e15113", "timestamp": 1682166538} +{"sha": "311c627", "timestamp": 1682221130} diff --git a/dist/index.js b/dist/index.js index 067ff35b..fb7f9e1c 100644 --- a/dist/index.js +++ b/dist/index.js @@ -43,9 +43,9 @@ var ENV = { // 检查更新的分支 UPDATE_BRANCH: "master", // 当前版本 - BUILD_TIMESTAMP: 1682166538, + BUILD_TIMESTAMP: 1682221130, // 当前版本 commit id - BUILD_VERSION: "4e15113", + BUILD_VERSION: "311c627", /** * @type {I18n} */ @@ -281,6 +281,23 @@ var Context = class { await this._initUserConfig(this.SHARE_CONTEXT.configStoreKey); console.log(this.USER_CONFIG); } + /** + * + * @return {string|null} + */ + openAIKeyFromContext() { + if (this.USER_CONFIG.OPENAI_API_KEY) { + return this.USER_CONFIG.OPENAI_API_KEY; + } + if (Array.isArray(ENV.API_KEY)) { + if (ENV.API_KEY.length === 0) { + return null; + } + return ENV.API_KEY[Math.floor(Math.random() * ENV.API_KEY.length)]; + } else { + return ENV.API_KEY; + } + } }; // src/telegram.js @@ -774,16 +791,6 @@ function makeResponse200(resp) { } // src/openai.js -function openAIKeyFromContext(context) { - if (context.USER_CONFIG.OPENAI_API_KEY) { - return context.USER_CONFIG.OPENAI_API_KEY; - } - if (Array.isArray(ENV.API_KEY)) { - return ENV.API_KEY[Math.floor(("0." + Math.sin((/* @__PURE__ */ new Date()).getTime()).toString().substring(6)) * ENV.API_KEY.length)]; - } else { - return ENV.API_KEY; - } -} function extractContentFromStreamData(stream) { const line = stream.split("\n"); let remainingStr = ""; @@ -808,7 +815,7 @@ function extractContentFromStreamData(stream) { async function requestCompletionsFromOpenAI(message, history, context, onStream) { console.log(`requestCompletionsFromOpenAI: ${message}`); console.log(`history: ${JSON.stringify(history, null, 2)}`); - const key = openAIKeyFromContext(context); + const key = context.openAIKeyFromContext(); const body = { model: ENV.CHAT_MODEL, ...context.USER_CONFIG.OPENAI_API_EXTRA_PARAMS, @@ -860,7 +867,7 @@ Body: ${JSON.stringify(body)}`); } async function requestImageFromOpenAI(prompt, context) { console.log(`requestImageFromOpenAI: ${prompt}`); - const key = openAIKeyFromContext(context); + const key = context.openAIKeyFromContext(); const body = { prompt, n: 1, @@ -881,38 +888,26 @@ async function requestImageFromOpenAI(prompt, context) { return resp.data[0].url; } async function requestBill(context) { - const now = /* @__PURE__ */ new Date(); const apiUrl = ENV.OPENAI_API_DOMAIN; - const key = openAIKeyFromContext(context); - let startDate = new Date(now - 90 * 24 * 60 * 60 * 1e3); - const endDate = new Date(now.getTime() + 24 * 60 * 60 * 1e3); - const subDate = new Date(now); - subDate.setDate(1); - const formatDate = (date) => { - const year = date.getFullYear(); - const month = (date.getMonth() + 1).toString().padStart(2, "0"); - const day = date.getDate().toString().padStart(2, "0"); - return `${year}-${month}-${day}`; - }; - const urlSubscription = `${apiUrl}/v1/dashboard/billing/subscription`; - let urlUsage = `${apiUrl}/v1/dashboard/billing/usage?start_date=${formatDate(startDate)}&end_date=${formatDate(endDate)}`; + const key = context.openAIKeyFromContext(); + const date = /* @__PURE__ */ new Date(); + const year = date.getFullYear(); + const month = (date.getMonth() + 1).toString().padStart(2, "0"); + const day = date.getDate().toString().padStart(2, "0"); + const endDate = `${year}-${month}-${day}`; + const startDate = `${year}-${month}-01`; + const urlSub = `${apiUrl}/v1/dashboard/billing/subscription`; + const urlUsage = `${apiUrl}/v1/dashboard/billing/usage?start_date=${startDate}&end_date=${endDate}`; const headers = { "Authorization": "Bearer " + key, "Content-Type": "application/json" }; try { - let response = await fetch(urlSubscription, { headers }); - if (!response.ok) { - return {}; - } - const subscriptionData = await response.json(); + const subResp = await fetch(urlSub, { headers }); + const subscriptionData = await subResp.json(); const totalAmount = subscriptionData.hard_limit_usd; - if (totalAmount > 20) { - startDate = subDate; - } - urlUsage = `${apiUrl}/v1/dashboard/billing/usage?start_date=${formatDate(startDate)}&end_date=${formatDate(endDate)}`; - response = await fetch(urlUsage, { headers }); - const usageData = await response.json(); + const usageResp = await fetch(urlUsage, { headers }); + const usageData = await usageResp.json(); const totalUsage = usageData.total_usage / 100; const remaining = totalAmount - totalUsage; return { @@ -1103,7 +1098,7 @@ var zh_hans_default = { "command_error": (e) => `\u547D\u4EE4\u6267\u884C\u9519\u8BEF: ${e.message}` }, bill: { - "bill_detail": (totalAmount, totalUsage, remaining) => `\u{1F4CA} \u5F53\u524D\u673A\u5668\u4EBA\u7528\u91CF + "bill_detail": (totalAmount, totalUsage, remaining) => `\u{1F4CA} \u672C\u6708\u673A\u5668\u4EBA\u7528\u91CF - \u603B\u989D\u5EA6: $${totalAmount || 0} - \u5DF2\u4F7F\u7528: $${totalUsage || 0} @@ -1186,7 +1181,7 @@ var zh_hant_default = { "command_error": (e) => `\u547D\u4EE4\u57F7\u884C\u51FA\u932F\uFF1A${e.message}` }, bill: { - "bill_detail": (totalAmount, totalUsage, remaining) => `\u{1F4CA} \u5F53\u524D\u673A\u5668\u4EBA\u7528\u91CF + "bill_detail": (totalAmount, totalUsage, remaining) => `\u{1F4CA} \u672C\u6708\u673A\u5668\u4EBA\u7528\u91CF - \u603B\u989D\u5EA6: $${totalAmount || 0} - \u5DF2\u4F7F\u7528: $${totalUsage || 0} @@ -1269,7 +1264,7 @@ var en_default = { "command_error": (e) => `Command execution error: ${e.message}` }, bill: { - "bill_detail": (totalAmount, totalUsage, remaining) => `\u{1F4CA} Current robot usage + "bill_detail": (totalAmount, totalUsage, remaining) => `\u{1F4CA} This month usage - Amount: $${totalAmount || 0} - Usage: $${totalUsage || 0} @@ -1782,7 +1777,7 @@ async function msgIgnoreOldMessage(message, context) { return null; } async function msgCheckEnvIsReady(message, context) { - if (!ENV.API_KEY || ENV.API_KEY.length === 0) { + if (context.openAIKeyFromContext() === null) { return sendMessageToTelegramWithContext(context)("OpenAI API Key Not Set"); } if (!DATABASE) { diff --git a/dist/timestamp b/dist/timestamp index 6b60e5aa..41b007c1 100644 --- a/dist/timestamp +++ b/dist/timestamp @@ -1 +1 @@ -1682166538 +1682221130 diff --git a/src/context.js b/src/context.js index 33ec8d0d..d76cfd84 100644 --- a/src/context.js +++ b/src/context.js @@ -188,4 +188,22 @@ export class Context { await this._initUserConfig(this.SHARE_CONTEXT.configStoreKey); console.log(this.USER_CONFIG); } + + /** + * + * @return {string|null} + */ + openAIKeyFromContext() { + if (this.USER_CONFIG.OPENAI_API_KEY) { + return this.USER_CONFIG.OPENAI_API_KEY; + } + if (Array.isArray(ENV.API_KEY)) { + if (ENV.API_KEY.length === 0) { + return null; + } + return ENV.API_KEY[Math.floor(Math.random() * ENV.API_KEY.length)]; + } else { + return ENV.API_KEY; + } + } } diff --git a/src/i18n/en.js b/src/i18n/en.js index e28c36ec..067950bd 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -79,7 +79,7 @@ export default { 'command_error': (e) => `Command execution error: ${e.message}`, }, bill: { - 'bill_detail': (totalAmount, totalUsage, remaining) => `📊 Current robot usage\n\n\t- Amount: $${totalAmount || 0}\n\t- Usage: $${totalUsage || 0}\n\t- Remaining: $${remaining || 0}`, + 'bill_detail': (totalAmount, totalUsage, remaining) => `📊 This month usage\n\n\t- Amount: $${totalAmount || 0}\n\t- Usage: $${totalUsage || 0}\n\t- Remaining: $${remaining || 0}`, }, }, }; diff --git a/src/i18n/zh-hans.js b/src/i18n/zh-hans.js index f7eb088b..f1136cfd 100644 --- a/src/i18n/zh-hans.js +++ b/src/i18n/zh-hans.js @@ -79,7 +79,7 @@ export default { 'command_error': (e) => `命令执行错误: ${e.message}`, }, bill: { - 'bill_detail': (totalAmount, totalUsage, remaining) => `📊 当前机器人用量\n\n\t- 总额度: $${totalAmount || 0}\n\t- 已使用: $${totalUsage || 0}\n\t- 剩余额度: $${remaining || 0}`, + 'bill_detail': (totalAmount, totalUsage, remaining) => `📊 本月机器人用量\n\n\t- 总额度: $${totalAmount || 0}\n\t- 已使用: $${totalUsage || 0}\n\t- 剩余额度: $${remaining || 0}`, }, }, }; diff --git a/src/i18n/zh-hant.js b/src/i18n/zh-hant.js index 44305e40..b00cb3e7 100644 --- a/src/i18n/zh-hant.js +++ b/src/i18n/zh-hant.js @@ -79,7 +79,7 @@ export default { 'command_error': (e) => `命令執行出錯:${e.message}`, }, bill: { - 'bill_detail': (totalAmount, totalUsage, remaining) => `📊 当前机器人用量\n\n\t- 总额度: $${totalAmount || 0}\n\t- 已使用: $${totalUsage || 0}\n\t- 剩余额度: $${remaining || 0}`, + 'bill_detail': (totalAmount, totalUsage, remaining) => `📊 本月机器人用量\n\n\t- 总额度: $${totalAmount || 0}\n\t- 已使用: $${totalUsage || 0}\n\t- 剩余额度: $${remaining || 0}`, }, }, }; diff --git a/src/message.js b/src/message.js index 562d61cc..84bd83b9 100644 --- a/src/message.js +++ b/src/message.js @@ -77,7 +77,7 @@ async function msgIgnoreOldMessage(message, context) { * @return {Promise} */ async function msgCheckEnvIsReady(message, context) { - if (!ENV.API_KEY || ENV.API_KEY.length === 0) { + if (context.openAIKeyFromContext() === null) { return sendMessageToTelegramWithContext(context)('OpenAI API Key Not Set'); } if (!DATABASE) { diff --git a/src/openai.js b/src/openai.js index 7ca262d0..5bf3920a 100644 --- a/src/openai.js +++ b/src/openai.js @@ -3,23 +3,6 @@ import {Context} from './context.js'; import {DATABASE, ENV} from './env.js'; import {tokensCounter} from './utils.js'; - -/** - * - * @param {Context} context - * @return {string|null} - */ -function openAIKeyFromContext(context) { - if (context.USER_CONFIG.OPENAI_API_KEY) { - return context.USER_CONFIG.OPENAI_API_KEY; - } - if (Array.isArray(ENV.API_KEY)) { - return (ENV.API_KEY)[Math.floor(('0.'+Math.sin(new Date().getTime()).toString().substring(6)) * (ENV.API_KEY).length)]; - } else { - return ENV.API_KEY; - } -} - /** * 从流数据中提取内容 * @param {string} stream @@ -59,7 +42,7 @@ function extractContentFromStreamData(stream) { async function requestCompletionsFromOpenAI(message, history, context, onStream) { console.log(`requestCompletionsFromOpenAI: ${message}`); console.log(`history: ${JSON.stringify(history, null, 2)}`); - const key = openAIKeyFromContext(context); + const key = context.openAIKeyFromContext(); const body = { model: ENV.CHAT_MODEL, ...context.USER_CONFIG.OPENAI_API_EXTRA_PARAMS, @@ -118,7 +101,7 @@ async function requestCompletionsFromOpenAI(message, history, context, onStream) */ export async function requestImageFromOpenAI(prompt, context) { console.log(`requestImageFromOpenAI: ${prompt}`); - const key = openAIKeyFromContext(context); + const key = context.openAIKeyFromContext(); const body = { prompt: prompt, n: 1, @@ -145,44 +128,33 @@ export async function requestImageFromOpenAI(prompt, context) { * @return {Promise<{totalAmount,totalUsage,remaining,}>} */ export async function requestBill(context) { - // 计算起始日期和结束日期 - const now = new Date(); const apiUrl = ENV.OPENAI_API_DOMAIN; - const key = openAIKeyFromContext(context); - let startDate = new Date(now - 90 * 24 * 60 * 60 * 1000); - const endDate = new Date(now.getTime() + 24 * 60 * 60 * 1000); - const subDate = new Date(now); - subDate.setDate(1); - const formatDate = (date) => { - const year = date.getFullYear(); - const month = (date.getMonth() + 1).toString().padStart(2, '0'); - const day = date.getDate().toString().padStart(2, '0'); - - return `${year}-${month}-${day}`; - }; + const key = context.openAIKeyFromContext(); + + const date = new Date(); + const year = date.getFullYear(); + const month = (date.getMonth() + 1).toString().padStart(2, '0'); + const day = date.getDate().toString().padStart(2, '0'); + const endDate = `${year}-${month}-${day}`; + const startDate = `${year}-${month}-01`; - const urlSubscription = `${apiUrl}/v1/dashboard/billing/subscription`; - let urlUsage = `${apiUrl}/v1/dashboard/billing/usage?start_date=${formatDate(startDate)}&end_date=${formatDate(endDate)}`; + const urlSub = `${apiUrl}/v1/dashboard/billing/subscription`; + const urlUsage = `${apiUrl}/v1/dashboard/billing/usage?start_date=${startDate}&end_date=${endDate}`; const headers = { 'Authorization': 'Bearer ' + key, 'Content-Type': 'application/json', }; try { - let response = await fetch(urlSubscription, {headers}); - if (!response.ok) { - return {}; - } - const subscriptionData = await response.json(); + const subResp = await fetch(urlSub, {headers}); + const subscriptionData = await subResp.json(); const totalAmount = subscriptionData.hard_limit_usd; - if (totalAmount > 20) { - startDate = subDate; - } - urlUsage = `${apiUrl}/v1/dashboard/billing/usage?start_date=${formatDate(startDate)}&end_date=${formatDate(endDate)}`; - response = await fetch(urlUsage, {headers}); - const usageData = await response.json(); + + const usageResp = await fetch(urlUsage, {headers}); + const usageData = await usageResp.json(); const totalUsage = usageData.total_usage / 100; const remaining = totalAmount - totalUsage; + return { totalAmount: totalAmount.toFixed(2), totalUsage: totalUsage.toFixed(2),