您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

108 行
4.3KB

  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. self.base_url = "https://api.link-ai.chat/v1"
  19. self.sessions = SessionManager(ChatGPTSession, model=conf().get("model") or "gpt-3.5-turbo")
  20. def reply(self, query, context: Context = None) -> Reply:
  21. if context.type == ContextType.TEXT:
  22. return self._chat(query, context)
  23. elif context.type == ContextType.IMAGE_CREATE:
  24. ok, retstring = self.create_img(query, 0)
  25. reply = None
  26. if ok:
  27. reply = Reply(ReplyType.IMAGE_URL, retstring)
  28. else:
  29. reply = Reply(ReplyType.ERROR, retstring)
  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):
  35. if retry_count >= 2:
  36. # exit from retry 2 times
  37. logger.warn("[LINKAI] failed after maximum number of retry times")
  38. return Reply(ReplyType.ERROR, "请再问我一次吧")
  39. try:
  40. # load config
  41. if context.get("generate_breaked_by"):
  42. logger.info(f"[LINKAI] won't set appcode because a plugin ({context['generate_breaked_by']}) affected the context")
  43. app_code = None
  44. else:
  45. app_code = conf().get("linkai_app_code")
  46. linkai_api_key = conf().get("linkai_api_key")
  47. session_id = context["session_id"]
  48. session = self.sessions.session_query(query, session_id)
  49. # remove system message
  50. if app_code and session.messages[0].get("role") == "system":
  51. session.messages.pop(0)
  52. logger.info(f"[LINKAI] query={query}, app_code={app_code}")
  53. body = {
  54. "appCode": app_code,
  55. "messages": session.messages,
  56. "model": conf().get("model") or "gpt-3.5-turbo", # 对话模型的名称
  57. "temperature": conf().get("temperature"),
  58. "top_p": conf().get("top_p", 1),
  59. "frequency_penalty": conf().get("frequency_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  60. "presence_penalty": conf().get("presence_penalty", 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
  61. }
  62. headers = {"Authorization": "Bearer " + linkai_api_key}
  63. # do http request
  64. res = requests.post(url=self.base_url + "/chat/completion", json=body, headers=headers).json()
  65. if not res or not res["success"]:
  66. if res.get("code") == self.AUTH_FAILED_CODE:
  67. logger.exception(f"[LINKAI] please check your linkai_api_key, res={res}")
  68. return Reply(ReplyType.ERROR, "请再问我一次吧")
  69. elif res.get("code") == self.NO_QUOTA_CODE:
  70. logger.exception(f"[LINKAI] please check your account quota, https://chat.link-ai.tech/console/account")
  71. return Reply(ReplyType.ERROR, "提问太快啦,请休息一下再问我吧")
  72. else:
  73. # retry
  74. time.sleep(2)
  75. logger.warn(f"[LINKAI] do retry, times={retry_count}")
  76. return self._chat(query, context, retry_count + 1)
  77. # execute success
  78. reply_content = res["data"]["content"]
  79. logger.info(f"[LINKAI] reply={reply_content}")
  80. self.sessions.session_reply(reply_content, session_id)
  81. return Reply(ReplyType.TEXT, reply_content)
  82. except Exception as e:
  83. logger.exception(e)
  84. # retry
  85. time.sleep(2)
  86. logger.warn(f"[LINKAI] do retry, times={retry_count}")
  87. return self._chat(query, context, retry_count + 1)