Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

204 lines
8.5KB

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