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.

147 lines
5.8KB

  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. new_query = Session.build_session_query(query, from_user_id)
  28. logger.debug("[OPEN_AI] session query={}".format(new_query))
  29. # if context.get('stream'):
  30. # # reply in stream
  31. # return self.reply_text_stream(query, new_query, from_user_id)
  32. reply_content = self.reply_text(new_query, from_user_id, 0)
  33. logger.debug("[OPEN_AI] new_query={}, user={}, reply_cont={}".format(new_query, from_user_id, reply_content))
  34. if reply_content:
  35. Session.save_session(query, reply_content, from_user_id)
  36. return reply_content
  37. elif context.get('type', None) == 'IMAGE_CREATE':
  38. return self.create_img(query, 0)
  39. def reply_text(self, query, user_id, retry_count=0):
  40. try:
  41. response = openai.ChatCompletion.create(
  42. model="gpt-3.5-turbo", # 对话模型的名称
  43. messages=query,
  44. temperature=0.9, # 值在[0,1]之间,越大表示回复越具有不确定性
  45. #max_tokens=4096, # 回复最大的字符数
  46. top_p=1,
  47. frequency_penalty=0.0, # [-2,2]之间,该值越大则更倾向于产生不同的内容
  48. presence_penalty=0.0, # [-2,2]之间,该值越大则更倾向于产生不同的内容
  49. )
  50. # res_content = response.choices[0]['text'].strip().replace('<|endoftext|>', '')
  51. logger.info(response.choices[0]['message']['content'])
  52. # log.info("[OPEN_AI] reply={}".format(res_content))
  53. return response.choices[0]['message']['content']
  54. except openai.error.RateLimitError as e:
  55. # rate limit exception
  56. logger.warn(e)
  57. if retry_count < 1:
  58. time.sleep(5)
  59. logger.warn("[OPEN_AI] RateLimit exceed, 第{}次重试".format(retry_count+1))
  60. return self.reply_text(query, user_id, retry_count+1)
  61. else:
  62. return "提问太快啦,请休息一下再问我吧"
  63. except openai.error.APIConnectionError as e:
  64. # api connection exception
  65. logger.warn(e)
  66. logger.warn("[OPEN_AI] APIConnection failed")
  67. return "我连接不到你的网络"
  68. except openai.error.Timeout as e:
  69. logger.warn(e)
  70. logger.warn("[OPEN_AI] Timeout")
  71. return "我没有收到你的消息"
  72. except Exception as e:
  73. # unknown exception
  74. logger.exception(e)
  75. Session.clear_session(user_id)
  76. return "请再问我一次吧"
  77. def create_img(self, query, retry_count=0):
  78. try:
  79. logger.info("[OPEN_AI] image_query={}".format(query))
  80. response = openai.Image.create(
  81. prompt=query, #图片描述
  82. n=1, #每次生成图片的数量
  83. size="256x256" #图片大小,可选有 256x256, 512x512, 1024x1024
  84. )
  85. image_url = response['data'][0]['url']
  86. logger.info("[OPEN_AI] image_url={}".format(image_url))
  87. return image_url
  88. except openai.error.RateLimitError as e:
  89. logger.warn(e)
  90. if retry_count < 1:
  91. time.sleep(5)
  92. logger.warn("[OPEN_AI] ImgCreate RateLimit exceed, 第{}次重试".format(retry_count+1))
  93. return self.reply_text(query, retry_count+1)
  94. else:
  95. return "提问太快啦,请休息一下再问我吧"
  96. except Exception as e:
  97. logger.exception(e)
  98. return None
  99. class Session(object):
  100. @staticmethod
  101. def build_session_query(query, user_id):
  102. '''
  103. build query with conversation history
  104. e.g. [
  105. {"role": "system", "content": "You are a helpful assistant."},
  106. {"role": "user", "content": "Who won the world series in 2020?"},
  107. {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
  108. {"role": "user", "content": "Where was it played?"}
  109. ]
  110. :param query: query content
  111. :param user_id: from user id
  112. :return: query content with conversaction
  113. '''
  114. session = user_session.get(user_id, [])
  115. if len(session) == 0:
  116. system_prompt = conf().get("character_desc", "")
  117. system_item = {'role': 'system', 'content': system_prompt}
  118. session.append(system_item)
  119. user_session[user_id] = session
  120. user_item = {'role': 'user', 'content': query}
  121. session.append(user_item)
  122. return session
  123. @staticmethod
  124. def save_session(query, answer, user_id):
  125. session = user_session.get(user_id)
  126. if session:
  127. # append conversation
  128. gpt_item = {'role': 'assistant', 'content': answer}
  129. session.append(gpt_item)
  130. @staticmethod
  131. def clear_session(user_id):
  132. user_session[user_id] = []