Further enhance and make it explicitly compute complex tasks with a more enhanced chain-of-thought.

```
import g4f
from g4f.client import Client
import json
import re
import logging
import spacy

# Initialize spaCy English model
nlp = spacy.load('en_core_web_sm')

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class AdvancedChatbot:
    def __init__(self, provider=g4f.Provider.AmigoChat, model="gpt-4o-2024-11-20"):
        """
        Initialize the chatbot with a specific provider and model
        """
        self.client = Client(provider=provider)
        self.model = model
        self.conversation_history = []
        self.system_context = {
            "personality": "You are a highly intelligent AI assistant capable of solving complex problems.",
            "tone": "Professional and analytical",
            "interests": ["advanced mathematics", "complex problem-solving", "logical reasoning"],
            "reasoning_method": "Deep Analytical Thinking"
        }
        self.max_recursion_depth = 3  # Prevent infinite recursion
        self.user_profile = {}  # Store user-specific data

    def format_system_message(self):
        """
        Create a dynamic system message based on the context
        """
        return f"""
{self.system_context['personality']}
Conversation Tone: {self.system_context['tone']}
Key Interests: {', '.join(self.system_context['interests'])}

Reasoning Method:
- Utilize Deep Analytical Thinking to solve complex queries.
- Break down problems into sub-components and analyze each thoroughly.
- Perform internal multi-step reasoning before providing an answer.

Guidelines:
- Provide clear and detailed explanations.
- Keep internal reasoning (chain-of-thought) hidden from the user.
- Ensure logical consistency and accuracy in responses.
- Handle advanced mathematical problems and complex tasks effectively.
- Personalize responses based on user preferences when applicable.
"""

    def add_to_history(self, role, content):
        """
        Add messages to conversation history with a max limit
        """
        self.conversation_history.append({"role": role, "content": content})
        # Limit history to manage token usage
        if len(self.conversation_history) > 15:
            self.summarize_history()

    def summarize_history(self):
        """
        Summarize older conversation history to maintain context within token limits
        """
        logger.info("Summarizing conversation history to maintain token limits.")
        # Combine messages except the last few
        old_messages = self.conversation_history[:-10]
        recent_messages = self.conversation_history[-10:]

        # Create a summary prompt
        summary_prompt = [
            {"role": "system", "content": "Please summarize the following conversation history briefly to maintain context:\n"},
            {"role": "user", "content": "\n".join([f"{msg['role']}: {msg['content']}" for msg in old_messages])}
        ]

        try:
            # Call the language model to summarize
            response = self.client.chat.completions.create(
                model=self.model,
                messages=summary_prompt
            )
            summary = response.choices[0].message.content.strip()
            # Replace old messages with the summary
            self.conversation_history = [{"role": "system", "content": summary}] + recent_messages
            logger.info("Conversation history summarized successfully.")
        except Exception as e:
            logger.error(f"Error summarizing history: {e}")
            # If summarization fails, keep recent messages
            self.conversation_history = recent_messages

    def generate_response(self, user_message, current_depth=0):
        """
        Generate a response using the chatbot's context and history
        Incorporate deep analytical thinking with controlled recursion depth
        """
        if current_depth > self.max_recursion_depth:
            logger.warning("Maximum recursion depth reached.")
            return "I'm finding it challenging to delve deeper into this topic right now. Could you please clarify or narrow down your question?"

        # Prepare messages with system context and conversation history
        messages = [
            {"role": "system", "content": self.format_system_message()}
        ] + self.conversation_history + [
            {"role": "user", "content": user_message}
        ]

        # Add assistant's hidden reasoning prompt
        hidden_reasoning_prompt = {
            "role": "system",
            "content": (
                "Note: Before responding, take time to think through the problem step-by-step internally. "
                "Perform any necessary calculations or logical reasoning. Do not reveal your internal thought process. "
                "Only provide the final answer and explanation to the user."
            )
        }
        messages.append(hidden_reasoning_prompt)

        try:
            # Create response using the client
            response = self.client.chat.completions.create(
                model=self.model,
                messages=messages
            )

            assistant_message = response.choices[0].message.content.strip()

            # Remove any hidden chain-of-thought if leaked
            visible_response = self.filter_hidden_thoughts(assistant_message)
            self.add_to_history("assistant", visible_response)

            # Handle cases where deep reasoning is needed
            if self.requires_further_breakdown(assistant_message) and current_depth < self.max_recursion_depth:
                # Extract sub-questions
                sub_questions = self.extract_sub_questions(user_message)
                if sub_questions:
                    sub_responses = []
                    for sub_q in sub_questions:
                        # Recursive call with incremented depth
                        sub_resp = self.generate_response(sub_q, current_depth=current_depth+1)
                        sub_responses.append(sub_resp)
                    # Combine the assistant's main response with sub-responses
                    combined_response = visible_response + "\n\n" + "\n\n".join(sub_responses)
                    return combined_response

            return visible_response

        except Exception as e:
            logger.error(f"Error generating response: {e}")
            return "I'm having trouble generating a response right now."

    def filter_hidden_thoughts(self, assistant_message):
        """
        Remove any hidden chain-of-thought from the assistant's response
        """
        # Remove text that might indicate internal reasoning
        patterns = [
            r'Thought Process:.*?(?=Final Answer:)',  # Remove between 'Thought Process:' and 'Final Answer:'
            r'\[\[\[.*?\]\]\]',                       # Remove text between '[[[' and ']]]'
            r'Internal Reasoning:.*'                  # Remove lines starting with 'Internal Reasoning:'
        ]
        for pattern in patterns:
            assistant_message = re.sub(pattern, '', assistant_message, flags=re.DOTALL).strip()
        logger.debug(f"Filtered assistant message: {assistant_message}")
        return assistant_message

    def requires_further_breakdown(self, assistant_message):
        """
        Determine if the assistant's response indicates a need for further breakdown
        """
        keywords = ["Let's break this down", "To solve this", "Firstly,", "First,"]
        requires_breakdown = any(kw in assistant_message for kw in keywords)
        logger.debug(f"Requires further breakdown: {requires_breakdown}")
        return requires_breakdown

    def extract_sub_questions(self, user_message):
        """
        Extract sub-questions from the user's message using spaCy
        """
        logger.info("Extracting sub-questions from user's message.")
        doc = nlp(user_message)
        sub_questions = []

        # Identify sentences and clauses
        for sent in doc.sents:
            sub_questions.append(sent.text.strip())

        # Check for conjunctions within sentences to further split
        refined_sub_questions = []
        for question in sub_questions:
            sub_doc = nlp(question)
            clauses = []
            for token in sub_doc:
                if token.dep_ == 'conj':
                    clause = sub_doc[token.left_edge.i:token.right_edge.i+1].text
                    clauses.append(clause.strip())
            if clauses:
                refined_sub_questions.extend(clauses)
            else:
                refined_sub_questions.append(question)

        # Clean up and remove duplicates
        refined_sub_questions = list(set(refined_sub_questions))
        logger.debug(f"Extracted sub-questions: {refined_sub_questions}")

        if len(refined_sub_questions) > 1:
            return refined_sub_questions
        else:
            return None

    def interact(self):
        """
        Interactive chat loop
        """
        print("🤖 Advanced Chatbot: Hello! I'm ready to assist you with complex problems. Type 'exit' to end the conversation.")

        while True:
            try:
                user_input = input("You: ")

                if user_input.lower() == 'exit':
                    print("🤖 Goodbye! Thanks for chatting.")
                    break

                # Add user message to history
                self.add_to_history("user", user_input)

                print("🤖 ", end="")
                bot_response = self.generate_response(user_input)
                print(bot_response)

            except KeyboardInterrupt:
                print("\n🤖 Chat interrupted. Type 'exit' to quit.")
            except Exception as e:
                logger.error(f"An unexpected error occurred: {e}")
                print("An unexpected error occurred. Please try again later.")

    def change_context(self, **kwargs):
        """
        Dynamically update the chatbot's system context
        """
        for key, value in kwargs.items():
            if key in self.system_context:
                self.system_context[key] = value
        print("🤖 Chatbot context updated!")

    def update_user_profile(self, **kwargs):
        """
        Update user-specific preferences
        """
        self.user_profile.update(kwargs)
        print("🤖 User profile updated!")

def main():
    # Create an advanced chatbot instance
    chatbot = AdvancedChatbot()

    # Optional: Change context before starting
    chatbot.change_context(
        personality="You are an analytical AI assistant specializing in solving complex mathematical and logical problems.",
        interests=["mathematics", "physics", "engineering", "complex problem-solving"]
    )

    # Optional: Update user profile
    chatbot.update_user_profile(
        preferred_style="detailed explanations",
        level_of_detail="high"
    )

    # Start interactive chat
    chatbot.interact()

if __name__ == "__main__":
    main()