open_ai_bot.py 5.9 KB

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