Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

198 linhas
8.5KB

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