No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

222 líneas
9.6KB

  1. # encoding:utf-8
  2. from bot.bot import Bot
  3. from bridge.context import ContextType
  4. from bridge.reply import Reply, ReplyType
  5. from config import conf, load_config
  6. from common.log import logger
  7. from common.token_bucket import TokenBucket
  8. from common.expired_dict import ExpiredDict
  9. import openai
  10. import time
  11. # OpenAI对话模型API (可用)
  12. class ChatGPTBot(Bot):
  13. def __init__(self):
  14. openai.api_key = conf().get('open_ai_api_key')
  15. if conf().get('open_ai_api_base'):
  16. openai.api_base = conf().get('open_ai_api_base')
  17. proxy = conf().get('proxy')
  18. self.sessions = SessionManager()
  19. if proxy:
  20. openai.proxy = proxy
  21. if conf().get('rate_limit_chatgpt'):
  22. self.tb4chatgpt = TokenBucket(conf().get('rate_limit_chatgpt', 20))
  23. if conf().get('rate_limit_dalle'):
  24. self.tb4dalle = TokenBucket(conf().get('rate_limit_dalle', 50))
  25. def reply(self, query, context=None):
  26. # acquire reply content
  27. if context.type == ContextType.TEXT:
  28. logger.info("[OPEN_AI] query={}".format(query))
  29. session_id = context['session_id']
  30. reply = None
  31. clear_memory_commands = conf().get('clear_memory_commands', ['#清除记忆'])
  32. if query in clear_memory_commands:
  33. self.sessions.clear_session(session_id)
  34. reply = Reply(ReplyType.INFO, '记忆已清除')
  35. elif query == '#清除所有':
  36. self.sessions.clear_all_session()
  37. reply = Reply(ReplyType.INFO, '所有人记忆已清除')
  38. elif query == '#更新配置':
  39. load_config()
  40. reply = Reply(ReplyType.INFO, '配置已更新')
  41. if reply:
  42. return reply
  43. session = self.sessions.build_session_query(query, session_id)
  44. logger.debug("[OPEN_AI] session query={}".format(session))
  45. # if context.get('stream'):
  46. # # reply in stream
  47. # return self.reply_text_stream(query, new_query, session_id)
  48. reply_content = self.reply_text(session, session_id, 0)
  49. logger.debug("[OPEN_AI] new_query={}, session_id={}, reply_cont={}".format(session, session_id, reply_content["content"]))
  50. if reply_content['completion_tokens'] == 0 and len(reply_content['content']) > 0:
  51. reply = Reply(ReplyType.ERROR, reply_content['content'])
  52. elif reply_content["completion_tokens"] > 0:
  53. self.sessions.save_session(reply_content["content"], session_id, reply_content["total_tokens"])
  54. reply = Reply(ReplyType.TEXT, reply_content["content"])
  55. else:
  56. reply = Reply(ReplyType.ERROR, reply_content['content'])
  57. logger.debug("[OPEN_AI] reply {} used 0 tokens.".format(reply_content))
  58. return reply
  59. elif context.type == ContextType.IMAGE_CREATE:
  60. ok, retstring = self.create_img(query, 0)
  61. reply = None
  62. if ok:
  63. reply = Reply(ReplyType.IMAGE_URL, retstring)
  64. else:
  65. reply = Reply(ReplyType.ERROR, retstring)
  66. return reply
  67. else:
  68. reply = Reply(ReplyType.ERROR, 'Bot不支持处理{}类型的消息'.format(context.type))
  69. return reply
  70. def reply_text(self, session, session_id, retry_count=0) -> dict:
  71. '''
  72. call openai's ChatCompletion to get the answer
  73. :param session: a conversation session
  74. :param session_id: session id
  75. :param retry_count: retry count
  76. :return: {}
  77. '''
  78. try:
  79. if conf().get('rate_limit_chatgpt') and not self.tb4chatgpt.get_token():
  80. return {"completion_tokens": 0, "content": "提问太快啦,请休息一下再问我吧"}
  81. response = openai.ChatCompletion.create(
  82. model= conf().get("model") or "gpt-3.5-turbo", # 对话模型的名称
  83. messages=session,
  84. temperature=conf().get('temperature', 0.9), # 值在[0,1]之间,越大表示回复越具有不确定性
  85. #max_tokens=4096, # 回复最大的字符数
  86. top_p=1,
  87. frequency_penalty=conf().get('frequency_penalty', 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  88. presence_penalty=conf().get('presence_penalty', 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  89. )
  90. # logger.info("[ChatGPT] reply={}, total_tokens={}".format(response.choices[0]['message']['content'], response["usage"]["total_tokens"]))
  91. return {"total_tokens": response["usage"]["total_tokens"],
  92. "completion_tokens": response["usage"]["completion_tokens"],
  93. "content": response.choices[0]['message']['content']}
  94. except openai.error.RateLimitError as e:
  95. # rate limit exception
  96. logger.warn(e)
  97. if retry_count < 1:
  98. time.sleep(5)
  99. logger.warn("[OPEN_AI] RateLimit exceed, 第{}次重试".format(retry_count+1))
  100. return self.reply_text(session, session_id, retry_count+1)
  101. else:
  102. return {"completion_tokens": 0, "content": "提问太快啦,请休息一下再问我吧"}
  103. except openai.error.APIConnectionError as e:
  104. # api connection exception
  105. logger.warn(e)
  106. logger.warn("[OPEN_AI] APIConnection failed")
  107. return {"completion_tokens": 0, "content": "我连接不到你的网络"}
  108. except openai.error.Timeout as e:
  109. logger.warn(e)
  110. logger.warn("[OPEN_AI] Timeout")
  111. return {"completion_tokens": 0, "content": "我没有收到你的消息"}
  112. except Exception as e:
  113. # unknown exception
  114. logger.exception(e)
  115. self.sessions.clear_session(session_id)
  116. return {"completion_tokens": 0, "content": "请再问我一次吧"}
  117. def create_img(self, query, retry_count=0):
  118. try:
  119. if conf().get('rate_limit_dalle') and not self.tb4dalle.get_token():
  120. return "请求太快了,请休息一下再问我吧"
  121. logger.info("[OPEN_AI] image_query={}".format(query))
  122. response = openai.Image.create(
  123. prompt=query, #图片描述
  124. n=1, #每次生成图片的数量
  125. size="256x256" #图片大小,可选有 256x256, 512x512, 1024x1024
  126. )
  127. image_url = response['data'][0]['url']
  128. logger.info("[OPEN_AI] image_url={}".format(image_url))
  129. return True, image_url
  130. except openai.error.RateLimitError as e:
  131. logger.warn(e)
  132. if retry_count < 1:
  133. time.sleep(5)
  134. logger.warn("[OPEN_AI] ImgCreate RateLimit exceed, 第{}次重试".format(retry_count+1))
  135. return self.create_img(query, retry_count+1)
  136. else:
  137. return False, "提问太快啦,请休息一下再问我吧"
  138. except Exception as e:
  139. logger.exception(e)
  140. return False, str(e)
  141. class SessionManager(object):
  142. def __init__(self):
  143. if conf().get('expires_in_seconds'):
  144. sessions = ExpiredDict(conf().get('expires_in_seconds'))
  145. else:
  146. sessions = dict()
  147. self.sessions = sessions
  148. def build_session(self, session_id, system_prompt=None):
  149. session = self.sessions.get(session_id, [])
  150. if len(session) == 0:
  151. if system_prompt is None:
  152. system_prompt = conf().get("character_desc", "")
  153. system_item = {'role': 'system', 'content': system_prompt}
  154. session.append(system_item)
  155. self.sessions[session_id] = session
  156. return session
  157. def build_session_query(self, query, session_id):
  158. '''
  159. build query with conversation history
  160. e.g. [
  161. {"role": "system", "content": "You are a helpful assistant."},
  162. {"role": "user", "content": "Who won the world series in 2020?"},
  163. {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
  164. {"role": "user", "content": "Where was it played?"}
  165. ]
  166. :param query: query content
  167. :param session_id: session id
  168. :return: query content with conversaction
  169. '''
  170. session = self.build_session(session_id)
  171. user_item = {'role': 'user', 'content': query}
  172. session.append(user_item)
  173. return session
  174. def save_session(self, answer, session_id, total_tokens):
  175. max_tokens = conf().get("conversation_max_tokens")
  176. if not max_tokens:
  177. # default 3000
  178. max_tokens = 1000
  179. max_tokens = int(max_tokens)
  180. session = self.sessions.get(session_id)
  181. if session:
  182. # append conversation
  183. gpt_item = {'role': 'assistant', 'content': answer}
  184. session.append(gpt_item)
  185. # discard exceed limit conversation
  186. self.discard_exceed_conversation(session, max_tokens, total_tokens)
  187. def discard_exceed_conversation(self, session, max_tokens, total_tokens):
  188. dec_tokens = int(total_tokens)
  189. # logger.info("prompt tokens used={},max_tokens={}".format(used_tokens,max_tokens))
  190. while dec_tokens > max_tokens:
  191. # pop first conversation
  192. if len(session) > 3:
  193. session.pop(1)
  194. session.pop(1)
  195. else:
  196. break
  197. dec_tokens = dec_tokens - max_tokens
  198. def clear_session(self, session_id):
  199. self.sessions[session_id] = []
  200. def clear_all_session(self):
  201. self.sessions.clear()