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.

429 lines
19KB

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