tanlie 1 year ago
parent
commit
0e739015b1

+ 4 - 4
bot/ali/ali_qwen_bot.py

@@ -115,22 +115,22 @@ class AliQwenBot(Bot):
         except Exception as e:
             need_retry = retry_count < 2
             result = {"completion_tokens": 0, "content": "我现在有点累了,等会再来吧"}
-            if isinstance(e, openai.error.RateLimitError):
+            if isinstance(e, openai.RateLimitError):
                 logger.warn("[QWEN] RateLimitError: {}".format(e))
                 result["content"] = "提问太快啦,请休息一下再问我吧"
                 if need_retry:
                     time.sleep(20)
-            elif isinstance(e, openai.error.Timeout):
+            elif isinstance(e, openai.Timeout):
                 logger.warn("[QWEN] Timeout: {}".format(e))
                 result["content"] = "我没有收到你的消息"
                 if need_retry:
                     time.sleep(5)
-            elif isinstance(e, openai.error.APIError):
+            elif isinstance(e, openai.APIError):
                 logger.warn("[QWEN] Bad Gateway: {}".format(e))
                 result["content"] = "请再问我一次"
                 if need_retry:
                     time.sleep(10)
-            elif isinstance(e, openai.error.APIConnectionError):
+            elif isinstance(e, openai.APIConnectionError):
                 logger.warn("[QWEN] APIConnectionError: {}".format(e))
                 need_retry = False
                 result["content"] = "我连接不到你的网络"

+ 19 - 16
bot/chatgpt/chat_gpt_bot.py

@@ -3,6 +3,10 @@
 import time
 
 import openai
+from openai import AzureOpenAI
+
+client = AzureOpenAI(api_key=conf().get("open_ai_api_key"),
+api_version=conf().get("azure_api_version", "2023-06-01-preview"))
 import openai.error
 import requests
 
@@ -22,12 +26,13 @@ class ChatGPTBot(Bot, OpenAIImage):
     def __init__(self):
         super().__init__()
         # set the default api_key
-        openai.api_key = conf().get("open_ai_api_key")
         if conf().get("open_ai_api_base"):
-            openai.api_base = conf().get("open_ai_api_base")
+            # TODO: The 'openai.api_base' option isn't read in the client API. You will need to pass it when you instantiate the client, e.g. 'OpenAI(base_url=conf().get("open_ai_api_base"))'
+            # openai.api_base = conf().get("open_ai_api_base")
         proxy = conf().get("proxy")
         if proxy:
-            openai.proxy = proxy
+            # TODO: The 'openai.proxy' option isn't read in the client API. You will need to pass it when you instantiate the client, e.g. 'OpenAI(proxy=proxy)'
+            # openai.proxy = proxy
         if conf().get("rate_limit_chatgpt"):
             self.tb4chatgpt = TokenBucket(conf().get("rate_limit_chatgpt", 20))
 
