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.

link_ai_bot.py 18KB

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