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

181 行
7.3KB

  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. # res_content = response.choices[0]['text'].strip().replace('<|endoftext|>', '')
  61. logger.info(response.choices[0]['message']['content'])
  62. return {"total_tokens": response["usage"]["total_tokens"],
  63. "completion_tokens": response["usage"]["completion_tokens"],
  64. "content": response.choices[0]['message']['content']}
  65. except openai.error.RateLimitError as e:
  66. # rate limit exception
  67. logger.warn(e)
  68. if retry_count < 1:
  69. time.sleep(5)
  70. logger.warn("[OPEN_AI] RateLimit exceed, 第{}次重试".format(retry_count+1))
  71. return self.reply_text(query, user_id, retry_count+1)
  72. else:
  73. return {"completion_tokens": 0, "content": "提问太快啦,请休息一下再问我吧"}
  74. except openai.error.APIConnectionError as e:
  75. # api connection exception
  76. logger.warn(e)
  77. logger.warn("[OPEN_AI] APIConnection failed")
  78. return {"completion_tokens": 0, "content":"我连接不到你的网络"}
  79. except openai.error.Timeout as e:
  80. logger.warn(e)
  81. logger.warn("[OPEN_AI] Timeout")
  82. return {"completion_tokens": 0, "content":"我没有收到你的消息"}
  83. except Exception as e:
  84. # unknown exception
  85. logger.exception(e)
  86. Session.clear_session(user_id)
  87. return {"completion_tokens": 0, "content": "请再问我一次吧"}
  88. def create_img(self, query, retry_count=0):
  89. try:
  90. logger.info("[OPEN_AI] image_query={}".format(query))
  91. response = openai.Image.create(
  92. prompt=query, #图片描述
  93. n=1, #每次生成图片的数量
  94. size="256x256" #图片大小,可选有 256x256, 512x512, 1024x1024
  95. )
  96. image_url = response['data'][0]['url']
  97. logger.info("[OPEN_AI] image_url={}".format(image_url))
  98. return image_url
  99. except openai.error.RateLimitError as e:
  100. logger.warn(e)
  101. if retry_count < 1:
  102. time.sleep(5)
  103. logger.warn("[OPEN_AI] ImgCreate RateLimit exceed, 第{}次重试".format(retry_count+1))
  104. return self.reply_text(query, retry_count+1)
  105. else:
  106. return "提问太快啦,请休息一下再问我吧"
  107. except Exception as e:
  108. logger.exception(e)
  109. return None
  110. class Session(object):
  111. @staticmethod
  112. def build_session_query(query, user_id):
  113. '''
  114. build query with conversation history
  115. e.g. [
  116. {"role": "system", "content": "You are a helpful assistant."},
  117. {"role": "user", "content": "Who won the world series in 2020?"},
  118. {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
  119. {"role": "user", "content": "Where was it played?"}
  120. ]
  121. :param query: query content
  122. :param user_id: from user id
  123. :return: query content with conversaction
  124. '''
  125. session = user_session.get(user_id, [])
  126. if len(session) == 0:
  127. system_prompt = conf().get("character_desc", "")
  128. system_item = {'role': 'system', 'content': system_prompt}
  129. session.append(system_item)
  130. user_session[user_id] = session
  131. user_item = {'role': 'user', 'content': query}
  132. session.append(user_item)
  133. return session
  134. @staticmethod
  135. def save_session(answer, user_id, total_tokens):
  136. max_tokens = conf().get("conversation_max_tokens")
  137. if not max_tokens:
  138. # default 3000
  139. max_tokens = 1000
  140. max_tokens=int(max_tokens)
  141. session = user_session.get(user_id)
  142. if session:
  143. # append conversation
  144. gpt_item = {'role': 'assistant', 'content': answer}
  145. session.append(gpt_item)
  146. # discard exceed limit conversation
  147. Session.discard_exceed_conversation(session, max_tokens, total_tokens)
  148. @staticmethod
  149. def discard_exceed_conversation(session, max_tokens, total_tokens):
  150. dec_tokens=int(total_tokens)
  151. # logger.info("prompt tokens used={},max_tokens={}".format(used_tokens,max_tokens))
  152. while dec_tokens > max_tokens:
  153. # pop first conversation
  154. if len(session) > 0:
  155. session.pop(0)
  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()