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 9.3KB

1 yıl önce
1 yıl önce
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. # access LinkAI knowledge base platform
  2. # docs: https://link-ai.tech/platform/link-app/wechat
  3. import time
  4. import requests
  5. from bot.bot import Bot
  6. from bot.chatgpt.chat_gpt_session import ChatGPTSession
  7. from bot.openai.open_ai_image import OpenAIImage
  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. class LinkAIBot(Bot, OpenAIImage):
  14. # authentication failed
  15. AUTH_FAILED_CODE = 401
  16. NO_QUOTA_CODE = 406
  17. def __init__(self):
  18. super().__init__()
  19. self.sessions = SessionManager(ChatGPTSession, model=conf().get("model") or "gpt-3.5-turbo")
  20. self.args = {}
  21. def reply(self, query, context: Context = None) -> Reply:
  22. if context.type == ContextType.TEXT:
  23. return self._chat(query, context)
  24. elif context.type == ContextType.IMAGE_CREATE:
  25. ok, res = self.create_img(query, 0)
  26. if ok:
  27. reply = Reply(ReplyType.IMAGE_URL, res)
  28. else:
  29. reply = Reply(ReplyType.ERROR, res)
  30. return reply
  31. else:
  32. reply = Reply(ReplyType.ERROR, "Bot不支持处理{}类型的消息".format(context.type))
  33. return reply
  34. def _chat(self, query, context, retry_count=0) -> Reply:
  35. """
  36. 发起对话请求
  37. :param query: 请求提示词
  38. :param context: 对话上下文
  39. :param retry_count: 当前递归重试次数
  40. :return: 回复
  41. """
  42. if retry_count >= 2:
  43. # exit from retry 2 times
  44. logger.warn("[LINKAI] failed after maximum number of retry times")
  45. return Reply(ReplyType.ERROR, "请再问我一次吧")
  46. try:
  47. # load config
  48. if context.get("generate_breaked_by"):
  49. logger.info(f"[LINKAI] won't set appcode because a plugin ({context['generate_breaked_by']}) affected the context")
  50. app_code = None
  51. else:
  52. app_code = context.kwargs.get("app_code") or conf().get("linkai_app_code")
  53. linkai_api_key = conf().get("linkai_api_key")
  54. session_id = context["session_id"]
  55. session = self.sessions.session_query(query, session_id)
  56. model = conf().get("model") or "gpt-3.5-turbo"
  57. # remove system message
  58. if session.messages[0].get("role") == "system":
  59. if app_code or model == "wenxin":
  60. session.messages.pop(0)
  61. body = {
  62. "app_code": app_code,
  63. "messages": session.messages,
  64. "model": model, # 对话模型的名称, 支持 gpt-3.5-turbo, gpt-3.5-turbo-16k, gpt-4, wenxin, xunfei
  65. "temperature": conf().get("temperature"),
  66. "top_p": conf().get("top_p", 1),
  67. "frequency_penalty": conf().get("frequency_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  68. "presence_penalty": conf().get("presence_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  69. }
  70. file_id = context.kwargs.get("file_id")
  71. if file_id:
  72. body["file_id"] = file_id
  73. logger.info(f"[LINKAI] query={query}, app_code={app_code}, mode={body.get('model')}, file_id={file_id}")
  74. headers = {"Authorization": "Bearer " + linkai_api_key}
  75. # do http request
  76. base_url = conf().get("linkai_api_base", "https://api.link-ai.chat")
  77. res = requests.post(url=base_url + "/v1/chat/completions", json=body, headers=headers,
  78. timeout=conf().get("request_timeout", 180))
  79. if res.status_code == 200:
  80. # execute success
  81. response = res.json()
  82. reply_content = response["choices"][0]["message"]["content"]
  83. total_tokens = response["usage"]["total_tokens"]
  84. suffix = self._fecth_knowledge_search_suffix(response)
  85. if suffix:
  86. reply_content += suffix
  87. logger.info(f"[LINKAI] reply={reply_content}, total_tokens={total_tokens}")
  88. self.sessions.session_reply(reply_content, session_id, total_tokens)
  89. return Reply(ReplyType.TEXT, reply_content)
  90. else:
  91. response = res.json()
  92. error = response.get("error")
  93. logger.error(f"[LINKAI] chat failed, status_code={res.status_code}, "
  94. f"msg={error.get('message')}, type={error.get('type')}")
  95. if res.status_code >= 500:
  96. # server error, need retry
  97. time.sleep(2)
  98. logger.warn(f"[LINKAI] do retry, times={retry_count}")
  99. return self._chat(query, context, retry_count + 1)
  100. return Reply(ReplyType.ERROR, "提问太快啦,请休息一下再问我吧")
  101. except Exception as e:
  102. logger.exception(e)
  103. # retry
  104. time.sleep(2)
  105. logger.warn(f"[LINKAI] do retry, times={retry_count}")
  106. return self._chat(query, context, retry_count + 1)
  107. def reply_text(self, session: ChatGPTSession, app_code="", retry_count=0) -> dict:
  108. if retry_count >= 2:
  109. # exit from retry 2 times
  110. logger.warn("[LINKAI] failed after maximum number of retry times")
  111. return {
  112. "total_tokens": 0,
  113. "completion_tokens": 0,
  114. "content": "请再问我一次吧"
  115. }
  116. try:
  117. body = {
  118. "app_code": app_code,
  119. "messages": session.messages,
  120. "model": conf().get("model") or "gpt-3.5-turbo", # 对话模型的名称, 支持 gpt-3.5-turbo, gpt-3.5-turbo-16k, gpt-4, wenxin, xunfei
  121. "temperature": conf().get("temperature"),
  122. "top_p": conf().get("top_p", 1),
  123. "frequency_penalty": conf().get("frequency_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  124. "presence_penalty": conf().get("presence_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  125. }
  126. if self.args.get("max_tokens"):
  127. body["max_tokens"] = self.args.get("max_tokens")
  128. headers = {"Authorization": "Bearer " + conf().get("linkai_api_key")}
  129. # do http request
  130. base_url = conf().get("linkai_api_base", "https://api.link-ai.chat")
  131. res = requests.post(url=base_url + "/v1/chat/completions", json=body, headers=headers,
  132. timeout=conf().get("request_timeout", 180))
  133. if res.status_code == 200:
  134. # execute success
  135. response = res.json()
  136. reply_content = response["choices"][0]["message"]["content"]
  137. total_tokens = response["usage"]["total_tokens"]
  138. logger.info(f"[LINKAI] reply={reply_content}, total_tokens={total_tokens}")
  139. return {
  140. "total_tokens": total_tokens,
  141. "completion_tokens": response["usage"]["completion_tokens"],
  142. "content": reply_content,
  143. }
  144. else:
  145. response = res.json()
  146. error = response.get("error")
  147. logger.error(f"[LINKAI] chat failed, status_code={res.status_code}, "
  148. f"msg={error.get('message')}, type={error.get('type')}")
  149. if res.status_code >= 500:
  150. # server error, need retry
  151. time.sleep(2)
  152. logger.warn(f"[LINKAI] do retry, times={retry_count}")
  153. return self.reply_text(session, app_code, retry_count + 1)
  154. return {
  155. "total_tokens": 0,
  156. "completion_tokens": 0,
  157. "content": "提问太快啦,请休息一下再问我吧"
  158. }
  159. except Exception as e:
  160. logger.exception(e)
  161. # retry
  162. time.sleep(2)
  163. logger.warn(f"[LINKAI] do retry, times={retry_count}")
  164. return self.reply_text(session, app_code, retry_count + 1)
  165. def _fecth_knowledge_search_suffix(self, response) -> str:
  166. try:
  167. if response.get("knowledge_base"):
  168. search_hit = response.get("knowledge_base").get("search_hit")
  169. first_similarity = response.get("knowledge_base").get("first_similarity")
  170. logger.info(f"[LINKAI] knowledge base, search_hit={search_hit}, first_similarity={first_similarity}")
  171. plugin_config = pconf("linkai")
  172. if plugin_config.get("knowledge_base") and plugin_config.get("knowledge_base").get("search_miss_text_enabled"):
  173. search_miss_similarity = plugin_config.get("knowledge_base").get("search_miss_similarity")
  174. search_miss_text = plugin_config.get("knowledge_base").get("search_miss_suffix")
  175. if not search_hit:
  176. return search_miss_text
  177. if search_miss_similarity and float(search_miss_similarity) > first_similarity:
  178. return search_miss_text
  179. except Exception as e:
  180. logger.exception(e)