Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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