Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

link_ai_bot.py 4.4KB

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