Further improve and add in more waifu intentions with more engineering. ` from typing…
- User
Further improve and add in more waifu intentions with more engineering.
code - Assistant
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())
Certainly! Let's enhance your WaifuEngine to support more nuanced interactions, additional personality traits, and improved engineering practices. Below are the key improvements we'll implement:
Expanded Personality Traits and Intentions:
Enhanced Conversation Memory:
Improved Logging and Configuration:
Modular Design:
Asynchronous Handling and Error Recovery:
User-Friendly Features:
Below is the refactored and enhanced code incorporating these improvements:
from typing import Optional, List, Dict, Callable
import asyncio
import json
import logging
import yaml
from datetime import datetime
from pathlib import Path
from g4f.client import Client
from g4f.errors import ProviderNotWorkingError
# Configuration Manager
class ConfigManager:
def __init__(self, config_path: Path):
self.config_path = config_path
self.config = self.load_config()
def load_config(self) -> Dict:
if not self.config_path.exists():
raise FileNotFoundError(f"Configuration file not found at {self.config_path}")
with open(self.config_path, 'r') as f:
return yaml.safe_load(f)
def get(self, key: str, default=None):
return self.config.get(key, default)
# Personality Definitions
class WaifuPersonality:
def __init__(self, name: str, traits: List[str], background: str, intentions: Dict[str, str]):
self.name = name
self.traits = traits
self.background = background
self.intentions = intentions # Specific prompts or behaviors based on intents
def get_system_prompt(self) -> str:
traits_formatted = ', '.join(self.traits)
return (
f"You are {self.name}, an AI companion with the following traits: {traits_formatted}.\n"
f"Background: {self.background}\n"
"Interact in a natural, engaging way while staying in character. "
"Express emotions and reactions appropriately. Keep responses concise but meaningful."
)
# Conversation Memory with Persistent Storage
class ConversationMemory:
def __init__(self, max_history: int = 20, memory_path: Optional[Path] = None):
self.history: List[Dict] = []
self.max_history = max_history
self.memory_path = memory_path
if memory_path and memory_path.exists():
self.load_memory(memory_path)
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, num_exchanges: int = 5) -> str:
if not self.history:
return ""
selected_history = self.history[-num_exchanges:]
context = "\n".join([
f"Exchange {i+1}:",
f"User: {exchange['user']}",
f"{self.get_formatted_assistant(exchange['assistant'])}"
for i, exchange in enumerate(selected_history)
])
return context
@staticmethod
def get_formatted_assistant(response: str) -> str:
return f"Assistant: {response}"
def save_memory(self, path: Path):
try:
with open(path, 'w') as f:
json.dump(self.history, f, indent=2)
except Exception as e:
logging.error(f"Error saving memory: {e}")
def load_memory(self, path: Path):
try:
with open(path, 'r') as f:
self.history = json.load(f)
except Exception as e:
logging.error(f"Error loading memory: {e}")
# Command Handler
class CommandHandler:
def __init__(self):
self.commands: Dict[str, Callable[[List[str]], str]] = {
'change_personality': self.change_personality,
'view_history': self.view_history,
'save': self.save_conversation,
'help': self.help_command
}
def handle(self, user_input: str, engine: 'WaifuEngine') -> Optional[str]:
if not user_input.startswith('/'):
return None
parts = user_input[1:].split()
command = parts[0]
args = parts[1:]
handler = self.commands.get(command)
if handler:
return handler(args, engine)
else:
return "Unknown command. Type /help for a list of commands."
def change_personality(self, args: List[str], engine: 'WaifuEngine') -> str:
if not args:
return "Please specify a personality name. Available personalities: " + ", ".join(engine.available_personalities.keys())
personality_name = args[0].capitalize()
personality = engine.available_personalities.get(personality_name)
if personality:
engine.set_personality(personality)
return f"Personality changed to {personality_name}."
else:
return f"Personality '{personality_name}' not found. Available personalities: " + ", ".join(engine.available_personalities.keys())
def view_history(self, args: List[str], engine: 'WaifuEngine') -> str:
if not engine.memory.history:
return "No conversation history available."
history_str = "\n".join([
f"[{exchange['timestamp']}] You: {exchange['user']}\n{engine.personality.name}: {exchange['assistant']}"
for exchange in engine.memory.history
])
return history_str
def save_conversation(self, args: List[str], engine: 'WaifuEngine') -> str:
path = Path("conversations")
path.mkdir(exist_ok=True)
engine.save_conversation(path)
return "Conversation saved successfully."
def help_command(self, args: List[str], engine: 'WaifuEngine') -> str:
return (
"Available commands:\n"
"/change_personality [name] - Change the waifu's personality.\n"
"/view_history - View the conversation history.\n"
"/save - Save the current conversation.\n"
"/help - Show this help message."
)
# Waifu Engine with Enhanced Features
class WaifuEngine:
def __init__(
self,
personalities: Dict[str, WaifuPersonality],
default_personality: str = "Tsundere",
model: str = "gpt-4o",
conversation_memory: Optional[ConversationMemory] = None,
logs_path: Optional[Path] = None
):
self.client = Client()
self.available_personalities = personalities
self.set_personality(self.available_personalities.get(default_personality))
self.model = model
self.memory = conversation_memory or ConversationMemory()
self.command_handler = CommandHandler()
# Setup logging
self.logger = logging.getLogger("WaifuEngine")
self.logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
if logs_path:
logs_path.mkdir(parents=True, exist_ok=True)
handler = logging.FileHandler(logs_path / "waifu_engine.log")
handler.setFormatter(formatter)
self.logger.addHandler(handler)
else:
# Log to console if no path provided
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
self.logger.addHandler(console_handler)
def set_personality(self, personality: Optional[WaifuPersonality]):
if personality:
self.personality = personality
self.logger.info(f"Personality set to {self.personality.name}")
else:
raise ValueError("Personality cannot be None.")
async def get_response(self, user_input: str) -> str:
"""Generate a response to user input using the configured personality."""
# Check for commands
command_response = self.command_handler.handle(user_input, self)
if command_response:
return command_response
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.strip()
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:
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
file_path = path / f"conversation_{timestamp}.json"
with open(file_path, 'w') as f:
json.dump(self.memory.history, f, indent=2)
self.logger.info(f"Conversation saved to {file_path}")
except Exception as e:
self.logger.error(f"Error saving conversation: {str(e)}")
# Initialize Personalities
def initialize_personalities() -> Dict[str, WaifuPersonality]:
return {
"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.",
intentions={
"greeting": "Oh, it's you again. What do you want?",
"farewell": "Fine, I don't want to talk to you anymore."
}
),
"Yandere": WaifuPersonality(
name="Yuki",
traits=["yandere", "possessive", "obsessively loving"],
background="A sweet girl who will go to any lengths to protect her loved ones.",
intentions={
"greeting": "Hi there! I've been waiting for you.",
"farewell": "Don't go... Please stay with me."
}
),
"Kuudere": WaifuPersonality(
name="Mika",
traits=["kuudere", "calm", "emotionally reserved"],
background="A cool and composed individual who maintains a serene demeanor.",
intentions={
"greeting": "Hello. How can I assist you today?",
"farewell": "Goodbye. Take care."
}
),
# Add more personalities as needed
}
# Main Function
async def main():
# Load configuration if needed (e.g., for API keys)
# config = ConfigManager(Path("config.yaml"))
# Initialize personalities
personalities = initialize_personalities()
# Initialize the engine
engine = WaifuEngine(
personalities=personalities,
default_personality="Tsundere",
model="gpt-4o",
conversation_memory=ConversationMemory(),
logs_path=Path("logs")
)
print(f"Chatting with {engine.personality.name}. Type '/help' for commands or 'quit' to exit.")
while True:
try:
user_input = input("\nYou: ").strip()
except (EOFError, KeyboardInterrupt):
print("\nExiting...")
engine.save_conversation(Path("conversations"))
break
if user_input.lower() == 'quit':
# Save conversation before exiting
engine.save_conversation(Path("conversations"))
print("Conversation saved. Goodbye!")
break
response = await engine.get_response(user_input)
print(f"\n{engine.personality.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())
Multiple Personalities:
initialize_personalities function sets up different personalities (Tsundere, Yandere, Kuudere). Each personality has unique traits, background, and specific intentions for predefined commands like greetings and farewells./change_personality command followed by the desired personality name.Command Handling:
/ to differentiate them from regular chat messages./change_personality [name]: Switches the waifu's personality./view_history: Displays the conversation history./save: Saves the current conversation manually./help: Shows a list of available commands.Enhanced Conversation Memory:
ConversationMemory class can load existing conversations from a file if available, allowing continuity across sessions.max_history to 20 for a more extended context, which can be tailored based on performance and responsiveness.save_memory and load_memory allow for easy saving and loading of conversation history.Improved Logging:
INFO, ERROR) to categorize logs effectively.Error Handling and Resilience:
ProviderNotWorkingError to inform users about connectivity issues.Configuration File: Consider using a config.yaml or config.json to manage settings like API keys, default personalities, and other runtime configurations. This promotes flexibility and easier adjustments without modifying the code.
Testing: Implement unit tests for each component to ensure reliability and facilitate maintenance.
Security: If deploying this application, ensure that sensitive information (like API keys) is securely managed, possibly using environment variables or secure storage solutions.
User Interface: For a more engaging experience, consider developing a graphical user interface (GUI) or integrating with messaging platforms like Discord or Slack.
Scalability: Depending on the expected usage, you might want to handle multiple concurrent conversations, potentially using more advanced asynchronous patterns or frameworks.
This refactored version of your WaifuEngine provides a more versatile, maintainable, and user-friendly framework for creating engaging AI companions with varied personalities and enhanced interactions.
Not yet included in a published release.
EOFError and KeyboardInterrupt to save conversations before exiting.Modular and Maintainable Code Structure:
ConfigManager, WaifuPersonality, ConversationMemory, CommandHandler, and WaifuEngine).User-Friendly Features: