選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

131 行
5.2KB

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