mirror of
https://github.com/zhayujie/chatgpt-on-wechat.git
synced 2026-07-21 14:17:11 +08:00
feat: retry when timeout
This commit is contained in:
@@ -31,7 +31,7 @@ class ChatGPTBot(Bot,OpenAIImage):
|
|||||||
def reply(self, query, context=None):
|
def reply(self, query, context=None):
|
||||||
# acquire reply content
|
# acquire reply content
|
||||||
if context.type == ContextType.TEXT:
|
if context.type == ContextType.TEXT:
|
||||||
logger.info("[OPEN_AI] query={}".format(query))
|
logger.info("[CHATGPT] query={}".format(query))
|
||||||
|
|
||||||
session_id = context['session_id']
|
session_id = context['session_id']
|
||||||
reply = None
|
reply = None
|
||||||
@@ -48,14 +48,14 @@ class ChatGPTBot(Bot,OpenAIImage):
|
|||||||
if reply:
|
if reply:
|
||||||
return reply
|
return reply
|
||||||
session = self.sessions.session_query(query, session_id)
|
session = self.sessions.session_query(query, session_id)
|
||||||
logger.debug("[OPEN_AI] session query={}".format(session.messages))
|
logger.debug("[CHATGPT] session query={}".format(session.messages))
|
||||||
|
|
||||||
# if context.get('stream'):
|
# if context.get('stream'):
|
||||||
# # reply in stream
|
# # reply in stream
|
||||||
# return self.reply_text_stream(query, new_query, session_id)
|
# return self.reply_text_stream(query, new_query, session_id)
|
||||||
|
|
||||||
reply_content = self.reply_text(session, session_id, 0)
|
reply_content = self.reply_text(session, session_id, 0)
|
||||||
logger.debug("[OPEN_AI] new_query={}, session_id={}, reply_cont={}, completion_tokens={}".format(session.messages, session_id, reply_content["content"], reply_content["completion_tokens"]))
|
logger.debug("[CHATGPT] new_query={}, session_id={}, reply_cont={}, completion_tokens={}".format(session.messages, session_id, reply_content["content"], reply_content["completion_tokens"]))
|
||||||
if reply_content['completion_tokens'] == 0 and len(reply_content['content']) > 0:
|
if reply_content['completion_tokens'] == 0 and len(reply_content['content']) > 0:
|
||||||
reply = Reply(ReplyType.ERROR, reply_content['content'])
|
reply = Reply(ReplyType.ERROR, reply_content['content'])
|
||||||
elif reply_content["completion_tokens"] > 0:
|
elif reply_content["completion_tokens"] > 0:
|
||||||
@@ -63,7 +63,7 @@ class ChatGPTBot(Bot,OpenAIImage):
|
|||||||
reply = Reply(ReplyType.TEXT, reply_content["content"])
|
reply = Reply(ReplyType.TEXT, reply_content["content"])
|
||||||
else:
|
else:
|
||||||
reply = Reply(ReplyType.ERROR, reply_content['content'])
|
reply = Reply(ReplyType.ERROR, reply_content['content'])
|
||||||
logger.debug("[OPEN_AI] reply {} used 0 tokens.".format(reply_content))
|
logger.debug("[CHATGPT] reply {} used 0 tokens.".format(reply_content))
|
||||||
return reply
|
return reply
|
||||||
|
|
||||||
elif context.type == ContextType.IMAGE_CREATE:
|
elif context.type == ContextType.IMAGE_CREATE:
|
||||||
@@ -98,7 +98,7 @@ class ChatGPTBot(Bot,OpenAIImage):
|
|||||||
'''
|
'''
|
||||||
try:
|
try:
|
||||||
if conf().get('rate_limit_chatgpt') and not self.tb4chatgpt.get_token():
|
if conf().get('rate_limit_chatgpt') and not self.tb4chatgpt.get_token():
|
||||||
return {"completion_tokens": 0, "content": "提问太快啦,请休息一下再问我吧"}
|
raise openai.error.RateLimitError("RateLimitError: rate limit exceeded")
|
||||||
response = openai.ChatCompletion.create(
|
response = openai.ChatCompletion.create(
|
||||||
messages=session.messages, **self.compose_args()
|
messages=session.messages, **self.compose_args()
|
||||||
)
|
)
|
||||||
@@ -106,29 +106,33 @@ class ChatGPTBot(Bot,OpenAIImage):
|
|||||||
return {"total_tokens": response["usage"]["total_tokens"],
|
return {"total_tokens": response["usage"]["total_tokens"],
|
||||||
"completion_tokens": response["usage"]["completion_tokens"],
|
"completion_tokens": response["usage"]["completion_tokens"],
|
||||||
"content": response.choices[0]['message']['content']}
|
"content": response.choices[0]['message']['content']}
|
||||||
except openai.error.RateLimitError as e:
|
except Exception as e:
|
||||||
# rate limit exception
|
need_retry = retry_count < 2
|
||||||
logger.warn(e)
|
result = {"completion_tokens": 0, "content": "我现在有点累了,等会再来吧"}
|
||||||
if retry_count < 1:
|
if isinstance(e, openai.error.RateLimitError):
|
||||||
time.sleep(5)
|
logger.warn("[CHATGPT] RateLimitError: {}".format(e))
|
||||||
logger.warn("[OPEN_AI] RateLimit exceed, 第{}次重试".format(retry_count+1))
|
result['content'] = "提问太快啦,请休息一下再问我吧"
|
||||||
|
if need_retry:
|
||||||
|
time.sleep(5)
|
||||||
|
elif isinstance(e, openai.error.Timeout):
|
||||||
|
logger.warn("[CHATGPT] Timeout: {}".format(e))
|
||||||
|
result['content'] = "我没有收到你的消息"
|
||||||
|
if need_retry:
|
||||||
|
time.sleep(5)
|
||||||
|
elif isinstance(e, openai.error.APIConnectionError):
|
||||||
|
logger.warn("[CHATGPT] APIConnectionError: {}".format(e))
|
||||||
|
need_retry = False
|
||||||
|
result['content'] = "我连接不到你的网络"
|
||||||
|
else:
|
||||||
|
logger.warn("[CHATGPT] Exception: {}".format(e))
|
||||||
|
need_retry = False
|
||||||
|
self.sessions.clear_session(session_id)
|
||||||
|
|
||||||
|
if need_retry:
|
||||||
|
logger.warn("[CHATGPT] 第{}次重试".format(retry_count+1))
|
||||||
return self.reply_text(session, session_id, retry_count+1)
|
return self.reply_text(session, session_id, retry_count+1)
|
||||||
else:
|
else:
|
||||||
return {"completion_tokens": 0, "content": "提问太快啦,请休息一下再问我吧"}
|
return result
|
||||||
except openai.error.APIConnectionError as e:
|
|
||||||
# api connection exception
|
|
||||||
logger.warn(e)
|
|
||||||
logger.warn("[OPEN_AI] APIConnection failed")
|
|
||||||
return {"completion_tokens": 0, "content": "我连接不到你的网络"}
|
|
||||||
except openai.error.Timeout as e:
|
|
||||||
logger.warn(e)
|
|
||||||
logger.warn("[OPEN_AI] Timeout")
|
|
||||||
return {"completion_tokens": 0, "content": "我没有收到你的消息"}
|
|
||||||
except Exception as e:
|
|
||||||
# unknown exception
|
|
||||||
logger.exception(e)
|
|
||||||
self.sessions.clear_session(session_id)
|
|
||||||
return {"completion_tokens": 0, "content": "请再问我一次吧"}
|
|
||||||
|
|
||||||
|
|
||||||
class AzureChatGPTBot(ChatGPTBot):
|
class AzureChatGPTBot(ChatGPTBot):
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ class OpenAIBot(Bot, OpenAIImage):
|
|||||||
reply = Reply(ReplyType.ERROR, retstring)
|
reply = Reply(ReplyType.ERROR, retstring)
|
||||||
return reply
|
return reply
|
||||||
|
|
||||||
def reply_text(self, query, user_id, retry_count=0):
|
def reply_text(self, query, session_id, retry_count=0):
|
||||||
try:
|
try:
|
||||||
response = openai.Completion.create(
|
response = openai.Completion.create(
|
||||||
model= conf().get("model") or "text-davinci-003", # 对话模型的名称
|
model= conf().get("model") or "text-davinci-003", # 对话模型的名称
|
||||||
@@ -80,17 +80,30 @@ class OpenAIBot(Bot, OpenAIImage):
|
|||||||
completion_tokens = response["usage"]["completion_tokens"]
|
completion_tokens = response["usage"]["completion_tokens"]
|
||||||
logger.info("[OPEN_AI] reply={}".format(res_content))
|
logger.info("[OPEN_AI] reply={}".format(res_content))
|
||||||
return total_tokens, completion_tokens, res_content
|
return total_tokens, completion_tokens, res_content
|
||||||
except openai.error.RateLimitError as e:
|
|
||||||
# rate limit exception
|
|
||||||
logger.warn(e)
|
|
||||||
if retry_count < 1:
|
|
||||||
time.sleep(5)
|
|
||||||
logger.warn("[OPEN_AI] RateLimit exceed, 第{}次重试".format(retry_count+1))
|
|
||||||
return self.reply_text(query, user_id, retry_count+1)
|
|
||||||
else:
|
|
||||||
return 0,0, "提问太快啦,请休息一下再问我吧"
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# unknown exception
|
need_retry = retry_count < 2
|
||||||
logger.exception(e)
|
result = [0,0,"我现在有点累了,等会再来吧"]
|
||||||
self.sessions.clear_session(user_id)
|
if isinstance(e, openai.error.RateLimitError):
|
||||||
return 0,0, "请再问我一次吧"
|
logger.warn("[OPEN_AI] RateLimitError: {}".format(e))
|
||||||
|
result[2] = "提问太快啦,请休息一下再问我吧"
|
||||||
|
if need_retry:
|
||||||
|
time.sleep(5)
|
||||||
|
elif isinstance(e, openai.error.Timeout):
|
||||||
|
logger.warn("[OPEN_AI] Timeout: {}".format(e))
|
||||||
|
result[2] = "我没有收到你的消息"
|
||||||
|
if need_retry:
|
||||||
|
time.sleep(5)
|
||||||
|
elif isinstance(e, openai.error.APIConnectionError):
|
||||||
|
logger.warn("[OPEN_AI] APIConnectionError: {}".format(e))
|
||||||
|
need_retry = False
|
||||||
|
result[2] = "我连接不到你的网络"
|
||||||
|
else:
|
||||||
|
logger.warn("[OPEN_AI] Exception: {}".format(e))
|
||||||
|
need_retry = False
|
||||||
|
self.sessions.clear_session(session_id)
|
||||||
|
|
||||||
|
if need_retry:
|
||||||
|
logger.warn("[OPEN_AI] 第{}次重试".format(retry_count+1))
|
||||||
|
return self.reply_text(query, session_id, retry_count+1)
|
||||||
|
else:
|
||||||
|
return result
|
||||||
Reference in New Issue
Block a user