import requests,utils

class AnythingLLM:


    def __init__(self, api_key: str=None, api_url: str=None):
        self._api_key = api_key or utils.get_config_value('anythingLLm.api_key')
        self._api_url = api_url or utils.get_config_value('anythingLLm.api_url')
        self._logger = utils.get_logger()
        self._headers ={}

    def build_header(self):
        if self._api_key is None:
            self._logger.error("anythingLLm.api_key 没有配置")
            raise Exception("anythingLLm.api_key 没有配置")
        self._headers = {
            "Authorization": f"Bearer {self._api_key}",
            "Content-Type": "application/json",
            "accept": "application/json"
        }

    def call_ai(self, msg: str, workspace:str=None) -> str|None:
        try:
            self.build_header()
            if workspace is None:
                workspace = utils.get_config_value('anythingLLm.workspace')
            url = f"{self._api_url}/workspace/{workspace}/chat"
            data = {
                "message": msg,
                "mode": "query"  # 可选chat/query模式
            }
            response = requests.post(url, headers=self._headers, json=data)
            if response.status_code == 200:
                result = response.json()
                self._logger.info(f"Response: {result}")
                # 提取有效回答（去除思考过程）
                answer = result['textResponse'].split('</think>')[-1].strip()
                self._logger.info(f"Answer: {answer}")
                sources = result.get('sources', [])
                for source in sources:
                    self._logger.info(f"Source: {source}")
                return answer
            else:
                return f"Error: {response.text}"
        except Exception as e:
            self._logger.error(f"Error: {str(e)}")
            return None

