Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

183 lignes
7.4KB

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