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.

421 lines
19KB

  1. # access LinkAI knowledge base platform
  2. # docs: https://link-ai.tech/platform/link-app/wechat
  3. import time
  4. import requests
  5. import config
  6. from bot.bot import Bot
  7. from bot.chatgpt.chat_gpt_session import ChatGPTSession
  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. import threading
  14. from common import memory, utils
  15. import base64
  16. class LinkAIBot(Bot):
  17. # authentication failed
  18. AUTH_FAILED_CODE = 401
  19. NO_QUOTA_CODE = 406
  20. def __init__(self):
  21. super().__init__()
  22. self.sessions = LinkAISessionManager(LinkAISession, model=conf().get("model") or "gpt-3.5-turbo")
  23. self.args = {}
  24. def reply(self, query, context: Context = None) -> Reply:
  25. if context.type == ContextType.TEXT:
  26. return self._chat(query, context)
  27. elif context.type == ContextType.IMAGE_CREATE:
  28. if not conf().get("text_to_image"):
  29. logger.warn("[LinkAI] text_to_image is not enabled, ignore the IMAGE_CREATE request")
  30. return Reply(ReplyType.TEXT, "")
  31. ok, res = self.create_img(query, 0)
  32. if ok:
  33. reply = Reply(ReplyType.IMAGE_URL, res)
  34. else:
  35. reply = Reply(ReplyType.ERROR, res)
  36. return reply
  37. else:
  38. reply = Reply(ReplyType.ERROR, "Bot不支持处理{}类型的消息".format(context.type))
  39. return reply
  40. def _chat(self, query, context, retry_count=0) -> Reply:
  41. """
  42. 发起对话请求
  43. :param query: 请求提示词
  44. :param context: 对话上下文
  45. :param retry_count: 当前递归重试次数
  46. :return: 回复
  47. """
  48. if retry_count > 2:
  49. # exit from retry 2 times
  50. logger.warn("[LINKAI] failed after maximum number of retry times")
  51. return Reply(ReplyType.TEXT, "请再问我一次吧")
  52. try:
  53. # load config
  54. if context.get("generate_breaked_by"):
  55. logger.info(f"[LINKAI] won't set appcode because a plugin ({context['generate_breaked_by']}) affected the context")
  56. app_code = None
  57. else:
  58. plugin_app_code = self._find_group_mapping_code(context)
  59. app_code = context.kwargs.get("app_code") or plugin_app_code or conf().get("linkai_app_code")
  60. linkai_api_key = conf().get("linkai_api_key")
  61. session_id = context["session_id"]
  62. session_message = self.sessions.session_msg_query(query, session_id)
  63. logger.debug(f"[LinkAI] session={session_message}, session_id={session_id}")
  64. # image process
  65. img_cache = memory.USER_IMAGE_CACHE.get(session_id)
  66. if img_cache:
  67. messages = self._process_image_msg(app_code=app_code, session_id=session_id, query=query, img_cache=img_cache)
  68. if messages:
  69. session_message = messages
  70. model = conf().get("model")
  71. # remove system message
  72. if session_message[0].get("role") == "system":
  73. if app_code or model == "wenxin":
  74. session_message.pop(0)
  75. body = {
  76. "app_code": app_code,
  77. "messages": session_message,
  78. "model": model, # 对话模型的名称, 支持 gpt-3.5-turbo, gpt-3.5-turbo-16k, gpt-4, wenxin, xunfei
  79. "temperature": conf().get("temperature"),
  80. "top_p": conf().get("top_p", 1),
  81. "frequency_penalty": conf().get("frequency_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  82. "presence_penalty": conf().get("presence_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  83. "session_id": session_id,
  84. "channel_type": conf().get("channel_type")
  85. }
  86. try:
  87. from linkai import LinkAIClient
  88. client_id = LinkAIClient.fetch_client_id()
  89. if client_id:
  90. body["client_id"] = client_id
  91. # start: client info deliver
  92. if context.kwargs.get("msg"):
  93. body["session_id"] = context.kwargs.get("msg").from_user_id
  94. if context.kwargs.get("msg").is_group:
  95. body["is_group"] = True
  96. body["group_name"] = context.kwargs.get("msg").from_user_nickname
  97. body["sender_name"] = context.kwargs.get("msg").actual_user_nickname
  98. else:
  99. body["sender_name"] = context.kwargs.get("msg").from_user_nickname
  100. except Exception as e:
  101. pass
  102. file_id = context.kwargs.get("file_id")
  103. if file_id:
  104. body["file_id"] = file_id
  105. logger.info(f"[LINKAI] query={query}, app_code={app_code}, model={body.get('model')}, file_id={file_id}")
  106. headers = {"Authorization": "Bearer " + linkai_api_key}
  107. # do http request
  108. base_url = conf().get("linkai_api_base", "https://api.link-ai.chat")
  109. res = requests.post(url=base_url + "/v1/chat/completions", json=body, headers=headers,
  110. timeout=conf().get("request_timeout", 180))
  111. if res.status_code == 200:
  112. # execute success
  113. response = res.json()
  114. reply_content = response["choices"][0]["message"]["content"]
  115. total_tokens = response["usage"]["total_tokens"]
  116. logger.info(f"[LINKAI] reply={reply_content}, total_tokens={total_tokens}")
  117. self.sessions.session_reply(reply_content, session_id, total_tokens, query=query)
  118. agent_suffix = self._fetch_agent_suffix(response)
  119. if agent_suffix:
  120. reply_content += agent_suffix
  121. if not agent_suffix:
  122. knowledge_suffix = self._fetch_knowledge_search_suffix(response)
  123. if knowledge_suffix:
  124. reply_content += knowledge_suffix
  125. # image process
  126. if response["choices"][0].get("img_urls"):
  127. thread = threading.Thread(target=self._send_image, args=(context.get("channel"), context, response["choices"][0].get("img_urls")))
  128. thread.start()
  129. if response["choices"][0].get("text_content"):
  130. reply_content = response["choices"][0].get("text_content")
  131. return Reply(ReplyType.TEXT, reply_content)
  132. else:
  133. response = res.json()
  134. error = response.get("error")
  135. logger.error(f"[LINKAI] chat failed, status_code={res.status_code}, "
  136. f"msg={error.get('message')}, type={error.get('type')}")
  137. if res.status_code >= 500:
  138. # server error, need retry
  139. time.sleep(2)
  140. logger.warn(f"[LINKAI] do retry, times={retry_count}")
  141. return self._chat(query, context, retry_count + 1)
  142. return Reply(ReplyType.TEXT, "提问太快啦,请休息一下再问我吧")
  143. except Exception as e:
  144. logger.exception(e)
  145. # retry
  146. time.sleep(2)
  147. logger.warn(f"[LINKAI] do retry, times={retry_count}")
  148. return self._chat(query, context, retry_count + 1)
  149. def _process_image_msg(self, app_code: str, session_id: str, query:str, img_cache: dict):
  150. try:
  151. enable_image_input = False
  152. app_info = self._fetch_app_info(app_code)
  153. if not app_info:
  154. logger.debug(f"[LinkAI] not found app, can't process images, app_code={app_code}")
  155. return None
  156. plugins = app_info.get("data").get("plugins")
  157. for plugin in plugins:
  158. if plugin.get("input_type") and "IMAGE" in plugin.get("input_type"):
  159. enable_image_input = True
  160. if not enable_image_input:
  161. return
  162. msg = img_cache.get("msg")
  163. path = img_cache.get("path")
  164. msg.prepare()
  165. logger.info(f"[LinkAI] query with images, path={path}")
  166. messages = self._build_vision_msg(query, path)
  167. memory.USER_IMAGE_CACHE[session_id] = None
  168. return messages
  169. except Exception as e:
  170. logger.exception(e)
  171. def _find_group_mapping_code(self, context):
  172. try:
  173. if context.kwargs.get("isgroup"):
  174. group_name = context.kwargs.get("msg").from_user_nickname
  175. if config.plugin_config and config.plugin_config.get("linkai"):
  176. linkai_config = config.plugin_config.get("linkai")
  177. group_mapping = linkai_config.get("group_app_map")
  178. if group_mapping and group_name:
  179. return group_mapping.get(group_name)
  180. except Exception as e:
  181. logger.exception(e)
  182. return None
  183. def _build_vision_msg(self, query: str, path: str):
  184. try:
  185. suffix = utils.get_path_suffix(path)
  186. with open(path, "rb") as file:
  187. base64_str = base64.b64encode(file.read()).decode('utf-8')
  188. messages = [{
  189. "role": "user",
  190. "content": [
  191. {
  192. "type": "text",
  193. "text": query
  194. },
  195. {
  196. "type": "image_url",
  197. "image_url": {
  198. "url": f"data:image/{suffix};base64,{base64_str}"
  199. }
  200. }
  201. ]
  202. }]
  203. return messages
  204. except Exception as e:
  205. logger.exception(e)
  206. def reply_text(self, session: ChatGPTSession, app_code="", retry_count=0) -> dict:
  207. if retry_count >= 2:
  208. # exit from retry 2 times
  209. logger.warn("[LINKAI] failed after maximum number of retry times")
  210. return {
  211. "total_tokens": 0,
  212. "completion_tokens": 0,
  213. "content": "请再问我一次吧"
  214. }
  215. try:
  216. body = {
  217. "app_code": app_code,
  218. "messages": session.messages,
  219. "model": conf().get("model") or "gpt-3.5-turbo", # 对话模型的名称, 支持 gpt-3.5-turbo, gpt-3.5-turbo-16k, gpt-4, wenxin, xunfei
  220. "temperature": conf().get("temperature"),
  221. "top_p": conf().get("top_p", 1),
  222. "frequency_penalty": conf().get("frequency_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  223. "presence_penalty": conf().get("presence_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  224. }
  225. if self.args.get("max_tokens"):
  226. body["max_tokens"] = self.args.get("max_tokens")
  227. headers = {"Authorization": "Bearer " + conf().get("linkai_api_key")}
  228. # do http request
  229. base_url = conf().get("linkai_api_base", "https://api.link-ai.chat")
  230. res = requests.post(url=base_url + "/v1/chat/completions", json=body, headers=headers,
  231. timeout=conf().get("request_timeout", 180))
  232. if res.status_code == 200:
  233. # execute success
  234. response = res.json()
  235. reply_content = response["choices"][0]["message"]["content"]
  236. total_tokens = response["usage"]["total_tokens"]
  237. logger.info(f"[LINKAI] reply={reply_content}, total_tokens={total_tokens}")
  238. return {
  239. "total_tokens": total_tokens,
  240. "completion_tokens": response["usage"]["completion_tokens"],
  241. "content": reply_content,
  242. }
  243. else:
  244. response = res.json()
  245. error = response.get("error")
  246. logger.error(f"[LINKAI] chat failed, status_code={res.status_code}, "
  247. f"msg={error.get('message')}, type={error.get('type')}")
  248. if res.status_code >= 500:
  249. # server error, need retry
  250. time.sleep(2)
  251. logger.warn(f"[LINKAI] do retry, times={retry_count}")
  252. return self.reply_text(session, app_code, retry_count + 1)
  253. return {
  254. "total_tokens": 0,
  255. "completion_tokens": 0,
  256. "content": "提问太快啦,请休息一下再问我吧"
  257. }
  258. except Exception as e:
  259. logger.exception(e)
  260. # retry
  261. time.sleep(2)
  262. logger.warn(f"[LINKAI] do retry, times={retry_count}")
  263. return self.reply_text(session, app_code, retry_count + 1)
  264. def _fetch_app_info(self, app_code: str):
  265. headers = {"Authorization": "Bearer " + conf().get("linkai_api_key")}
  266. # do http request
  267. base_url = conf().get("linkai_api_base", "https://api.link-ai.chat")
  268. params = {"app_code": app_code}
  269. res = requests.get(url=base_url + "/v1/app/info", params=params, headers=headers, timeout=(5, 10))
  270. if res.status_code == 200:
  271. return res.json()
  272. else:
  273. logger.warning(f"[LinkAI] find app info exception, res={res}")
  274. def create_img(self, query, retry_count=0, api_key=None):
  275. try:
  276. logger.info("[LinkImage] image_query={}".format(query))
  277. headers = {
  278. "Content-Type": "application/json",
  279. "Authorization": f"Bearer {conf().get('linkai_api_key')}"
  280. }
  281. data = {
  282. "prompt": query,
  283. "n": 1,
  284. "model": conf().get("text_to_image") or "dall-e-2",
  285. "response_format": "url",
  286. "img_proxy": conf().get("image_proxy")
  287. }
  288. url = conf().get("linkai_api_base", "https://api.link-ai.chat") + "/v1/images/generations"
  289. res = requests.post(url, headers=headers, json=data, timeout=(5, 90))
  290. t2 = time.time()
  291. image_url = res.json()["data"][0]["url"]
  292. logger.info("[OPEN_AI] image_url={}".format(image_url))
  293. return True, image_url
  294. except Exception as e:
  295. logger.error(format(e))
  296. return False, "画图出现问题,请休息一下再问我吧"
  297. def _fetch_knowledge_search_suffix(self, response) -> str:
  298. try:
  299. if response.get("knowledge_base"):
  300. search_hit = response.get("knowledge_base").get("search_hit")
  301. first_similarity = response.get("knowledge_base").get("first_similarity")
  302. logger.info(f"[LINKAI] knowledge base, search_hit={search_hit}, first_similarity={first_similarity}")
  303. plugin_config = pconf("linkai")
  304. if plugin_config and plugin_config.get("knowledge_base") and plugin_config.get("knowledge_base").get("search_miss_text_enabled"):
  305. search_miss_similarity = plugin_config.get("knowledge_base").get("search_miss_similarity")
  306. search_miss_text = plugin_config.get("knowledge_base").get("search_miss_suffix")
  307. if not search_hit:
  308. return search_miss_text
  309. if search_miss_similarity and float(search_miss_similarity) > first_similarity:
  310. return search_miss_text
  311. except Exception as e:
  312. logger.exception(e)
  313. def _fetch_agent_suffix(self, response):
  314. try:
  315. plugin_list = []
  316. logger.debug(f"[LinkAgent] res={response}")
  317. if response.get("agent") and response.get("agent").get("chain") and response.get("agent").get("need_show_plugin"):
  318. chain = response.get("agent").get("chain")
  319. suffix = "\n\n- - - - - - - - - - - -"
  320. i = 0
  321. for turn in chain:
  322. plugin_name = turn.get('plugin_name')
  323. suffix += "\n"
  324. need_show_thought = response.get("agent").get("need_show_thought")
  325. if turn.get("thought") and plugin_name and need_show_thought:
  326. suffix += f"{turn.get('thought')}\n"
  327. if plugin_name:
  328. plugin_list.append(turn.get('plugin_name'))
  329. suffix += f"{turn.get('plugin_icon')} {turn.get('plugin_name')}"
  330. if turn.get('plugin_input'):
  331. suffix += f":{turn.get('plugin_input')}"
  332. if i < len(chain) - 1:
  333. suffix += "\n"
  334. i += 1
  335. logger.info(f"[LinkAgent] use plugins: {plugin_list}")
  336. return suffix
  337. except Exception as e:
  338. logger.exception(e)
  339. def _send_image(self, channel, context, image_urls):
  340. if not image_urls:
  341. return
  342. try:
  343. for url in image_urls:
  344. reply = Reply(ReplyType.IMAGE_URL, url)
  345. channel.send(reply, context)
  346. except Exception as e:
  347. logger.error(e)
  348. class LinkAISessionManager(SessionManager):
  349. def session_msg_query(self, query, session_id):
  350. session = self.build_session(session_id)
  351. messages = session.messages + [{"role": "user", "content": query}]
  352. return messages
  353. def session_reply(self, reply, session_id, total_tokens=None, query=None):
  354. session = self.build_session(session_id)
  355. if query:
  356. session.add_query(query)
  357. session.add_reply(reply)
  358. try:
  359. max_tokens = conf().get("conversation_max_tokens", 2500)
  360. tokens_cnt = session.discard_exceeding(max_tokens, total_tokens)
  361. logger.debug(f"[LinkAI] chat history, before tokens={total_tokens}, now tokens={tokens_cnt}")
  362. except Exception as e:
  363. logger.warning("Exception when counting tokens precisely for session: {}".format(str(e)))
  364. return session
  365. class LinkAISession(ChatGPTSession):
  366. def calc_tokens(self):
  367. if not self.messages:
  368. return 0
  369. return len(str(self.messages))
  370. def discard_exceeding(self, max_tokens, cur_tokens=None):
  371. cur_tokens = self.calc_tokens()
  372. if cur_tokens > max_tokens:
  373. for i in range(0, len(self.messages)):
  374. if i > 0 and self.messages[i].get("role") == "assistant" and self.messages[i - 1].get("role") == "user":
  375. self.messages.pop(i)
  376. self.messages.pop(i - 1)
  377. return self.calc_tokens()
  378. return cur_tokens