From cf04d833f9843d51c94a225e259da623935dcdc0 Mon Sep 17 00:00:00 2001 From: Rock Chin <1010553892@qq.com> Date: Thu, 15 Dec 2022 23:48:51 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E6=9C=AA=E7=BB=8Fkeymgr=E5=AE=8C?= =?UTF-8?q?=E6=95=B4=E8=B7=9F=E8=B8=AA=E7=9A=84key=E8=B6=85=E9=A2=9D?= =?UTF-8?q?=E9=97=AE=E9=A2=98=20#39?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkg/openai/keymgr.py | 7 +++++++ pkg/qqbot/manager.py | 12 ++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/pkg/openai/keymgr.py b/pkg/openai/keymgr.py index 8163999c..e3a58034 100644 --- a/pkg/openai/keymgr.py +++ b/pkg/openai/keymgr.py @@ -91,6 +91,13 @@ class KeysManager: self.alerted.append(key_name) return False + # 设置当前使用的api-key使用量超限 + # 这是在尝试调用api时发生超限异常时调用的 + def set_current_exceeded(self): + md5 = hashlib.md5(self.using_key.encode('utf-8')).hexdigest() + self.usage[md5] = self.api_key_usage_threshold + self.dump_usage() + def dump_usage(self): pkg.database.manager.get_inst().dump_api_key_usage(api_keys=self.api_key, usage=self.usage) diff --git a/pkg/qqbot/manager.py b/pkg/qqbot/manager.py index e3511ada..ec7c2090 100644 --- a/pkg/qqbot/manager.py +++ b/pkg/qqbot/manager.py @@ -194,8 +194,16 @@ class QQBotManager: self.notify_admin("{}会话调用API失败:{}".format(session_name, e)) reply = "[bot]err:调用API失败,请重试或联系作者,或等待修复" except openai.error.RateLimitError as e: - self.notify_admin("API调用额度超限,请向OpenAI账户充值或在config.py中更换api_key") - reply = "[bot]err:API调用额度超额,请联系作者,或等待修复" + # 尝试切换api-key + pkg.openai.manager.get_inst().key_mgr.set_current_exceeded() + switched, name = pkg.openai.manager.get_inst().key_mgr.auto_switch() + + if not switched: + self.notify_admin("API调用额度超限,请向OpenAI账户充值或在config.py中更换api_key") + reply = "[bot]err:API调用额度超额,请联系作者,或等待修复" + else: + self.notify_admin("API调用额度超限,已切换到{}".format(name)) + reply = "[bot]err:API调用额度超额,已自动切换,请重新发送消息" except openai.error.InvalidRequestError as e: self.notify_admin("{}API调用参数错误:{}\n\n这可能是由于config.py中的prompt_submit_length参数或" "completion_api_params中的max_tokens参数数值过大导致的,请尝试将其降低".format(