custom_agent.py 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. from typing import Optional
  2. from openai import OpenAI
  3. from wcferry import WxMsg
  4. from plugins.plugin import Plugin
  5. from openai import OpenAI, AuthenticationError, APIConnectionError, APIError
  6. class CustomAgent(Plugin):
  7. def __init__(self):
  8. super().__init__()
  9. self.customAiClient = OpenAI(api_key=self.config.get("custom_agent_key"), base_url=self.config.get("custom_agent_base"))
  10. def answer(self, msg: WxMsg, wx_wxid: Optional[str] = None) -> str:
  11. rsp = ""
  12. try:
  13. messages = [
  14. {"role": "user", "content": msg.content}
  15. ]
  16. rsp = self._client_reply(self.customAiClient, messages, msg.sender, msg.roomid)
  17. self.LOG.info(rsp)
  18. except AuthenticationError:
  19. self.LOG.error("OpenAI API 认证失败,请检查 API 密钥是否正确")
  20. except APIConnectionError:
  21. self.LOG.error("无法连接到 OpenAI API,请检查网络连接")
  22. except APIError as e1:
  23. self.LOG.error(f"OpenAI API 返回了错误:{str(e1)}")
  24. except Exception as e0:
  25. self.LOG.error(f"发生未知错误:{str(e0)}")
  26. return rsp