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.

239 lines
11KB

  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, pconf
  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. agent_suffix = self._fetch_agent_suffix(response)
  87. if agent_suffix:
  88. reply_content += agent_suffix
  89. if not agent_suffix:
  90. knowledge_suffix = self._fetch_knowledge_search_suffix(response)
  91. if knowledge_suffix:
  92. reply_content += knowledge_suffix
  93. return Reply(ReplyType.TEXT, reply_content)
  94. else:
  95. response = res.json()
  96. error = response.get("error")
  97. logger.error(f"[LINKAI] chat failed, status_code={res.status_code}, "
  98. f"msg={error.get('message')}, type={error.get('type')}")
  99. if res.status_code >= 500:
  100. # server error, need 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. return Reply(ReplyType.ERROR, "提问太快啦,请休息一下再问我吧")
  105. except Exception as e:
  106. logger.exception(e)
  107. # retry
  108. time.sleep(2)
  109. logger.warn(f"[LINKAI] do retry, times={retry_count}")
  110. return self._chat(query, context, retry_count + 1)
  111. def reply_text(self, session: ChatGPTSession, app_code="", retry_count=0) -> dict:
  112. if retry_count >= 2:
  113. # exit from retry 2 times
  114. logger.warn("[LINKAI] failed after maximum number of retry times")
  115. return {
  116. "total_tokens": 0,
  117. "completion_tokens": 0,
  118. "content": "请再问我一次吧"
  119. }
  120. try:
  121. body = {
  122. "app_code": app_code,
  123. "messages": session.messages,
  124. "model": conf().get("model") or "gpt-3.5-turbo", # 对话模型的名称, 支持 gpt-3.5-turbo, gpt-3.5-turbo-16k, gpt-4, wenxin, xunfei
  125. "temperature": conf().get("temperature"),
  126. "top_p": conf().get("top_p", 1),
  127. "frequency_penalty": conf().get("frequency_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  128. "presence_penalty": conf().get("presence_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  129. }
  130. if self.args.get("max_tokens"):
  131. body["max_tokens"] = self.args.get("max_tokens")
  132. headers = {"Authorization": "Bearer " + conf().get("linkai_api_key")}
  133. # do http request
  134. base_url = conf().get("linkai_api_base", "https://api.link-ai.chat")
  135. res = requests.post(url=base_url + "/v1/chat/completions", json=body, headers=headers,
  136. timeout=conf().get("request_timeout", 180))
  137. if res.status_code == 200:
  138. # execute success
  139. response = res.json()
  140. reply_content = response["choices"][0]["message"]["content"]
  141. total_tokens = response["usage"]["total_tokens"]
  142. logger.info(f"[LINKAI] reply={reply_content}, total_tokens={total_tokens}")
  143. return {
  144. "total_tokens": total_tokens,
  145. "completion_tokens": response["usage"]["completion_tokens"],
  146. "content": reply_content,
  147. }
  148. else:
  149. response = res.json()
  150. error = response.get("error")
  151. logger.error(f"[LINKAI] chat failed, status_code={res.status_code}, "
  152. f"msg={error.get('message')}, type={error.get('type')}")
  153. if res.status_code >= 500:
  154. # server error, need retry
  155. time.sleep(2)
  156. logger.warn(f"[LINKAI] do retry, times={retry_count}")
  157. return self.reply_text(session, app_code, retry_count + 1)
  158. return {
  159. "total_tokens": 0,
  160. "completion_tokens": 0,
  161. "content": "提问太快啦,请休息一下再问我吧"
  162. }
  163. except Exception as e:
  164. logger.exception(e)
  165. # retry
  166. time.sleep(2)
  167. logger.warn(f"[LINKAI] do retry, times={retry_count}")
  168. return self.reply_text(session, app_code, retry_count + 1)
  169. def _fetch_knowledge_search_suffix(self, response) -> str:
  170. try:
  171. if response.get("knowledge_base"):
  172. search_hit = response.get("knowledge_base").get("search_hit")
  173. first_similarity = response.get("knowledge_base").get("first_similarity")
  174. logger.info(f"[LINKAI] knowledge base, search_hit={search_hit}, first_similarity={first_similarity}")
  175. plugin_config = pconf("linkai")
  176. if plugin_config and plugin_config.get("knowledge_base") and plugin_config.get("knowledge_base").get("search_miss_text_enabled"):
  177. search_miss_similarity = plugin_config.get("knowledge_base").get("search_miss_similarity")
  178. search_miss_text = plugin_config.get("knowledge_base").get("search_miss_suffix")
  179. if not search_hit:
  180. return search_miss_text
  181. if search_miss_similarity and float(search_miss_similarity) > first_similarity:
  182. return search_miss_text
  183. except Exception as e:
  184. logger.exception(e)
  185. def _fetch_agent_suffix(self, response):
  186. try:
  187. plugin_list = []
  188. logger.debug(f"[LinkAgent] res={response}")
  189. if response.get("agent") and response.get("agent").get("chain") and response.get("agent").get("need_show_plugin"):
  190. chain = response.get("agent").get("chain")
  191. suffix = "\n\n- - - - - - - - - - - -"
  192. i = 0
  193. for turn in chain:
  194. plugin_name = turn.get('plugin_name')
  195. suffix += "\n"
  196. need_show_thought = response.get("agent").get("need_show_thought")
  197. if turn.get("thought") and plugin_name and need_show_thought:
  198. suffix += f"{turn.get('thought')}\n"
  199. if plugin_name:
  200. plugin_list.append(turn.get('plugin_name'))
  201. suffix += f"{turn.get('plugin_icon')} {turn.get('plugin_name')}"
  202. if turn.get('plugin_input'):
  203. suffix += f":{turn.get('plugin_input')}"
  204. if i < len(chain) - 1:
  205. suffix += "\n"
  206. i += 1
  207. logger.info(f"[LinkAgent] use plugins: {plugin_list}")
  208. return suffix
  209. except Exception as e:
  210. logger.exception(e)