@@ -116,37 +121,37 @@ class ChatGPTBot(Bot, OpenAIImage):
         """
         try:
             if conf().get("rate_limit_chatgpt") and not self.tb4chatgpt.get_token():
-                raise openai.error.RateLimitError("RateLimitError: rate limit exceeded")
+                raise openai.RateLimitError("RateLimitError: rate limit exceeded")
             # if api_key == None, the default openai.api_key will be used
             if args is None:
                 args = self.args
-            response = openai.ChatCompletion.create(api_key=api_key, messages=session.messages, **args)
+            response = client.chat.completions.create(api_key=api_key, messages=session.messages, **args)
             # logger.debug("[CHATGPT] response={}".format(response))
             # logger.info("[ChatGPT] reply={}, total_tokens={}".format(response.choices[0]['message']['content'], response["usage"]["total_tokens"]))
             return {
-                "total_tokens": response["usage"]["total_tokens"],
-                "completion_tokens": response["usage"]["completion_tokens"],
-                "content": response.choices[0]["message"]["content"],
+                "total_tokens": response.usage.total_tokens,
+                "completion_tokens": response.usage.completion_tokens,
+                "content": response.choices[0].message.content,
             }
         except Exception as e:
             need_retry = retry_count < 2
             result = {"completion_tokens": 0, "content": "我现在有点累了,等会再来吧"}
-            if isinstance(e, openai.error.RateLimitError):
+            if isinstance(e, openai.RateLimitError):
                 logger.warn("[CHATGPT] RateLimitError: {}".format(e))
                 result["content"] = "提问太快啦,请休息一下再问我吧"
                 if need_retry:
                     time.sleep(20)
-            elif isinstance(e, openai.error.Timeout):
+            elif isinstance(e, openai.Timeout):
                 logger.warn("[CHATGPT] Timeout: {}".format(e))
                 result["content"] = "我没有收到你的消息"
                 if need_retry:
                     time.sleep(5)
-            elif isinstance(e, openai.error.APIError):
+            elif isinstance(e, openai.APIError):
                 logger.warn("[CHATGPT] Bad Gateway: {}".format(e))
                 result["content"] = "请再问我一次"
                 if need_retry:
                     time.sleep(10)
-            elif isinstance(e, openai.error.APIConnectionError):
+            elif isinstance(e, openai.APIConnectionError):
                 logger.warn("[CHATGPT] APIConnectionError: {}".format(e))
                 result["content"] = "我连接不到你的网络"
                 if need_retry:
@@ -166,8 +171,6 @@ class ChatGPTBot(Bot, OpenAIImage):
 class AzureChatGPTBot(ChatGPTBot):
     def __init__(self):
         super().__init__()
-        openai.api_type = "azure"
-        openai.api_version = conf().get("azure_api_version", "2023-06-01-preview")
         self.args["deployment_id"] = conf().get("azure_deployment_id")
 
     def create_img(self, query, retry_count=0, api_key=None):
@@ -186,8 +189,8 @@ class AzureChatGPTBot(ChatGPTBot):
                 logger.info("waiting for image create..., " + status + ",retry after " + retry_after + " seconds")
                 time.sleep(int(retry_after))
                 response = requests.get(operation_location, headers=headers)
-                status = response.json()["status"]
-            image_url = response.json()["result"]["contentUrl"]
+                status = response.json().status
+            image_url = response.json().result.contentUrl
             return True, image_url
         except Exception as e:
             logger.error("create image error: {}".format(e))

+ 7 - 6
bot/claudeapi/claude_api_bot.py

@@ -26,12 +26,13 @@ class ClaudeAPIBot(Bot, OpenAIImage):
         self.claudeClient = anthropic.Anthropic(
             api_key=conf().get("claude_api_key")
         )
-        openai.api_key = conf().get("open_ai_api_key")
         if conf().get("open_ai_api_base"):
-            openai.api_base = conf().get("open_ai_api_base")
+            # TODO: The 'openai.api_base' option isn't read in the client API. You will need to pass it when you instantiate the client, e.g. 'OpenAI(base_url=conf().get("open_ai_api_base"))'
+            # openai.api_base = conf().get("open_ai_api_base")
         proxy = conf().get("proxy")
         if proxy:
-            openai.proxy = proxy
+            # TODO: The 'openai.proxy' option isn't read in the client API. You will need to pass it when you instantiate the client, e.g. 'OpenAI(proxy=proxy)'
+            # openai.proxy = proxy
 
         self.sessions = SessionManager(ChatGPTSession, model=conf().get("model") or "text-davinci-003")
 
@@ -98,17 +99,17 @@ class ClaudeAPIBot(Bot, OpenAIImage):
         except Exception as e:
             need_retry = retry_count < 2
             result = {"completion_tokens": 0, "content": "我现在有点累了,等会再来吧"}
-            if isinstance(e, openai.error.RateLimitError):
+            if isinstance(e, openai.RateLimitError):
                 logger.warn("[CLAUDE_API] RateLimitError: {}".format(e))
                 result["content"] = "提问太快啦,请休息一下再问我吧"
                 if need_retry:
                     time.sleep(20)
-            elif isinstance(e, openai.error.Timeout):
+            elif isinstance(e, openai.Timeout):
                 logger.warn("[CLAUDE_API] Timeout: {}".format(e))
                 result["content"] = "我没有收到你的消息"
                 if need_retry:
                     time.sleep(5)
-            elif isinstance(e, openai.error.APIConnectionError):
+            elif isinstance(e, openai.APIConnectionError):
                 logger.warn("[CLAUDE_API] APIConnectionError: {}".format(e))
                 need_retry = False
                 result["content"] = "我连接不到你的网络"

+ 14 - 10
bot/openai/open_ai_bot.py

@@ -3,6 +3,9 @@
 import time
 
 import openai
+from openai import OpenAI
+
+client = OpenAI(api_key=conf().get("open_ai_api_key"))
 import openai.error
 
 from bot.bot import Bot
@@ -21,12 +24,13 @@ user_session = dict()
 class OpenAIBot(Bot, OpenAIImage):
     def __init__(self):
         super().__init__()
-        openai.api_key = conf().get("open_ai_api_key")
         if conf().get("open_ai_api_base"):
-            openai.api_base = conf().get("open_ai_api_base")
+            # TODO: The 'openai.api_base' option isn't read in the client API. You will need to pass it when you instantiate the client, e.g. 'OpenAI(base_url=conf().get("open_ai_api_base"))'
+            # openai.api_base = conf().get("open_ai_api_base")
         proxy = conf().get("proxy")
         if proxy:
-            openai.proxy = proxy
+            # TODO: The 'openai.proxy' option isn't read in the client API. You will need to pass it when you instantiate the client, e.g. 'OpenAI(proxy=proxy)'
+            # openai.proxy = proxy
 
         self.sessions = SessionManager(OpenAISession, model=conf().get("model") or "text-davinci-003")
         self.args = {
@@ -83,10 +87,10 @@ class OpenAIBot(Bot, OpenAIImage):
 
     def reply_text(self, session: OpenAISession, retry_count=0):
         try:
-            response = openai.Completion.create(prompt=str(session), **self.args)
-            res_content = response.choices[0]["text"].strip().replace("<|endoftext|>", "")
-            total_tokens = response["usage"]["total_tokens"]
-            completion_tokens = response["usage"]["completion_tokens"]
+            response = client.completions.create(prompt=str(session), **self.args)
+            res_content = response.choices[0].text.strip().replace("<|endoftext|>", "")
+            total_tokens = response.usage.total_tokens
+            completion_tokens = response.usage.completion_tokens
             logger.info("[OPEN_AI] reply={}".format(res_content))
             return {
                 "total_tokens": total_tokens,
@@ -96,17 +100,17 @@ class OpenAIBot(Bot, OpenAIImage):
         except Exception as e:
             need_retry = retry_count < 2
             result = {"completion_tokens": 0, "content": "我现在有点累了,等会再来吧"}
-            if isinstance(e, openai.error.RateLimitError):
+            if isinstance(e, openai.RateLimitError):
                 logger.warn("[OPEN_AI] RateLimitError: {}".format(e))
                 result["content"] = "提问太快啦,请休息一下再问我吧"
                 if need_retry:
                     time.sleep(20)
-            elif isinstance(e, openai.error.Timeout):
+            elif isinstance(e, openai.Timeout):
                 logger.warn("[OPEN_AI] Timeout: {}".format(e))
                 result["content"] = "我没有收到你的消息"
                 if need_retry:
                     time.sleep(5)
-            elif isinstance(e, openai.error.APIConnectionError):
+            elif isinstance(e, openai.APIConnectionError):
                 logger.warn("[OPEN_AI] APIConnectionError: {}".format(e))
                 need_retry = False
                 result["content"] = "我连接不到你的网络"

+ 9 - 10
bot/openai/open_ai_image.py

@@ -1,6 +1,9 @@
 import time
 
 import openai
+from openai import OpenAI
+
+client = OpenAI(api_key=conf().get("open_ai_api_key"))
 import openai.error
 
 from common.log import logger
@@ -11,7 +14,6 @@ from config import conf
 # OPENAI提供的画图接口
 class OpenAIImage(object):
     def __init__(self):
-        openai.api_key = conf().get("open_ai_api_key")
         if conf().get("rate_limit_dalle"):
             self.tb4dalle = TokenBucket(conf().get("rate_limit_dalle", 50))
 
@@ -20,17 +22,14 @@ class OpenAIImage(object):
             if conf().get("rate_limit_dalle") and not self.tb4dalle.get_token():
                 return False, "请求太快了,请休息一下再问我吧"
             logger.info("[OPEN_AI] image_query={}".format(query))
-            response = openai.Image.create(
-                api_key=api_key,
-                prompt=query,  # 图片描述
-                n=1,  # 每次生成图片的数量
-                model=conf().get("text_to_image") or "dall-e-2",
-                # size=conf().get("image_create_size", "256x256"),  # 图片大小,可选有 256x256, 512x512, 1024x1024
-            )
-            image_url = response["data"][0]["url"]
+            response = client.images.generate(api_key=api_key,
+            prompt=query,  # 图片描述
+            n=1,  # 每次生成图片的数量
+            model=conf().get("text_to_image") or "dall-e-2")
+            image_url = response.data[0].url
             logger.info("[OPEN_AI] image_url={}".format(image_url))
             return True, image_url
-        except openai.error.RateLimitError as e:
+        except openai.RateLimitError as e:
             logger.warn(e)
             if retry_count < 1:
                 time.sleep(5)

+ 4 - 4
bot/zhipuai/zhipuai_bot.py

@@ -117,22 +117,22 @@ class ZHIPUAIBot(Bot, ZhipuAIImage):
         except Exception as e:
             need_retry = retry_count < 2
             result = {"completion_tokens": 0, "content": "我现在有点累了,等会再来吧"}
-            if isinstance(e, openai.error.RateLimitError):
+            if isinstance(e, openai.RateLimitError):
                 logger.warn("[ZHIPU_AI] RateLimitError: {}".format(e))
                 result["content"] = "提问太快啦,请休息一下再问我吧"
                 if need_retry:
                     time.sleep(20)
-            elif isinstance(e, openai.error.Timeout):
+            elif isinstance(e, openai.Timeout):
                 logger.warn("[ZHIPU_AI] Timeout: {}".format(e))
                 result["content"] = "我没有收到你的消息"
                 if need_retry:
                     time.sleep(5)
-            elif isinstance(e, openai.error.APIError):
+            elif isinstance(e, openai.APIError):
                 logger.warn("[ZHIPU_AI] Bad Gateway: {}".format(e))
                 result["content"] = "请再问我一次"
                 if need_retry:
                     time.sleep(10)
-            elif isinstance(e, openai.error.APIConnectionError):
+            elif isinstance(e, openai.APIConnectionError):
                 logger.warn("[ZHIPU_AI] APIConnectionError: {}".format(e))
                 result["content"] = "我连接不到你的网络"
                 if need_retry:

+ 0 - 1
voice/openai/openai_voice.py

@@ -15,7 +15,6 @@ import datetime, random
 
 class OpenaiVoice(Voice):
     def __init__(self):
-        openai.api_key = conf().get("open_ai_api_key")
 
     def voiceToText(self, voice_file):
         logger.debug("[Openai] voice file name={}".format(voice_file))