from typing import Optional

from openai import OpenAI
from wcferry import WxMsg

from plugins.plugin import Plugin
from openai import OpenAI, AuthenticationError, APIConnectionError, APIError


class CustomAgent(Plugin):
    def __init__(self):
        super().__init__()
        self.customAiClient = OpenAI(api_key=self.config.get("custom_agent_key"), base_url=self.config.get("custom_agent_base"))

    def answer(self, msg: WxMsg, wx_wxid: Optional[str] = None) -> str:
        rsp = ""
        try:
            messages = [
                {"role": "user", "content": msg.content}
            ]
            rsp = self._client_reply(self.customAiClient, messages, msg.sender, msg.roomid)
            self.LOG.info(rsp)
        except AuthenticationError:
            self.LOG.error("OpenAI API 认证失败，请检查 API 密钥是否正确")
        except APIConnectionError:
            self.LOG.error("无法连接到 OpenAI API，请检查网络连接")
        except APIError as e1:
            self.LOG.error(f"OpenAI API 返回了错误：{str(e1)}")
        except Exception as e0:
            self.LOG.error(f"发生未知错误：{str(e0)}")
        return rsp
