選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

link_ai_bot.py 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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
  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. logger.info(f"[LINKAI] query={query}, app_code={app_code}, mode={body.get('model')}")
  71. headers = {"Authorization": "Bearer " + linkai_api_key}
  72. # do http request
  73. base_url = conf().get("linkai_api_base", "https://api.link-ai.chat")
  74. res = requests.post(url=base_url + "/v1/chat/completions", json=body, headers=headers,
  75. timeout=conf().get("request_timeout", 180))
  76. if res.status_code == 200:
  77. # execute success
  78. response = res.json()
  79. reply_content = response["choices"][0]["message"]["content"]
  80. total_tokens = response["usage"]["total_tokens"]
  81. logger.info(f"[LINKAI] reply={reply_content}, total_tokens={total_tokens}")
  82. self.sessions.session_reply(reply_content, session_id, total_tokens)
  83. return Reply(ReplyType.TEXT, reply_content)
  84. else:
  85. response = res.json()
  86. error = response.get("error")
  87. logger.error(f"[LINKAI] chat failed, status_code={res.status_code}, "
  88. f"msg={error.get('message')}, type={error.get('type')}")
  89. if res.status_code >= 500:
  90. # server error, need retry
  91. time.sleep(2)
  92. logger.warn(f"[LINKAI] do retry, times={retry_count}")
  93. return self._chat(query, context, retry_count + 1)
  94. return Reply(ReplyType.ERROR, "提问太快啦,请休息一下再问我吧")
  95. except Exception as e:
  96. logger.exception(e)
  97. # retry
  98. time.sleep(2)
  99. logger.warn(f"[LINKAI] do retry, times={retry_count}")
  100. return self._chat(query, context, retry_count + 1)
  101. def reply_text(self, session: ChatGPTSession, app_code="", retry_count=0) -> dict:
  102. if retry_count >= 2:
  103. # exit from retry 2 times
  104. logger.warn("[LINKAI] failed after maximum number of retry times")
  105. return {
  106. "total_tokens": 0,
  107. "completion_tokens": 0,
  108. "content": "请再问我一次吧"
  109. }
  110. try:
  111. body = {
  112. "app_code": app_code,
  113. "messages": session.messages,
  114. "model": conf().get("model") or "gpt-3.5-turbo", # 对话模型的名称, 支持 gpt-3.5-turbo, gpt-3.5-turbo-16k, gpt-4, wenxin, xunfei
  115. "temperature": conf().get("temperature"),
  116. "top_p": conf().get("top_p", 1),
  117. "frequency_penalty": conf().get("frequency_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  118. "presence_penalty": conf().get("presence_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  119. }
  120. if self.args.get("max_tokens"):
  121. body["max_tokens"] = self.args.get("max_tokens")
  122. headers = {"Authorization": "Bearer " + conf().get("linkai_api_key")}
  123. # do http request
  124. base_url = conf().get("linkai_api_base", "https://api.link-ai.chat")
  125. res = requests.post(url=base_url + "/v1/chat/completions", json=body, headers=headers,
  126. timeout=conf().get("request_timeout", 180))
  127. if res.status_code == 200:
  128. # execute success
  129. response = res.json()
  130. reply_content = response["choices"][0]["message"]["content"]
  131. total_tokens = response["usage"]["total_tokens"]
  132. logger.info(f"[LINKAI] reply={reply_content}, total_tokens={total_tokens}")
  133. return {
  134. "total_tokens": total_tokens,
  135. "completion_tokens": response["usage"]["completion_tokens"],
  136. "content": reply_content,
  137. }
  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.reply_text(session, app_code, retry_count + 1)
  148. return {
  149. "total_tokens": 0,
  150. "completion_tokens": 0,
  151. "content": "提问太快啦,请休息一下再问我吧"
  152. }
  153. except Exception as e:
  154. logger.exception(e)
  155. # retry
  156. time.sleep(2)
  157. logger.warn(f"[LINKAI] do retry, times={retry_count}")
  158. return self.reply_text(session, app_code, retry_count + 1)