選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

166 行
6.0KB

  1. # encoding:utf-8
  2. from bot.bot import Bot
  3. from config import conf
  4. from common.log import logger
  5. import openai
  6. import time
  7. user_session = dict()
  8. # OpenAI对话模型API (可用)
  9. class OpenAIBot(Bot):
  10. def __init__(self):
  11. openai.api_key = conf().get('open_ai_api_key')
  12. def reply(self, query, context=None):
  13. # acquire reply content
  14. if not context or not context.get('type') or context.get('type') == 'TEXT':
  15. logger.info("[OPEN_AI] query={}".format(query))
  16. from_user_id = context['from_user_id']
  17. if query == '#清除记忆':
  18. Session.clear_session(from_user_id)
  19. return '记忆已清除'
  20. elif query == '#清除所有':
  21. Session.clear_all_session()
  22. return '所有人记忆已清除'
  23. new_query = Session.build_session_query(query, from_user_id)
  24. logger.debug("[OPEN_AI] session query={}".format(new_query))
  25. reply_content = self.reply_text(new_query, from_user_id, 0)
  26. logger.debug("[OPEN_AI] new_query={}, user={}, reply_cont={}".format(new_query, from_user_id, reply_content))
  27. if reply_content and query:
  28. Session.save_session(query, reply_content, from_user_id)
  29. return reply_content
  30. elif context.get('type', None) == 'IMAGE_CREATE':
  31. return self.create_img(query, 0)
  32. def reply_text(self, query, user_id, retry_count=0):
  33. try:
  34. response = openai.Completion.create(
  35. model="text-davinci-003", # 对话模型的名称
  36. prompt=query,
  37. temperature=0.9, # 值在[0,1]之间,越大表示回复越具有不确定性
  38. max_tokens=1200, # 回复最大的字符数
  39. top_p=1,
  40. frequency_penalty=0.0, # [-2,2]之间,该值越大则更倾向于产生不同的内容
  41. presence_penalty=0.0, # [-2,2]之间,该值越大则更倾向于产生不同的内容
  42. stop=["\n\n\n"]
  43. )
  44. res_content = response.choices[0]['text'].strip().replace('<|endoftext|>', '')
  45. logger.info("[OPEN_AI] reply={}".format(res_content))
  46. return res_content
  47. except openai.error.RateLimitError as e:
  48. # rate limit exception
  49. logger.warn(e)
  50. if retry_count < 1:
  51. time.sleep(5)
  52. logger.warn("[OPEN_AI] RateLimit exceed, 第{}次重试".format(retry_count+1))
  53. return self.reply_text(query, user_id, retry_count+1)
  54. else:
  55. return "提问太快啦,请休息一下再问我吧"
  56. except Exception as e:
  57. # unknown exception
  58. logger.exception(e)
  59. Session.clear_session(user_id)
  60. return "请再问我一次吧"
  61. def create_img(self, query, retry_count=0):
  62. try:
  63. logger.info("[OPEN_AI] image_query={}".format(query))
  64. response = openai.Image.create(
  65. prompt=query, #图片描述
  66. n=1, #每次生成图片的数量
  67. size="256x256" #图片大小,可选有 256x256, 512x512, 1024x1024
  68. )
  69. image_url = response['data'][0]['url']
  70. logger.info("[OPEN_AI] image_url={}".format(image_url))
  71. return image_url
  72. except openai.error.RateLimitError as e:
  73. logger.warn(e)
  74. if retry_count < 1:
  75. time.sleep(5)
  76. logger.warn("[OPEN_AI] ImgCreate RateLimit exceed, 第{}次重试".format(retry_count+1))
  77. return self.reply_text(query, retry_count+1)
  78. else:
  79. return "提问太快啦,请休息一下再问我吧"
  80. except Exception as e:
  81. logger.exception(e)
  82. return None
  83. class Session(object):
  84. @staticmethod
  85. def build_session_query(query, user_id):
  86. '''
  87. build query with conversation history
  88. e.g. Q: xxx
  89. A: xxx
  90. Q: xxx
  91. :param query: query content
  92. :param user_id: from user id
  93. :return: query content with conversaction
  94. '''
  95. prompt = conf().get("character_desc", "")
  96. if prompt:
  97. prompt += "<|endoftext|>\n\n\n"
  98. session = user_session.get(user_id, None)
  99. if session:
  100. for conversation in session:
  101. prompt += "Q: " + conversation["question"] + "\n\n\nA: " + conversation["answer"] + "<|endoftext|>\n"
  102. prompt += "Q: " + query + "\nA: "
  103. return prompt
  104. else:
  105. return prompt + "Q: " + query + "\nA: "
  106. @staticmethod
  107. def save_session(query, answer, user_id):
  108. max_tokens = conf().get("conversation_max_tokens")
  109. if not max_tokens:
  110. # default 3000
  111. max_tokens = 1000
  112. conversation = dict()
  113. conversation["question"] = query
  114. conversation["answer"] = answer
  115. session = user_session.get(user_id)
  116. logger.debug(conversation)
  117. logger.debug(session)
  118. if session:
  119. # append conversation
  120. session.append(conversation)
  121. else:
  122. # create session
  123. queue = list()
  124. queue.append(conversation)
  125. user_session[user_id] = queue
  126. # discard exceed limit conversation
  127. Session.discard_exceed_conversation(user_session[user_id], max_tokens)
  128. @staticmethod
  129. def discard_exceed_conversation(session, max_tokens):
  130. count = 0
  131. count_list = list()
  132. for i in range(len(session)-1, -1, -1):
  133. # count tokens of conversation list
  134. history_conv = session[i]
  135. count += len(history_conv["question"]) + len(history_conv["answer"])
  136. count_list.append(count)
  137. for c in count_list:
  138. if c > max_tokens:
  139. # pop first conversation
  140. session.pop(0)
  141. @staticmethod
  142. def clear_session(user_id):
  143. user_session[user_id] = []
  144. @staticmethod
  145. def clear_all_session():
  146. user_session.clear()