Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

174 lines
6.8KB

  1. # encoding:utf-8
  2. from bot.bot import Bot
  3. from config import conf
  4. from common.log import logger
  5. from common.expired_dict import ExpiredDict
  6. import openai
  7. import time
  8. if conf().get('expires_in_seconds'):
  9. user_session = ExpiredDict(conf().get('expires_in_seconds'))
  10. else:
  11. user_session = dict()
  12. # OpenAI对话模型API (可用)
  13. class ChatGPTBot(Bot):
  14. def __init__(self):
  15. openai.api_key = conf().get('open_ai_api_key')
  16. openai.proxy = conf().get('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['from_user_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. # if context.get('stream'):
  31. # # reply in stream
  32. # return self.reply_text_stream(query, new_query, from_user_id)
  33. reply_content = self.reply_text(new_query, from_user_id, 0)
  34. logger.debug("[OPEN_AI] new_query={}, user={}, reply_cont={}".format(new_query, from_user_id, reply_content))
  35. if reply_content:
  36. Session.save_session(query, reply_content, from_user_id)
  37. return reply_content
  38. elif context.get('type', None) == 'IMAGE_CREATE':
  39. return self.create_img(query, 0)
  40. def reply_text(self, query, user_id, retry_count=0):
  41. try:
  42. response = openai.ChatCompletion.create(
  43. model="gpt-3.5-turbo", # 对话模型的名称
  44. messages=query,
  45. temperature=0.9, # 值在[0,1]之间,越大表示回复越具有不确定性
  46. #max_tokens=4096, # 回复最大的字符数
  47. top_p=1,
  48. frequency_penalty=0.0, # [-2,2]之间,该值越大则更倾向于产生不同的内容
  49. presence_penalty=0.0, # [-2,2]之间,该值越大则更倾向于产生不同的内容
  50. )
  51. # res_content = response.choices[0]['text'].strip().replace('<|endoftext|>', '')
  52. logger.info(response.choices[0]['message']['content'])
  53. # log.info("[OPEN_AI] reply={}".format(res_content))
  54. return response.choices[0]['message']['content']
  55. except openai.error.RateLimitError as e:
  56. # rate limit exception
  57. logger.warn(e)
  58. if retry_count < 1:
  59. time.sleep(5)
  60. logger.warn("[OPEN_AI] RateLimit exceed, 第{}次重试".format(retry_count+1))
  61. return self.reply_text(query, user_id, retry_count+1)
  62. else:
  63. return "提问太快啦,请休息一下再问我吧"
  64. except openai.error.APIConnectionError as e:
  65. # api connection exception
  66. logger.warn(e)
  67. logger.warn("[OPEN_AI] APIConnection failed")
  68. return "我连接不到你的网络"
  69. except openai.error.Timeout as e:
  70. logger.warn(e)
  71. logger.warn("[OPEN_AI] Timeout")
  72. return "我没有收到你的消息"
  73. except Exception as e:
  74. # unknown exception
  75. logger.exception(e)
  76. Session.clear_session(user_id)
  77. return "请再问我一次吧"
  78. def create_img(self, query, retry_count=0):
  79. try:
  80. logger.info("[OPEN_AI] image_query={}".format(query))
  81. response = openai.Image.create(
  82. prompt=query, #图片描述
  83. n=1, #每次生成图片的数量
  84. size="256x256" #图片大小,可选有 256x256, 512x512, 1024x1024
  85. )
  86. image_url = response['data'][0]['url']
  87. logger.info("[OPEN_AI] image_url={}".format(image_url))
  88. return image_url
  89. except openai.error.RateLimitError as e:
  90. logger.warn(e)
  91. if retry_count < 1:
  92. time.sleep(5)
  93. logger.warn("[OPEN_AI] ImgCreate RateLimit exceed, 第{}次重试".format(retry_count+1))
  94. return self.reply_text(query, retry_count+1)
  95. else:
  96. return "提问太快啦,请休息一下再问我吧"
  97. except Exception as e:
  98. logger.exception(e)
  99. return None
  100. class Session(object):
  101. @staticmethod
  102. def build_session_query(query, user_id):
  103. '''
  104. build query with conversation history
  105. e.g. [
  106. {"role": "system", "content": "You are a helpful assistant."},
  107. {"role": "user", "content": "Who won the world series in 2020?"},
  108. {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
  109. {"role": "user", "content": "Where was it played?"}
  110. ]
  111. :param query: query content
  112. :param user_id: from user id
  113. :return: query content with conversaction
  114. '''
  115. session = user_session.get(user_id, [])
  116. if len(session) == 0:
  117. system_prompt = conf().get("character_desc", "")
  118. system_item = {'role': 'system', 'content': system_prompt}
  119. session.append(system_item)
  120. user_session[user_id] = session
  121. user_item = {'role': 'user', 'content': query}
  122. session.append(user_item)
  123. return session
  124. @staticmethod
  125. def save_session(query, answer, user_id):
  126. max_tokens = conf().get("conversation_max_tokens")
  127. if not max_tokens:
  128. # default 3000
  129. max_tokens = 1000
  130. session = user_session.get(user_id)
  131. if session:
  132. # append conversation
  133. gpt_item = {'role': 'assistant', 'content': answer}
  134. session.append(gpt_item)
  135. # discard exceed limit conversation
  136. Session.discard_exceed_conversation(user_session[user_id], max_tokens)
  137. @staticmethod
  138. def discard_exceed_conversation(session, max_tokens):
  139. count = 0
  140. count_list = list()
  141. for i in range(len(session)-1, -1, -1):
  142. # count tokens of conversation list
  143. history_conv = session[i]
  144. tokens=history_conv.split()
  145. count += len(tokens)
  146. count_list.append(count)
  147. for c in count_list:
  148. if c > max_tokens:
  149. # pop first conversation
  150. session.pop(0)
  151. @staticmethod
  152. def clear_session(user_id):
  153. user_session[user_id] = []
  154. @staticmethod
  155. def clear_all_session():
  156. user_session.clear()