您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

open_ai_bot.py 6.3KB

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