Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

468 rindas
21KB

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