I'll help you create an advanced AI waifu engine using g4f that incorporates best practices and proper error handling. This implementation will use the Client API, which is the recommended modern approach for g4f.
Here's a well-engineered solution:
python
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-3.5-turbo",
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="[Redacted Person]",
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-3.5-turbo",
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())
This implementation includes several advanced features:
Personality System: The WaifuPersonality class allows creating different AI personalities with specific traits and backgrounds.
Conversation Memory: The ConversationMemory class maintains chat history and provides relevant context for more coherent conversations.
Logging System: Comprehensive logging of operations and errors for debugging and monitoring.
Error Handling: Robust error handling for various failure scenarios.
Conversation Persistence: Ability to save conversations to JSON files for later reference.
Asynchronous Operation: Uses async/await for better performance.
To use this script:
Install the required g4f package:
bash
pip install -U g4f[all]
Run the script:
bash
python waifu_engine.py
You can customize the personality by modifying the traits and background in the main() function. The script creates a tsundere personality by default, but you can create any type of personality you want.
The engine will:
Maintain conversation context
Stay in character based on the defined personality
Log all interactions
Save conversations to JSON files
Handle errors gracefully
Provide natural, engaging responses
You can extend this further by:
Adding more personality templates
Implementing different conversation strategies
Adding voice output using text-to-speech
Creating a GUI interface
Adding sentiment analysis for better emotional responses
Implementing multiple AI models support
Remember that the actual responses will depend on the AI model's capabilities and the provider's availability.