import requests

class ChatGPTOS:
    def __init__(self, api_key: str, base_url: str = "https://coollamaceo-chatgptopensourceapi.hf.space"):
        """
        ChatGPT Open-Source Python Client
        
        :param api_key: Your generated API key
        :param base_url: URL to your Hugging Face FastAPI space
        """
        self.api_key = api_key
        self.base_url = base_url.rstrip("/")
        self.session_id = None  # Optional session memory

    def chat(self, message: str, session_id: str = "default") -> str:
        """
        Send a message to the GPT-OSS 20B backend
        """
        self.session_id = session_id
        payload = {
            "message": message,
            "session_id": self.session_id
        }
        headers = {
            "Content-Type": "application/json",
            "X-API-Key": self.api_key
        }

        try:
            response = requests.post(f"{self.base_url}/v1/chat", json=payload, headers=headers, timeout=120)
            response.raise_for_status()
            data = response.json()
            return data.get("response", "[No response from API]")
        except requests.exceptions.Timeout:
            return "[Request timed out — large model is slow]"
        except requests.exceptions.RequestException as e:
            return f"[Error calling API: {e}]"
