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.

186 lines
8.1KB

  1. # access LinkAI knowledge base platform
  2. # docs: https://link-ai.tech/platform/link-app/wechat
  3. import time
  4. import requests
  5. from bot.bot import Bot
  6. from bot.chatgpt.chat_gpt_session import ChatGPTSession
  7. from bot.openai.open_ai_image import OpenAIImage
  8. from bot.session_manager import SessionManager
  9. from bridge.context import Context, ContextType
  10. from bridge.reply import Reply, ReplyType
  11. from common.log import logger
  12. from config import conf
  13. class LinkAIBot(Bot, OpenAIImage):
  14. # authentication failed
  15. AUTH_FAILED_CODE = 401
  16. NO_QUOTA_CODE = 406
  17. def __init__(self):
  18. super().__init__()
  19. self.sessions = SessionManager(ChatGPTSession, model=conf().get("model") or "gpt-3.5-turbo")
  20. self.args = {}
  21. def reply(self, query, context: Context = None) -> Reply:
  22. if context.type == ContextType.TEXT:
  23. return self._chat(query, context)
  24. elif context.type == ContextType.IMAGE_CREATE:
  25. ok, res = self.create_img(query, 0)
  26. if ok:
  27. reply = Reply(ReplyType.IMAGE_URL, res)
  28. else:
  29. reply = Reply(ReplyType.ERROR, res)
  30. return reply
  31. else:
  32. reply = Reply(ReplyType.ERROR, "Bot不支持处理{}类型的消息".format(context.type))
  33. return reply
  34. def _chat(self, query, context, retry_count=0) -> Reply:
  35. """
  36. 发起对话请求
  37. :param query: 请求提示词
  38. :param context: 对话上下文
  39. :param retry_count: 当前递归重试次数
  40. :return: 回复
  41. """
  42. if retry_count >= 2:
  43. # exit from retry 2 times
  44. logger.warn("[LINKAI] failed after maximum number of retry times")
  45. return Reply(ReplyType.ERROR, "请再问我一次吧")
  46. try:
  47. # load config
  48. if context.get("generate_breaked_by"):
  49. logger.info(f"[LINKAI] won't set appcode because a plugin ({context['generate_breaked_by']}) affected the context")
  50. app_code = None
  51. else:
  52. app_code = context.kwargs.get("app_code") or conf().get("linkai_app_code")
  53. linkai_api_key = conf().get("linkai_api_key")
  54. session_id = context["session_id"]
  55. session = self.sessions.session_query(query, session_id)
  56. model = conf().get("model") or "gpt-3.5-turbo"
  57. # remove system message
  58. if session.messages[0].get("role") == "system":
  59. if app_code or model == "wenxin":
  60. session.messages.pop(0)
  61. body = {
  62. "app_code": app_code,
  63. "messages": session.messages,
  64. "model": model, # 对话模型的名称, 支持 gpt-3.5-turbo, gpt-3.5-turbo-16k, gpt-4, wenxin, xunfei
  65. "temperature": conf().get("temperature"),
  66. "top_p": conf().get("top_p", 1),
  67. "frequency_penalty": conf().get("frequency_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  68. "presence_penalty": conf().get("presence_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  69. }
  70. file_id = context.kwargs.get("file_id")
  71. if file_id:
  72. body["file_id"] = file_id
  73. logger.info(f"[LINKAI] query={query}, app_code={app_code}, mode={body.get('model')}, file_id={file_id}")
  74. headers = {"Authorization": "Bearer " + linkai_api_key}
  75. # do http request
  76. base_url = conf().get("linkai_api_base", "https://api.link-ai.chat")
  77. res = requests.post(url=base_url + "/v1/chat/completions", json=body, headers=headers,
  78. timeout=conf().get("request_timeout", 180))
  79. if res.status_code == 200:
  80. # execute success
  81. response = res.json()
  82. reply_content = response["choices"][0]["message"]["content"]
  83. total_tokens = response["usage"]["total_tokens"]
  84. logger.info(f"[LINKAI] reply={reply_content}, total_tokens={total_tokens}")
  85. self.sessions.session_reply(reply_content, session_id, total_tokens)
  86. return Reply(ReplyType.TEXT, reply_content)
  87. else:
  88. response = res.json()
  89. error = response.get("error")
  90. logger.error(f"[LINKAI] chat failed, status_code={res.status_code}, "
  91. f"msg={error.get('message')}, type={error.get('type')}")
  92. if res.status_code >= 500:
  93. # server error, need retry
  94. time.sleep(2)
  95. logger.warn(f"[LINKAI] do retry, times={retry_count}")
  96. return self._chat(query, context, retry_count + 1)
  97. return Reply(ReplyType.ERROR, "提问太快啦,请休息一下再问我吧")
  98. except Exception as e:
  99. logger.exception(e)
  100. # retry
  101. time.sleep(2)
  102. logger.warn(f"[LINKAI] do retry, times={retry_count}")
  103. return self._chat(query, context, retry_count + 1)
  104. def reply_text(self, session: ChatGPTSession, app_code="", retry_count=0) -> dict:
  105. if retry_count >= 2:
  106. # exit from retry 2 times
  107. logger.warn("[LINKAI] failed after maximum number of retry times")
  108. return {
  109. "total_tokens": 0,
  110. "completion_tokens": 0,
  111. "content": "请再问我一次吧"
  112. }
  113. try:
  114. body = {
  115. "app_code": app_code,
  116. "messages": session.messages,
  117. "model": conf().get("model") or "gpt-3.5-turbo", # 对话模型的名称, 支持 gpt-3.5-turbo, gpt-3.5-turbo-16k, gpt-4, wenxin, xunfei
  118. "temperature": conf().get("temperature"),
  119. "top_p": conf().get("top_p", 1),
  120. "frequency_penalty": conf().get("frequency_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  121. "presence_penalty": conf().get("presence_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  122. }
  123. if self.args.get("max_tokens"):
  124. body["max_tokens"] = self.args.get("max_tokens")
  125. headers = {"Authorization": "Bearer " + conf().get("linkai_api_key")}
  126. # do http request
  127. base_url = conf().get("linkai_api_base", "https://api.link-ai.chat")
  128. res = requests.post(url=base_url + "/v1/chat/completions", json=body, headers=headers,
  129. timeout=conf().get("request_timeout", 180))
  130. if res.status_code == 200:
  131. # execute success
  132. response = res.json()
  133. reply_content = response["choices"][0]["message"]["content"]
  134. total_tokens = response["usage"]["total_tokens"]
  135. logger.info(f"[LINKAI] reply={reply_content}, total_tokens={total_tokens}")
  136. return {
  137. "total_tokens": total_tokens,
  138. "completion_tokens": response["usage"]["completion_tokens"],
  139. "content": reply_content,
  140. }
  141. else:
  142. response = res.json()
  143. error = response.get("error")
  144. logger.error(f"[LINKAI] chat failed, status_code={res.status_code}, "
  145. f"msg={error.get('message')}, type={error.get('type')}")
  146. if res.status_code >= 500:
  147. # server error, need retry
  148. time.sleep(2)
  149. logger.warn(f"[LINKAI] do retry, times={retry_count}")
  150. return self.reply_text(session, app_code, retry_count + 1)
  151. return {
  152. "total_tokens": 0,
  153. "completion_tokens": 0,
  154. "content": "提问太快啦,请休息一下再问我吧"
  155. }
  156. except Exception as e:
  157. logger.exception(e)
  158. # retry
  159. time.sleep(2)
  160. logger.warn(f"[LINKAI] do retry, times={retry_count}")
  161. return self.reply_text(session, app_code, retry_count + 1)