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.

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