Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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