Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

137 lines
5.8KB

  1. # encoding:utf-8
  2. import time
  3. import openai
  4. import openai.error
  5. from bot.bot import Bot
  6. from bot.openai.open_ai_image import OpenAIImage
  7. from bot.openai.open_ai_session import OpenAISession
  8. from bot.session_manager import SessionManager
  9. from bridge.context import ContextType
  10. from bridge.reply import Reply, ReplyType
  11. from common.log import logger
  12. from config import conf
  13. user_session = dict()
  14. # OpenAI对话模型API (可用)
  15. class OpenAIBot(Bot, OpenAIImage):
  16. def __init__(self):
  17. super().__init__()
  18. openai.api_key = conf().get("open_ai_api_key")
  19. if conf().get("open_ai_api_base"):
  20. openai.api_base = conf().get("open_ai_api_base")
  21. proxy = conf().get("proxy")
  22. if proxy:
  23. openai.proxy = proxy
  24. self.sessions = SessionManager(
  25. OpenAISession, model=conf().get("model") or "text-davinci-003"
  26. )
  27. self.args = {
  28. "model": conf().get("model") or "text-davinci-003", # 对话模型的名称
  29. "temperature": conf().get("temperature", 0.9), # 值在[0,1]之间,越大表示回复越具有不确定性
  30. "max_tokens": 1200, # 回复最大的字符数
  31. "top_p": 1,
  32. "frequency_penalty": conf().get(
  33. "frequency_penalty", 0.0
  34. ), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  35. "presence_penalty": conf().get(
  36. "presence_penalty", 0.0
  37. ), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  38. "request_timeout": conf().get(
  39. "request_timeout", None
  40. ), # 请求超时时间,openai接口默认设置为600,对于难问题一般需要较长时间
  41. "timeout": conf().get("request_timeout", None), # 重试超时时间,在这个时间内,将会自动重试
  42. "stop": ["\n\n\n"],
  43. }
  44. def reply(self, query, context=None):
  45. # acquire reply content
  46. if context and context.type:
  47. if context.type == ContextType.TEXT:
  48. logger.info("[OPEN_AI] query={}".format(query))
  49. session_id = context["session_id"]
  50. reply = None
  51. if query == "#清除记忆":
  52. self.sessions.clear_session(session_id)
  53. reply = Reply(ReplyType.INFO, "记忆已清除")
  54. elif query == "#清除所有":
  55. self.sessions.clear_all_session()
  56. reply = Reply(ReplyType.INFO, "所有人记忆已清除")
  57. else:
  58. session = self.sessions.session_query(query, session_id)
  59. result = self.reply_text(session)
  60. total_tokens, completion_tokens, reply_content = (
  61. result["total_tokens"],
  62. result["completion_tokens"],
  63. result["content"],
  64. )
  65. logger.debug(
  66. "[OPEN_AI] new_query={}, session_id={}, reply_cont={}, completion_tokens={}".format(
  67. str(session), session_id, reply_content, completion_tokens
  68. )
  69. )
  70. if total_tokens == 0:
  71. reply = Reply(ReplyType.ERROR, reply_content)
  72. else:
  73. self.sessions.session_reply(
  74. reply_content, session_id, total_tokens
  75. )
  76. reply = Reply(ReplyType.TEXT, reply_content)
  77. return reply
  78. elif context.type == ContextType.IMAGE_CREATE:
  79. ok, retstring = self.create_img(query, 0)
  80. reply = None
  81. if ok:
  82. reply = Reply(ReplyType.IMAGE_URL, retstring)
  83. else:
  84. reply = Reply(ReplyType.ERROR, retstring)
  85. return reply
  86. def reply_text(self, session: OpenAISession, retry_count=0):
  87. try:
  88. response = openai.Completion.create(prompt=str(session), **self.args)
  89. res_content = (
  90. response.choices[0]["text"].strip().replace("<|endoftext|>", "")
  91. )
  92. total_tokens = response["usage"]["total_tokens"]
  93. completion_tokens = response["usage"]["completion_tokens"]
  94. logger.info("[OPEN_AI] reply={}".format(res_content))
  95. return {
  96. "total_tokens": total_tokens,
  97. "completion_tokens": completion_tokens,
  98. "content": res_content,
  99. }
  100. except Exception as e:
  101. need_retry = retry_count < 2
  102. result = {"completion_tokens": 0, "content": "我现在有点累了,等会再来吧"}
  103. if isinstance(e, openai.error.RateLimitError):
  104. logger.warn("[OPEN_AI] RateLimitError: {}".format(e))
  105. result["content"] = "提问太快啦,请休息一下再问我吧"
  106. if need_retry:
  107. time.sleep(20)
  108. elif isinstance(e, openai.error.Timeout):
  109. logger.warn("[OPEN_AI] Timeout: {}".format(e))
  110. result["content"] = "我没有收到你的消息"
  111. if need_retry:
  112. time.sleep(5)
  113. elif isinstance(e, openai.error.APIConnectionError):
  114. logger.warn("[OPEN_AI] APIConnectionError: {}".format(e))
  115. need_retry = False
  116. result["content"] = "我连接不到你的网络"
  117. else:
  118. logger.warn("[OPEN_AI] Exception: {}".format(e))
  119. need_retry = False
  120. self.sessions.clear_session(session.session_id)
  121. if need_retry:
  122. logger.warn("[OPEN_AI] 第{}次重试".format(retry_count + 1))
  123. return self.reply_text(session, retry_count + 1)
  124. else:
  125. return result