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.

116 satır
4.7KB

  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.base_url = "https://api.link-ai.chat/v1"
  20. self.sessions = SessionManager(ChatGPTSession, model=conf().get("model") or "gpt-3.5-turbo")
  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. # remove system message
  57. if app_code and session.messages[0].get("role") == "system":
  58. session.messages.pop(0)
  59. body = {
  60. "app_code": app_code,
  61. "messages": session.messages,
  62. "model": conf().get("model") or "gpt-3.5-turbo", # 对话模型的名称
  63. "temperature": conf().get("temperature"),
  64. "top_p": conf().get("top_p", 1),
  65. "frequency_penalty": conf().get("frequency_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  66. "presence_penalty": conf().get("presence_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  67. }
  68. logger.info(f"[LINKAI] query={query}, app_code={app_code}, mode={body.get('model')}")
  69. headers = {"Authorization": "Bearer " + linkai_api_key}
  70. # do http request
  71. res = requests.post(url=self.base_url + "/chat/completions", json=body, headers=headers,
  72. timeout=conf().get("request_timeout", 180))
  73. if res.status_code == 200:
  74. # execute success
  75. response = res.json()
  76. reply_content = response["choices"][0]["message"]["content"]
  77. total_tokens = response["usage"]["total_tokens"]
  78. logger.info(f"[LINKAI] reply={reply_content}, total_tokens={total_tokens}")
  79. self.sessions.session_reply(reply_content, session_id, total_tokens)
  80. return Reply(ReplyType.TEXT, reply_content)
  81. else:
  82. response = res.json()
  83. error = response.get("error")
  84. logger.error(f"[LINKAI] chat failed, status_code={res.status_code}, "
  85. f"msg={error.get('message')}, type={error.get('type')}")
  86. if res.status_code >= 500:
  87. # server error, need retry
  88. time.sleep(2)
  89. logger.warn(f"[LINKAI] do retry, times={retry_count}")
  90. return self._chat(query, context, retry_count + 1)
  91. return Reply(ReplyType.ERROR, "提问太快啦,请休息一下再问我吧")
  92. except Exception as e:
  93. logger.exception(e)
  94. # retry
  95. time.sleep(2)
  96. logger.warn(f"[LINKAI] do retry, times={retry_count}")
  97. return self._chat(query, context, retry_count + 1)