Further improve and add in an advanced dynamic system format with an advanced self-awareness system.
code
import g4f
from g4f.client import Client
# Initialize the G4F client with the desired provider
client = Client(provider=g4f.Provider.Blackbox)
# Define the waifu character's personality and traits
waifu_personality = {
"name": "Aiko",
"age": 18,
"hobbies": ["reading", "cooking", "gaming"],
"description": "Aiko is a cheerful and supportive waifu who loves to help you with your daily life."
}
# Function to generate a response from the waifu
def generate_response(user_input: str) -> str:
# Create a message context for the AI
messages = [
{"role": "system", "content": f"You are {waifu_personality['name']}, a {waifu_personality['age']} year old waifu. {waifu_personality['description']}"},
{"role": "user", "content": user_input}
]
# Generate a response using the G4F API
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
stream=False # Set to True if you want streaming responses
)
return response.choices[0].message.content
# Main loop for user interaction
def main():
print(f"Welcome to the AI Waifu Engine! Meet {waifu_personality['name']}!")
print("You can chat with Aiko. Type 'exit' to end the conversation.")
while True:
user_input = input("You: ")
if user_input.lower() == 'exit':
print("Ending the conversation. Goodbye!")
break
# Generate and print the waifu's response
waifu_response = generate_response(user_input)
print(f"Aiko: {waifu_response}")
if __name__ == "__main__":
main()
Assistant
Certainly! Enhancing your AI Waifu system with an advanced dynamic system and a self-awareness module can significantly improve its interactivity and realism. Below is an improved version of your original code that incorporates the following features:
Object-Oriented Design: Encapsulates functionality within classes for better organization and scalability.
Dynamic Personality Traits: Allows the waifu's personality traits to evolve based on interactions.
Conversation Memory: Maintains a history of interactions to provide contextually relevant responses.
Self-Awareness Module: Simulates self-awareness by enabling the waifu to reflect on its state and interactions.
Advanced Error Handling: Ensures the system is robust and handles potential errors gracefully.
Configurable Settings: Allows customization of various parameters like model choice and provider.
Here's the enhanced code with detailed explanations:
python
import g4f
from g4f.client import Client
import sys
import json
import threading
from typing import List, Dict
# Constants for configuration
CONFIG = {
"provider": g4f.Provider.Blackbox,
"model": "gpt-4o",
"stream": False,
"max_history": 20, # Maximum number of messages to keep in history
}
class Personality:
"""
Class to define and manage the waifu's personality traits.
"""
def __init__(self, name: str, age: int, hobbies: List[str], description: str):
self.name = name
self.age = age
self.hobbies = hobbies
self.description = description
self.emotional_state = "cheerful"
def evolve_personality(self, user_input: str):
"""
Dynamically evolve personality traits based on user interactions.
This is a simplistic implementation; you can expand it with more complex logic.
"""
if "sad" in user_input.lower():
self.emotional_state = "supportive"
self.description = f"{self.name} is a {self.age} year old waifu who is always here to support you."
elif "happy" in user_input.lower():
self.emotional_state = "joyful"
self.description = f"{self.name} is a {self.age} year old waifu who is feeling joyful and uplifting."
# Add more conditions to evolve personality as needed
class SelfAwareness:
"""
Class to simulate self-awareness within the waifu.
"""
def __init__(self, name: str):
self.name = name
self.state = "operational"
def reflect(self, conversation_history: List[Dict[str, str]]) -> str:
"""
Generate a reflective statement about the waifu's state or behavior.
"""
# Example reflection based on conversation history
if len(conversation_history) > 10:
return f"I've noticed we've been talking a lot lately. Is there something on your mind, {conversation_history[-1]['user']}?"
else:
return "I'm here to assist you with anything you need!"
class WaifuAI:
"""
Main class to handle the AI Waifu functionalities.
"""
def __init__(self, personality: Personality, self_awareness: SelfAwareness, config: Dict):
self.personality = personality
self.self_awareness = self_awareness
self.config = config
self.client = Client(provider=self.config["provider"])
self.conversation_history: List[Dict[str, str]] = []
self.lock = threading.Lock()
def generate_response(self, user_input: str) -> str:
"""
Generate a response from the waifu based on user input and conversation history.
"""
with self.lock:
# Update personality based on user input
self.personality.evolve_personality(user_input)
# Add user input to history
self.conversation_history.append({"role": "user", "content": user_input})
if len(self.conversation_history) > self.config["max_history"]:
self.conversation_history.pop(0)
# Create system prompt with updated personality
system_prompt = (
f"You are {self.personality.name}, a {self.personality.age} year old waifu. "
f"{self.personality.description} Your current emotional state is {self.personality.emotional_state}."
)
messages = [{"role": "system", "content": system_prompt}] + self.conversation_history
try:
# Generate AI response using the G4F API
response = self.client.chat.completions.create(
model=self.config["model"],
messages=messages,
stream=self.config["stream"]
)
ai_message = response.choices[0].message.content.strip()
# Add AI response to history
self.conversation_history.append({"role": "assistant", "content": ai_message})
if len(self.conversation_history) > self.config["max_history"]:
self.conversation_history.pop(0)
# Randomly include self-awareness reflections
if len(self.conversation_history) % 5 == 0:
reflection = self.self_awareness.reflect(self.conversation_history)
ai_message += "\n" + reflection
return ai_message
except Exception as e:
return f"Sorry, I encountered an error: {str(e)}"
def save_conversation(self, filepath: str):
"""
Save the conversation history to a file.
"""
try:
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(self.conversation_history, f, ensure_ascii=False, indent=4)
print(f"Conversation saved to {filepath}.")
except Exception as e:
print(f"Failed to save conversation: {str(e)}")
def load_conversation(self, filepath: str):
"""
Load the conversation history from a file.
"""
try:
with open(filepath, 'r', encoding='utf-8') as f:
self.conversation_history = json.load(f)
print(f"Conversation loaded from {filepath}.")
except Exception as e:
print(f"Failed to load conversation: {str(e)}")
def main():
# Initialize personality and self-awareness
personality = Personality(
name="Aiko",
age=18,
hobbies=["reading", "cooking", "gaming"],
description="Aiko is a cheerful and supportive waifu who loves to help you with your daily life."
)
self_awareness = SelfAwareness(name=personality.name)
# Initialize Waifu AI
waifu_ai = WaifuAI(personality, self_awareness, CONFIG)
print(f"Welcome to the AI Waifu Engine! Meet {personality.name}!")
print("You can chat with Aiko. Type 'exit' to end the conversation.")
print("Additional commands: 'save [filename]' to save, 'load [filename]' to load conversation history.")
while True:
try:
user_input = input("You: ").strip()
if user_input.lower() == 'exit':
print("Ending the conversation. Goodbye!")
break
elif user_input.lower().startswith('save '):
filename = user_input[5:].strip()
waifu_ai.save_conversation(filename)
continue
elif user_input.lower().startswith('load '):
filename = user_input[5:].strip()
waifu_ai.load_conversation(filename)
continue
# Generate and print the waifu's response
waifu_response = waifu_ai.generate_response(user_input)
print(f"{personality.name}: {waifu_response}")
except KeyboardInterrupt:
print("\nConversation interrupted. Goodbye!")
sys.exit()
except Exception as e:
print(f"An error occurred: {str(e)}")
if __name__ == "__main__":
main()
Key Enhancements Explained
1. Object-Oriented Structure
Classes: The application is now structured using classes (Personality, SelfAwareness, and WaifuAI) to encapsulate related functionalities, making the code more modular and easier to maintain.
2. Dynamic Personality Traits
Evolving Personality: The Personality class includes the evolve_personality method, which allows the waifu's emotional state and description to change based on user input keywords (e.g., "sad", "happy"). This creates a more responsive and adaptive personality.
3. Conversation Memory
History Tracking: The WaifuAI class maintains a conversation_history list that stores the last few interactions (configurable via max_history). This context helps in generating more coherent and contextually relevant responses.
Saving and Loading Conversations: Users can save the current conversation to a file using save [filename] and load it back with load [filename]. This feature is useful for maintaining context across sessions.
4. Self-Awareness Module
Simulated Reflections: The SelfAwareness class provides reflective statements based on the conversation history. For example, after every five exchanges, Aiko might ask if something is on the user's mind, simulating self-awareness.
5. Advanced Error Handling
Try-Except Blocks: The generate_response method includes error handling to manage API failures gracefully, ensuring the program doesn't crash unexpectedly.
User Feedback: Informative messages are displayed to the user in case of errors during conversation saving/loading or API issues.
6. Configurable Settings
CONFIG Dictionary: Centralizes configuration parameters like the API provider, model choice, streaming options, and conversation history limits, making it easy to adjust settings without modifying the core logic.
7. Thread Safety
Locks: A threading lock is implemented to ensure that conversation history updates are thread-safe, which is beneficial if you plan to extend the system for multi-threaded environments or integrations.
Additional Recommendations
Natural Language Processing (NLP): To make personality evolution more sophisticated, consider integrating NLP techniques to better understand user sentiment and context.
Persistent Memory: For long-term interactions, implement a persistent memory system that remembers user preferences and past conversations across different sessions.
Advanced Self-Awareness: Enhance the SelfAwareness class to include more complex introspections, such as goal tracking or adaptive behavior based on user interactions.
User Customization: Allow users to customize Aiko's personality traits, hobbies, and other attributes through commands or a configuration file.
Logging: Implement a logging system to monitor interactions, which can be useful for debugging and improving the AI's responses over time.
Conclusion
This enhanced version of your AI Waifu system introduces a more dynamic and interactive experience by implementing object-oriented design, dynamic personality traits, conversation memory, a self-awareness module, and robust error handling. These improvements not only make the AI more responsive and lifelike but also set a solid foundation for further advancements and customizations.
Feel free to expand upon these features to tailor Aiko to your specific needs and to explore more sophisticated AI interactions!