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.

160 lines
5.8KB

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