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.

402 satır
18KB

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