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.

464 line
20KB

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