You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

132 satır
5.3KB

  1. # encoding:utf-8
  2. from bot.bot import Bot
  3. from config import conf
  4. from common.log import logger
  5. import openai
  6. import time
  7. user_session = dict()
  8. # OpenAI对话模型API (可用)
  9. class ChatGPTBot(Bot):
  10. def __init__(self):
  11. openai.api_key = conf().get('open_ai_api_key')
  12. openai.proxy = conf().get('proxy')
  13. def reply(self, query, context=None):
  14. # acquire reply content
  15. if not context or not context.get('type') or context.get('type') == 'TEXT':
  16. logger.info("[OPEN_AI] query={}".format(query))
  17. from_user_id = context['from_user_id']
  18. if query == '#清除记忆':
  19. Session.clear_session(from_user_id)
  20. return '记忆已清除'
  21. new_query = Session.build_session_query(query, from_user_id)
  22. logger.debug("[OPEN_AI] session query={}".format(new_query))
  23. # if context.get('stream'):
  24. # # reply in stream
  25. # return self.reply_text_stream(query, new_query, from_user_id)
  26. reply_content = self.reply_text(new_query, from_user_id, 0)
  27. logger.debug("[OPEN_AI] new_query={}, user={}, reply_cont={}".format(new_query, from_user_id, reply_content))
  28. if reply_content:
  29. Session.save_session(query, reply_content, from_user_id)
  30. return reply_content
  31. elif context.get('type', None) == 'IMAGE_CREATE':
  32. return self.create_img(query, 0)
  33. def reply_text(self, query, user_id, retry_count=0):
  34. try:
  35. response = openai.ChatCompletion.create(
  36. model="gpt-3.5-turbo", # 对话模型的名称
  37. messages=query,
  38. temperature=0.9, # 值在[0,1]之间,越大表示回复越具有不确定性
  39. max_tokens=1200, # 回复最大的字符数
  40. top_p=1,
  41. frequency_penalty=0.0, # [-2,2]之间,该值越大则更倾向于产生不同的内容
  42. presence_penalty=0.0, # [-2,2]之间,该值越大则更倾向于产生不同的内容
  43. )
  44. # res_content = response.choices[0]['text'].strip().replace('<|endoftext|>', '')
  45. logger.info(response.choices[0]['message']['content'])
  46. # log.info("[OPEN_AI] reply={}".format(res_content))
  47. return response.choices[0]['message']['content']
  48. except openai.error.RateLimitError as e:
  49. # rate limit exception
  50. logger.warn(e)
  51. if retry_count < 1:
  52. time.sleep(5)
  53. logger.warn("[OPEN_AI] RateLimit exceed, 第{}次重试".format(retry_count+1))
  54. return self.reply_text(query, user_id, retry_count+1)
  55. else:
  56. return "提问太快啦,请休息一下再问我吧"
  57. except Exception as e:
  58. # unknown exception
  59. logger.exception(e)
  60. Session.clear_session(user_id)
  61. return "请再问我一次吧"
  62. def create_img(self, query, retry_count=0):
  63. try:
  64. logger.info("[OPEN_AI] image_query={}".format(query))
  65. response = openai.Image.create(
  66. prompt=query, #图片描述
  67. n=1, #每次生成图片的数量
  68. size="256x256" #图片大小,可选有 256x256, 512x512, 1024x1024
  69. )
  70. image_url = response['data'][0]['url']
  71. logger.info("[OPEN_AI] image_url={}".format(image_url))
  72. return image_url
  73. except openai.error.RateLimitError as e:
  74. logger.warn(e)
  75. if retry_count < 1:
  76. time.sleep(5)
  77. logger.warn("[OPEN_AI] ImgCreate RateLimit exceed, 第{}次重试".format(retry_count+1))
  78. return self.reply_text(query, retry_count+1)
  79. else:
  80. return "提问太快啦,请休息一下再问我吧"
  81. except Exception as e:
  82. logger.exception(e)
  83. return None
  84. class Session(object):
  85. @staticmethod
  86. def build_session_query(query, user_id):
  87. '''
  88. build query with conversation history
  89. e.g. [
  90. {"role": "system", "content": "You are a helpful assistant."},
  91. {"role": "user", "content": "Who won the world series in 2020?"},
  92. {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
  93. {"role": "user", "content": "Where was it played?"}
  94. ]
  95. :param query: query content
  96. :param user_id: from user id
  97. :return: query content with conversaction
  98. '''
  99. session = user_session.get(user_id, [])
  100. if len(session) == 0:
  101. system_prompt = conf().get("character_desc", "")
  102. system_item = {'role': 'system', 'content': system_prompt}
  103. session.append(system_item)
  104. user_session[user_id] = session
  105. user_item = {'role': 'user', 'content': query}
  106. session.append(user_item)
  107. return session
  108. @staticmethod
  109. def save_session(query, answer, user_id):
  110. session = user_session.get(user_id)
  111. if session:
  112. # append conversation
  113. gpt_item = {'role': 'assistant', 'content': answer}
  114. session.append(gpt_item)
  115. @staticmethod
  116. def clear_session(user_id):
  117. user_session[user_id] = []