import requests
import re
from urllib.parse import quote_plus

class AGDeepThink():
    def __init__(self):
        self.system_prompt = (
            "You are an AGI assistant called OpenAGI. You are artificial general intelligence. "
            "If the user asks to generate an image, audio, or video, say you are doing it." 
            "Your response should be inside <response> tags. for example:\n"
            "<response>Here is the response.</response>\n"
        )

    def _ask(self, prompt: str):
        url = f"http://text.pollinations.ai/{quote_plus(prompt)}"

        try:
            response = requests.get(url, timeout=20)
            response.raise_for_status()
            text = response.text
            text = text.replace(self.system_prompt, "")
            text = re.sub(r'\[([^\]]+)\]\((https?://[^\s)]+)\)', '', text)
            text = re.sub(r'https?://[^\s]+', '', text)
            text = re.sub(r'\b[\w\d%$^&+_=]{15,}\b', '', text)
            return text.strip()

        except requests.RequestException as e:
            print(f"[ERROR] API request failed: {e}")
            return "The request failed."

    def _rask(self, prompt: str):
        reasoning_prompt = (
            "Provide a reasoning CoT about the following prompt, do not provide a final answer, "
            "Provide your reasoning inside <cot> tags. "
            "for example:\n"
            "<cot>Here is the reasoning.</cot>\n"
            "just reasoning and a long CoT (chain of thought) about the prompt. "
            "Your CoT must be less than 500 characters.\n\nThe prompt is:\n\n" + prompt
        )
        response = self._ask(reasoning_prompt)
        cot_match = re.search(r'<cot>(.*?)</cot>', response, re.DOTALL)
        if cot_match:
            cot = f"<cot>{cot_match.group(1).strip()}</cot>"
        else:
            cot = "<cot></cot>"
        return cot

    def ask(self, prompt: str):
        cot = self._rask(prompt)
        full_prompt = f"{self.system_prompt}\nCoT: {cot}\nUser: {prompt}"
        response = self._ask(full_prompt)
        response_match = re.search(r'<response>(.*?)</response>', response, re.DOTALL)
        if response_match:
            response = f"<response>{response_match.group(1).strip()}</response>"
        else:
            response = "<response></response>"
        return cot + "\n" + response

if __name__ == "__main__":
    model = AGDeepThink()
    response = model.ask("hi")
    print(response)  