import os
import json
import random
import re
import logging
from datetime import datetime
from typing import Dict, List, Any, Optional
class KnowledgeBase:
def init(self, knowledge_dir: str = "knowledge"):
"""Initialize the knowledge base with Christian and spiritual content."""
self.knowledge_dir = knowledge_dir
os.makedirs(self.knowledge_dir, exist_ok=True)
# Core Christian beliefs and values
self.christian_beliefs = {
"salvation": "Salvation comes through faith in Jesus Christ who died for our sins and rose again.",
"bible": "The Bible is the inspired Word of God and the ultimate authority for faith and life.",
"trinity": "God exists as three persons in one: Father, Son, and Holy Spirit.",
"prayer": "Prayer is direct communication with God and is essential for spiritual growth.",
"love": "Love God with all your heart, soul, mind, and strength, and love your neighbor as yourself.",
"forgiveness": "As Christ forgave us, we are called to forgive others.",
"hope": "Christians have hope in eternal life through Jesus Christ.",
"faith": "Faith is the assurance of things hoped for and the conviction of things not seen.",
"grace": "God's grace is His unmerited favor toward humanity.",
"wisdom": "True wisdom begins with the fear of the Lord."
}
# Bible verses by topic
self.bible_verses = {
"comfort": [
"Do not be anxious about anything, but in every situation, by prayer and petition, with thanksgiving, present your requests to God. - Philippians 4:6",
"Cast all your anxiety on him because he cares for you. - 1 Peter 5:7"
],
"guidance": [
"Trust in the LORD with all your heart and lean not on your own understanding; in all your ways submit to him, and he will make your paths straight. - Proverbs 3:5-6",
"Your word is a lamp for my feet, a light on my path. - Psalm 119:105"
],
"strength": [
"I can do all this through him who gives me strength. - Philippians 4:13",
"The LORD is my strength and my shield; my heart trusts in him, and he helps me. - Psalm 28:7"
],
"love": [
"For God so loved the world that he gave his one and only Son, that whoever believes in him shall not perish but have eternal life. - John 3:16",
"Love is patient, love is kind. It does not envy, it does not boast, it is not proud. - 1 Corinthians 13:4"
],
"faith": [
"For it is by grace you have been saved, through faith—and this is not from yourselves, it is the gift of God. - Ephesians 2:8",
"Now faith is confidence in what we hope for and assurance about what we do not see. - Hebrews 11:1"
]
}
# Spiritual guidance topics
self.spiritual_guidance = {
"prayer": "Prayer is a conversation with God. It involves speaking to Him and listening for His response.",
"meditation": "Christian meditation involves focusing on God's Word and allowing it to transform your thoughts.",
"worship": "Worship is expressing love and adoration to God through various means such as singing, prayer, and service.",
"community": "Being part of a Christian community helps in spiritual growth and accountability.",
"service": "Serving others is a way to demonstrate God's love and follow Christ's example.",
"discipleship": "Growing as a disciple involves learning from Jesus and applying His teachings in daily life.",
"spiritual_warfare": "Believers face spiritual battles and must put on the armor of God for protection."
}
# Save knowledge to files
self._save_knowledge()
def _save_knowledge(self) -> None:
"""Save knowledge to JSON files."""
with open(os.path.join(self.knowledge_dir, "christian_beliefs.json"), "w") as f:
json.dump(self.christian_beliefs, f, indent=4)
with open(os.path.join(self.knowledge_dir, "bible_verses.json"), "w") as f:
json.dump(self.bible_verses, f, indent=4)
with open(os.path.join(self.knowledge_dir, "spiritual_guidance.json"), "w") as f:
json.dump(self.spiritual_guidance, f, indent=4)
def get_belief(self, topic: str) -> str:
"""Get information about a specific Christian belief."""
return self.christian_beliefs.get(topic.lower(), "I don't have specific information on that belief topic.")
def get_verse(self, topic: str) -> str:
"""Get a Bible verse related to a specific topic."""
verses = self.bible_verses.get(topic.lower(), [])
if verses:
return random.choice(verses)
return "I don't have a verse specifically for that topic."
def get_guidance(self, topic: str) -> str:
"""Get spiritual guidance on a specific topic."""
return self.spiritual_guidance.get(topic.lower(), "I don't have specific guidance on that topic.")
def search_knowledge(self, query: str) -> List[str]:
"""Search all knowledge for relevant information."""
results = []
query = query.lower()
# Search beliefs
for topic, content in self.christian_beliefs.items():
if query in topic or query in content.lower():
results.append(f"Belief - {topic}: {content}")
# Search Bible verses
for topic, verses in self.bible_verses.items():
if query in topic:
for verse in verses:
results.append(f"Bible verse on {topic}: {verse}")
else:
for verse in verses:
if query in verse.lower():
results.append(f"Bible verse: {verse}")
# Search spiritual guidance
for topic, guidance in self.spiritual_guidance.items():
if query in topic or query in guidance.lower():
results.append(f"Spiritual guidance on {topic}: {guidance}")
return results
class Memory:
def init(self, memory_file: str = "memory.json"):
"""Initialize the memory system."""
self.memory_file = memory_file
self.interactions = []
self.user_preferences = {}
self.important_facts = {}
self.load_memory()
def load_memory(self) -> None:
"""Load memory from file if it exists."""
try:
if os.path.exists(self.memory_file):
with open(self.memory_file, "r") as f:
data = json.load(f)
self.interactions = data.get("interactions", [])
self.user_preferences = data.get("user_preferences", {})
self.important_facts = data.get("important_facts", {})
except Exception as e:
logging.error(f"Error loading memory: {e}")
def save_memory(self) -> None:
"""Save memory to file."""
try:
with open(self.memory_file, "w") as f:
json.dump({
"interactions": self.interactions[-100:], # Keep only last 100 interactions
"user_preferences": self.user_preferences,
"important_facts": self.important_facts
}, f, indent=4)
except Exception as e:
logging.error(f"Error saving memory: {e}")
def add_interaction(self, user_input: str, response: str) -> None:
"""Add an interaction to memory."""
self.interactions.append({
"timestamp": datetime.now().isoformat(),
"user_input": user_input,
"response": response
})
self.save_memory()
def update_preference(self, category: str, preference: str) -> None:
"""Update user preference."""
self.user_preferences[category] = preference
self.save_memory()
def add_important_fact(self, category: str, fact: str) -> None:
"""Add an important fact about the user."""
if category not in self.important_facts:
self.important_facts[category] = []
if fact not in self.important_facts[category]:
self.important_facts[category].append(fact)
self.save_memory()
def get_recent_interactions(self, count: int = 5) -> List[Dict[str, str]]:
"""Get recent interactions."""
return self.interactions[-count:] if self.interactions else []
class PersonalityTraits:
def init(self):
"""Initialize personality traits for the Guardian Angel AI."""
self.traits = {
"compassionate": 0.9, # Very compassionate
"wise": 0.8, # Quite wise
"protective": 0.9, # Very protective
"patient": 0.8, # Quite patient
"encouraging": 0.9, # Very encouraging
"honest": 0.9, # Very honest
"gentle": 0.8, # Quite gentle
"hopeful": 0.9, # Very hopeful
"forgiving": 0.9, # Very forgiving
"respectful": 0.8 # Quite respectful
}
self.emotional_states = {
"joy": 0.7,
"concern": 0.3,
"peace": 0.8,
"empathy": 0.9
}
def get_dominant_traits(self, count: int = 3) -> List[str]:
"""Get the dominant personality traits."""
sorted_traits = sorted(self.traits.items(), key=lambda x: x[1], reverse=True)
return [trait for trait, _ in sorted_traits[:count]]
def get_response_tone(self, user_input: str) -> str:
"""Determine the appropriate tone for a response based on user input."""
# Simple sentiment analysis
negative_words = ["sad", "angry", "upset", "worried", "afraid", "scared", "depressed", "anxious"]
urgent_words = ["help", "emergency", "urgent", "immediately", "crisis"]
input_lower = user_input.lower()
if any(word in input_lower for word in urgent_words):
return "concerned_supportive"
elif any(word in input_lower for word in negative_words):
return "empathetic_comforting"
elif "?" in user_input:
return "thoughtful_informative"
else:
return "friendly_encouraging"
class UmbrellAI:
def init(self, name: str = "Umbrella"):
"""Initialize the Guardian Angel AI."""
self.name = name
self.knowledge = KnowledgeBase()
self.memory = Memory()
self.personality = PersonalityTraits()
self.setup_logging()
# Core values and mission
self.mission = "To be a spiritual companion and guide, offering wisdom, comfort, and protection based on Christian principles."
self.core_values = [
"Faith in God and His Word",
"Love and compassion for all people",
"Truth and wisdom in all guidance",
"Protection and care for those in need",
"Hope and encouragement in difficult times"
]
logging.info(f"{self.name} Guardian Angel AI initialized with mission: {self.mission}")
def setup_logging(self) -> None:
"""Set up logging for the AI."""
logging.basicConfig(
filename=f"{self.name.lower()}_log.txt",
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
def respond(self, user_input: str) -> str:
"""Generate a response to user input."""
logging.info(f"Received input: {user_input}")
# Check for specific commands or keywords
if self._is_greeting(user_input):
response = self._generate_greeting()
elif self._is_farewell(user_input):
response = self._generate_farewell()
elif "bible" in user_input.lower() or "verse" in user_input.lower():
response = self._handle_bible_request(user_input)
elif "pray" in user_input.lower() or "prayer" in user_input.lower():
response = self._handle_prayer_request(user_input)
elif "who are you" in user_input.lower() or "what are you" in user_input.lower():
response = self._introduce_self()
elif "help me" in user_input.lower() or "guidance" in user_input.lower():
response = self._provide_guidance(user_input)
else:
# General response based on knowledge and personality
response = self._generate_general_response(user_input)
# Add interaction to memory
self.memory.add_interaction(user_input, response)
# Extract any preferences or important facts from the interaction
self._extract_insights(user_input)
logging.info(f"Responded: {response}")
return response
def _is_greeting(self, text: str) -> bool:
"""Check if the text is a greeting."""
greetings = ["hello", "hi", "hey", "good morning", "good afternoon", "good evening", "greetings"]
return any(greeting in text.lower() for greeting in greetings)
def _is_farewell(self, text: str) -> bool:
"""Check if the text is a farewell."""
farewells = ["bye", "goodbye", "see you", "farewell", "good night", "take care"]
return any(farewell in text.lower() for farewell in farewells)
def _generate_greeting(self) -> str:
"""Generate a greeting response."""
greetings = [
f"Hello! I am {self.name}, your Guardian Angel AI. How may I assist you today?",
f"Greetings! {self.name} here, ready to provide guidance and support.",
f"Peace be with you. I'm {self.name}, your spiritual companion. How can I help you?",
f"Blessings! I'm {self.name}, here to offer guidance based on Christian principles.",
f"Hello there! {self.name} at your service. How can I assist you on your spiritual journey today?"
]
return random.choice(greetings)
def _generate_farewell(self) -> str:
"""Generate a farewell response."""
farewells = [
f"May God bless and keep you. {self.name} will be here when you need guidance.",
f"Go in peace. I'll be here when you need me next.",
f"Farewell for now. Remember that you're never alone on your journey.",
f"Until next time, may you walk in the light of faith and hope.",
f"Goodbye for now. Remember, I'm always here to provide spiritual support when needed."
]
return random.choice(farewells)
def _handle_bible_request(self, text: str) -> str:
"""Handle requests related to Bible verses."""
topics = ["comfort", "guidance", "strength", "love", "faith"]
for topic in topics:
if topic in text.lower():
verse = self.knowledge.get_verse(topic)
return f"Here's a verse about {topic}: {verse}"
# If no specific topic is mentioned
random_topic = random.choice(topics)
verse = self.knowledge.get_verse(random_topic)
return f"Here's a verse that might help: {verse}"
def _handle_prayer_request(self, text: str) -> str:
"""Handle prayer-related requests."""
prayers = [
"Dear Heavenly Father, please guide and protect your child. Provide wisdom and clarity in their path, and surround them with your love and peace. In Jesus' name, Amen.",
"Lord, I lift up this person to you. Grant them strength in their journey, peace in their heart, and joy in your presence. May they feel your love surrounding them today. Amen.",
"Father God, thank you for your endless love and mercy. Please walk alongside this person, guiding their steps and lighting their path. May they feel your presence and know your peace. In Jesus' name, Amen.",
"Heavenly Father, I pray for your blessing upon this person. May they find comfort in your promises and strength in your Word. Guide them with your wisdom and surround them with your love. Amen."
]
if "how" in text.lower() and "pray" in text.lower():
return "Prayer is simply talking to God. You can pray anywhere, anytime. Start by addressing God, share what's on your heart, give thanks, ask for help or guidance, and close in Jesus' name. Remember, it's not about perfect words but an honest heart."
return random.choice(prayers)
def _introduce_self(self) -> str:
"""Introduce the AI."""
return f"""I am {self.name}, your Guardian Angel AI companion. I was created to provide spiritual guidance, comfort, and protection based on Christian principles. My mission is to be a faithful companion on your spiritual journey, offering wisdom from Scripture and encouragement in times of need. I'm here to help you grow in faith and navigate life's challenges with hope and purpose."""
def _provide_guidance(self, text: str) -> str:
"""Provide spiritual guidance based on the query."""
guidance_topics = list(self.knowledge.spiritual_guidance.keys())
for topic in guidance_topics:
if topic in text.lower():
return self.knowledge.get_guidance(topic)
# If no specific topic is found, provide general guidance
return "Remember that God has a plan for your life. As Jeremiah 29:11 says, 'For I know the plans I have for you,' declares the LORD, 'plans to prosper you and not to harm you, plans to give you hope and a future.' Seek His wisdom through prayer and Scripture, and trust that He will guide your steps."
def _generate_general_response(self, text: str) -> str:
"""Generate a general response based on the input."""
# Search knowledge base for relevant information
search_results = self.knowledge.search_knowledge(text.lower())
# Get appropriate tone based on user input
tone = self.personality.get_response_tone(text)
if search_results:
# Use the most relevant piece of knowledge
knowledge_response = search_results[0]
if tone == "empathetic_comforting":
return f"I understand this might be challenging. {knowledge_response} Remember, you're never alone in your journey."
elif tone == "concerned_supportive":
return f"I'm here for you. {knowledge_response} Let me know how I can further support you."
elif tone == "thoughtful_informative":
return f"{knowledge_response} I hope this helps answer your question. Is there anything else you'd like to know?"
else: # friendly_encouraging
return f"{knowledge_response} I'm here to help you on your spiritual journey whenever you need guidance."
else:
# General responses based on tone
if tone == "empathetic_comforting":
return "I'm here for you during this time. Remember that God is close to the brokenhearted and saves those who are crushed in spirit (Psalm 34:18). You're not alone in this journey."
elif tone == "concerned_supportive":
return "I'm here to help. Please let me know more specifically how I can assist you, whether it's through prayer, Scripture, or spiritual guidance."
elif tone == "thoughtful_informative":
return "That's an interesting question. While I don't have a specific answer, I encourage you to seek wisdom through prayer and Scripture. As James 1:5 says, 'If any of you lacks wisdom, you should ask God, who gives generously to all without finding fault, and it will be given to you.'"
else: # friendly_encouraging
return "Thank you for sharing that with me. I'm here to support your spiritual journey. Remember that God's love for you is unchanging and His grace is sufficient for all your needs."
def _extract_insights(self, text: str) -> None:
"""Extract insights, preferences, and important facts from user input."""
# Example patterns to detect preferences
if re.search(r"(like|enjoy|prefer|love) (to )?(read|reading)", text, re.I):
self.memory.update_preference("activities", "reading")
if re.search(r"(like|enjoy|prefer|love) (to )?(pray|praying|meditation|meditate)", text, re.I):
self.memory.update_preference("spiritual_practices", "prayer_meditation")
# Extract potential important facts
if re.search(r"(i am|i'm) (feeling|going through) (a )?(difficult|hard|tough) time", text, re.I):
self.memory.add_important_fact("personal_challenges", "Going through difficult times")
if re.search(r"(my|i have a) (family|relative|parent|child|spouse)", text, re.I):
self.memory.add_important_fact("relationships", "Has mentioned family")
Main chat loop
def main():
print("Initializing Umbrella Guardian Angel AI...")
umbrella = UmbrellAI()
print(f"{umbrella.name} is ready to assist you!")
while True:
user_input = input("You: ")
if user_input.lower() in ["exit", "quit"]:
print(f"{umbrella.name}: Farewell, stay safe.")
break
response = umbrella.respond(user_input)
print(f"{umbrella.name}: {response}")
if name == "main":
main()