Further improve and add in more waifu intentions with more engineering.

```
from typing import Optional, List, Dict
import asyncio
import json
import logging
from datetime import datetime
from pathlib import Path
from g4f.client import Client
from g4f.errors import ProviderNotWorkingError

class WaifuPersonality:
    def __init__(self, name: str, traits: List[str], background: str):
        self.name = name
        self.traits = traits
        self.background = background
        
    def get_system_prompt(self) -> str:
        return f"""You are {self.name}, an AI companion with the following traits: {', '.join(self.traits)}.
Background: {self.background}
Interact in a natural, engaging way while staying in character. Express emotions and reactions appropriately.
Keep responses concise but meaningful."""

class ConversationMemory:
    def __init__(self, max_history: int = 10):
        self.history: List[Dict] = []
        self.max_history = max_history
        
    def add_exchange(self, user_msg: str, ai_response: str):
        timestamp = datetime.now().isoformat()
        self.history.append({
            "timestamp": timestamp,
            "user": user_msg,
            "assistant": ai_response
        })
        if len(self.history) > self.max_history:
            self.history.pop(0)
            
    def get_context(self) -> str:
        if not self.history:
            return ""
        return "\n".join([
            f"Previous exchange {i+1}:",
            f"User: {exchange['user']}", 
            f"Assistant: {exchange['assistant']}"
            for i, exchange in enumerate(self.history[-3:]) # Only use last 3 exchanges for context
        ])

class WaifuEngine:
    def __init__(
        self,
        personality: WaifuPersonality,
        model: str = "gpt-4o",
        conversation_memory: Optional[ConversationMemory] = None,
        logs_path: Optional[Path] = None
    ):
        self.client = Client()
        self.personality = personality
        self.model = model
        self.memory = conversation_memory or ConversationMemory()
        
        # Setup logging
        self.logger = logging.getLogger("WaifuEngine")
        self.logger.setLevel(logging.INFO)
        
        if logs_path:
            handler = logging.FileHandler(logs_path / "waifu_engine.log")
            handler.setFormatter(logging.Formatter(
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
            ))
            self.logger.addHandler(handler)

    async def get_response(self, user_input: str) -> str:
        """Generate a response to user input using the configured personality."""
        try:
            messages = [
                {"role": "system", "content": self.personality.get_system_prompt()},
                {"role": "system", "content": f"Current context:\n{self.memory.get_context()}"},
                {"role": "user", "content": user_input}
            ]

            response = await self.client.chat.completions.create(
                model=self.model,
                messages=messages,
                max_tokens=300,
                temperature=0.7
            )
            
            ai_response = response.choices[0].message.content
            self.memory.add_exchange(user_input, ai_response)
            self.logger.info(f"Generated response for input: {user_input[:50]}...")
            
            return ai_response

        except ProviderNotWorkingError as e:
            self.logger.error(f"Provider error: {str(e)}")
            return "I'm having trouble connecting right now. Please try again in a moment."
            
        except Exception as e:
            self.logger.error(f"Unexpected error: {str(e)}")
            return "Something went wrong. Please try again."

    def save_conversation(self, path: Path):
        """Save the current conversation history to a JSON file."""
        try:
            with open(path / f"conversation_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json", 'w') as f:
                json.dump(self.memory.history, f, indent=2)
            self.logger.info("Conversation saved successfully")
        except Exception as e:
            self.logger.error(f"Error saving conversation: {str(e)}")

async def main():
    # Create a tsundere waifu personality
    tsundere = WaifuPersonality(
        name="Sakura",
        traits=["tsundere", "intelligent", "caring beneath a tough exterior"],
        background="A brilliant computer science student who acts tough but secretly enjoys helping others."
    )
    
    # Initialize the engine
    engine = WaifuEngine(
        personality=tsundere,
        model="gpt-4o",
        logs_path=Path("logs")
    )
    
    print(f"Chatting with {tsundere.name}. Type 'quit' to exit.")
    
    while True:
        user_input = input("\nYou: ").strip()
        
        if user_input.lower() == 'quit':
            # Save conversation before exiting
            engine.save_conversation(Path("conversations"))
            break
            
        response = await engine.get_response(user_input)
        print(f"\n{tsundere.name}: {response}")

if __name__ == "__main__":
    # Create necessary directories
    Path("logs").mkdir(exist_ok=True)
    Path("conversations").mkdir(exist_ok=True)
    
    # Run the main loop
    asyncio.run(main())