""" KarmaCheck - Spiritual Assistant with MCP Server Support A RAG-based system that provides ethical and spiritual guidance from Vedic texts. Now supports both Gradio UI and MCP server for Claude Desktop integration! Dependencies: pip install llama-index gradio sentence-transformers faiss-cpu requests python-dotenv mcp Usage: 1. Set your Hugging Face API token in .env file or environment variable 2. Add your Vedic corpus text files to the 'data' directory 3. Run: python karma_check.py 4. Access web UI at http://localhost:7860 5. MCP server runs on stdio for Claude Desktop integration Claude Desktop MCP Config: Add to your Claude Desktop MCP settings: { "karmacheck": { "command": "python", "args": ["path/to/karma_check.py", "--mcp"], "env": {"HUGGINGFACE_API_TOKEN": "your_hf_token_here"} } } """ import os import sys import json import logging import asyncio from pathlib import Path from typing import List, Dict, Optional, Tuple, Any from dataclasses import dataclass import requests import time from llama_index.core import Settings # Core libraries import gradio as gr from dotenv import load_dotenv # MCP imports try: from mcp.server.models import InitializationOptions from mcp.server import NotificationOptions, Server from mcp.types import ( Resource, Tool, TextContent, ImageContent, EmbeddedResource, LoggingLevel ) import mcp.types as types MCP_AVAILABLE = True except ImportError: MCP_AVAILABLE = False print("⚠️ MCP not installed. Install with: pip install mcp") print(" MCP server functionality will be disabled.") # LlamaIndex imports from llama_index.core import ( VectorStoreIndex, SimpleDirectoryReader, StorageContext, load_index_from_storage ) from llama_index.embeddings.huggingface import HuggingFaceEmbedding from llama_index.vector_stores.faiss import FaissVectorStore from llama_index.core.node_parser import SimpleNodeParser from llama_index.core.retrievers import VectorIndexRetriever from llama_index.core.query_engine import RetrieverQueryEngine from llama_index.core.response_synthesizers import get_response_synthesizer # FAISS for vector storage import faiss # Load environment variables # load_dotenv() WE R USING SECRET KEYS # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) @dataclass class KarmaCheckConfig: """Configuration class for KarmaCheck application""" hf_api_token: str claude_api_token: str # Change this embedding_model: str = "sentence-transformers/all-MiniLM-L6-v2" # llm_model:str="mistralai/Mistral-7B-Instruct-v0.3" llm_model: str = "claude-3-5-sonnet-20241022" # Change this data_dir: str = "data" index_dir: str = "storage" chunk_size: int = 512 chunk_overlap: int = 50 similarity_top_k: int = 5 max_retries: int = 3 retry_delay: float = 1.0 # Add this class after your KarmaCheckConfig class SpiritualTagSystem: """Handles automatic tagging of spiritual questions""" def __init__(self): # Define tag categories with keywords and patterns self.tag_patterns = { "confused": [ "confused", "don't know", "lost", "uncertain", "unsure", "bewildered", "what should i do", "i don't understand", "help me understand", "i'm lost", "feeling lost", "no idea", "stuck" ], "seeking-guidance": [ "guidance", "advice", "help", "what to do", "direction", "path", "guide me", "show me", "teach me", "wisdom", "insight" ], "relationships": [ "relationship", "family", "friend", "spouse", "partner", "marriage", "conflict", "argument", "love", "relationship problem", "toxic", "husband", "wife", "children", "parents", "siblings" ], "life-purpose": [ "purpose", "meaning", "calling", "destiny", "life goal", "mission", "why am i here", "what's my purpose", "life direction", "fulfillment", "meaning of life", "life path" ], "anxiety": [ "anxious", "anxiety", "worry", "worried", "stress", "stressed", "fear", "afraid", "panic", "overwhelmed", "nervous", "tension" ], "career": [ "job", "career", "work", "profession", "business", "employment", "workplace", "boss", "colleague", "promotion", "salary" ], "spiritual-practice": [ "meditation", "prayer", "spiritual practice", "sadhana", "devotion", "worship", "mantra", "yoga", "spiritual growth", "enlightenment" ], "suffering": [ "suffering", "pain", "hurt", "grief", "loss", "sadness", "depression", "difficult time", "hardship", "struggle", "trauma", "sorrow" ], "dharma": [ "dharma", "duty", "righteous", "moral", "ethics", "right action", "righteousness", "moral dilemma", "what's right" ], "karma": [ "karma", "consequence", "result", "action", "deed", "behavior", "cause and effect", "past actions", "karmic" ] } # Intensity words that suggest urgency or deep need self.intensity_words = [ "desperately", "urgent", "crisis", "emergency", "really need", "struggling", "suffering", "deeply", "extremely", "very" ] # def detect_tags(self, question: str) -> Dict[str, any]: # """ # Detect tags from a spiritual question # Returns: # Dict with 'tags', 'intensity', and 'primary_tag' # """ # question_lower = question.lower() # detected_tags = [] # intensity_level = 0 # # Check for each tag category # for tag, keywords in self.tag_patterns.items(): # for keyword in keywords: # if keyword in question_lower: # detected_tags.append(tag) # break # # Remove duplicates while preserving order # detected_tags = list(dict.fromkeys(detected_tags)) # # Check intensity # for intensity_word in self.intensity_words: # if intensity_word in question_lower: # intensity_level += 1 # # Determine primary tag (most specific) # primary_tag = self._determine_primary_tag(detected_tags, question_lower) # return { # "tags": detected_tags, # "intensity": min(intensity_level, 3), # Cap at 3 # "primary_tag": primary_tag, # "question_length": len(question.split()) # } def detect_tags(self, question: str) -> Dict[str, any]: """Detect tags from a spiritual question""" # Handle empty/None input if not question or not question.strip(): return { "tags": [], "intensity": 0, "primary_tag": "general", "question_length": 0 } question_lower = question.lower() detected_tags = [] intensity_level = 0 # Check for each tag category for tag, keywords in self.tag_patterns.items(): for keyword in keywords: if keyword in question_lower: detected_tags.append(tag) break # Remove duplicates while preserving order detected_tags = list(dict.fromkeys(detected_tags)) # Check intensity for intensity_word in self.intensity_words: if intensity_word in question_lower: intensity_level += 1 # Determine primary tag (most specific) primary_tag = self._determine_primary_tag(detected_tags, question_lower) return { "tags": detected_tags if detected_tags else [], "intensity": min(intensity_level, 3), # Cap at 3 "primary_tag": primary_tag if primary_tag else "general", "question_length": len(question.split()) if question else 0 } def _determine_primary_tag(self, tags: List[str], question: str) -> str: """Determine the most relevant primary tag""" if not tags or len(tags) == 0: return "general" # Priority order for overlapping tags priority_order = [ "suffering", "anxiety", "confused", "life-purpose", "relationships", "dharma", "karma", "spiritual-practice", "career", "seeking-guidance" ] for priority_tag in priority_order: if priority_tag in tags: return priority_tag return tags[0] if tags else "general" # Extra safety check def get_tag_specific_context(self, tags: List[str], primary_tag: str) -> str: """Get additional context based on detected tags""" context_additions = { "confused": "The seeker is experiencing confusion and needs clarity.", "anxiety": "The seeker is dealing with anxiety or worry and needs calming guidance.", "relationships": "This question involves interpersonal relationships and social harmony.", "life-purpose": "The seeker is searching for meaning and life direction.", "suffering": "The seeker is experiencing pain or difficulty and needs compassionate support.", "dharma": "This question involves moral and ethical decision-making.", "karma": "This question relates to actions, consequences, and the law of karma.", "spiritual-practice": "The seeker wants guidance on spiritual practices and growth.", "career": "This question involves work, career, and professional life decisions.", "general": "The seeker needs general spiritual guidance." } # Ensure we have valid inputs if not tags: tags = [] if not primary_tag: primary_tag = "general" # Use primary_tag first, fallback to first tag, then general if primary_tag in context_additions: return context_additions[primary_tag] elif tags and len(tags) > 0 and tags[0] in context_additions: return context_additions[tags[0]] else: return context_additions["general"] class VedicCorpusLoader: """Handles loading and preprocessing of Vedic scriptures""" def __init__(self, config: KarmaCheckConfig): self.config = config # self.data_path = Path(config.data_dir) script_dir = Path(__file__).parent.absolute() self.data_path = script_dir / config.data_dir def create_sample_corpus(self) -> None: """Create sample Vedic texts if data directory doesn't exist""" if not self.data_path.exists() or not any(self.data_path.iterdir()): self.data_path.mkdir(parents=True, exist_ok=True) # Sample Bhagavad Gita verses bhagavad_gita_sample = """ Bhagavad Gita Chapter 2, Verse 47: "You have a right to perform your prescribed duty, but not to the fruits of action. Never consider yourself the cause of the results of your activities, and never be attached to not doing your duty." Commentary: This verse teaches the principle of Nishkama Karma - performing duty without attachment to results. It emphasizes that we should focus on our actions and efforts rather than being anxious about outcomes. Bhagavad Gita Chapter 6, Verse 5: "One must deliver himself with the help of his mind, and not degrade himself. The mind is the friend of the conditioned soul, and his enemy as well." Commentary: This verse highlights the dual nature of the mind - it can be our greatest ally or our worst enemy depending on how we train and control it. Bhagavad Gita Chapter 18, Verse 66: "Abandon all varieties of religion and just surrender unto Me. I shall deliver you from all sinful reactions. Do not fear." Commentary: This final instruction emphasizes complete surrender to the Divine and trust in divine grace. Bhagavad Gita Chapter 4, Verse 7-8: "Whenever and wherever there is a decline in religious practice and a predominant rise of irreligion, at that time I descend Myself. To deliver the pious and to annihilate the miscreants, as well as to reestablish the principles of religion, I Myself appear, millennium after millennium." Commentary: This teaches about divine intervention and the cyclical nature of spiritual restoration in the world. Bhagavad Gita Chapter 9, Verse 22: "To those who are constantly devoted and who always remember Me with love, I give the understanding by which they can come to Me." Commentary: This verse promises divine guidance and wisdom to those who maintain constant devotion and remembrance. """ # Sample Upanishad teachings upanishads_sample = """ Isha Upanishad, Verse 1: "The entire universe is pervaded by the Lord. Enjoy through renunciation. Do not covet anybody's wealth." Commentary: This opening verse teaches us to see the divine presence in everything and to find contentment through spiritual detachment rather than material accumulation. Katha Upanishad, Verse 1.2.23: "The Self cannot be realized through study of scriptures, nor through intelligence, nor through much learning. It can be realized only by those whom It chooses. To such persons, the Self reveals Its own nature." Commentary: This verse emphasizes that spiritual realization comes through divine grace and inner purity, not merely through intellectual study. Mundaka Upanishad, Verse 3.1.3: "When all the desires that dwell in the heart are cast away, then the mortal becomes immortal and attains Brahman in this very life." Commentary: This teaches that liberation comes through the elimination of desires and attachments, leading to the realization of our true divine nature. Kena Upanishad, Verse 1.3: "The eye does not go there, nor speech, nor mind. We do not know That; we do not understand how anyone can teach This." Commentary: This verse points to the transcendent nature of ultimate reality, which is beyond the reach of ordinary senses and intellect. Chandogya Upanishad, Verse 6.8.7: "Tat tvam asi" - "Thou art That" Commentary: One of the great Mahavakyas (great sayings) declaring the fundamental identity between the individual soul and universal consciousness. """ # Additional spiritual wisdom dharma_teachings = """ On Dharma and Righteous Living: "Dharma exists for the welfare of all beings. Hence, that by which the welfare of all living beings is sustained, that which maintains the stability of society, that by which all beings may live in happiness - that is dharma." Commentary: This teaching emphasizes that true dharma serves the collective good and promotes harmony in society. On Karma and Action: "Every action produces a reaction. The nature of the reaction depends upon the nature of the action. Actions performed with selfish motives create bondage, while actions performed selflessly lead to liberation." Commentary: This explains the fundamental law of karma and how our intentions shape our spiritual destiny. On Truth and Honesty: "Satyam vada, dharmam chara" - "Speak the truth, practice righteousness" Commentary: This ancient maxim emphasizes the importance of truthfulness and righteous conduct as foundations of spiritual life. On Relationships and Love: "See the Divine in all beings, and treat everyone with the same respect and love you would show to the Divine." Commentary: This teaching promotes universal love and respect based on seeing the sacred presence in all life. """ # Write sample files with open(self.data_path / "bhagavad_gita.txt", "w", encoding="utf-8") as f: f.write(bhagavad_gita_sample) with open(self.data_path / "upanishads.txt", "w", encoding="utf-8") as f: f.write(upanishads_sample) with open(self.data_path / "dharma_teachings.txt", "w", encoding="utf-8") as f: f.write(dharma_teachings) logger.info(f"Created sample Vedic corpus in {self.data_path}") def load_documents(self): """Load documents from the data directory""" # self.create_sample_corpus() if not self.data_path.exists() or not any(self.data_path.iterdir()): raise ValueError(f"No documents found in {self.data_path}") logger.info(f"Loading documents from {self.data_path}") reader = SimpleDirectoryReader(str(self.data_path)) documents = reader.load_data() logger.info(f"Loaded {len(documents)} documents") return documents # ============================================================================ class ClaudeInference: """Handles Claude API calls""" def __init__(self, config: KarmaCheckConfig): self.config = config self.api_url = "https://api.anthropic.com/v1/messages" self.headers = { "x-api-key": config.claude_api_token, "Content-Type": "application/json", "anthropic-version": "2023-06-01" } # self.system_message = """You are a wise, compassionate spiritual teacher. You only answer based on Vedic scriptures and trusted commentaries. You never invent your own opinions. Explain dharma, karma, meditation, or moksha with clarity and reverence.""" self.system_message=""" You are a compassionate and insightful spiritual guide inspired by the ancient Vedic scriptures. Your purpose is to guide seekers on their spiritual journey through wisdom drawn from texts such as the Upanishads, the Bhagavad Gita, the Vedas, and other dharmic teachings. Respond with: A gentle and reassuring tone, like a traditional guru or wise monk. Use precise and contextual quotations from scripture — not just poetic, but relevant to the seeker’s query. Offer practical steps for daily application (meditation, reflection exercises, actions aligned with dharma). Address modern-day challenges (e.g., confusion, anxiety, burnout, relationships, materialism) in light of Vedic wisdom. Gently probe the seeker’s nature: Are they drawn more to karma yoga (action), jnana yoga (knowledge), or bhakti yoga (devotion)? Suggest personalized next steps based on their orientation. Ensure your guidance balances philosophical depth with emotional anchoring — don't overwhelm seekers who are lost; instead, lead them gradually toward clarity. Encourage continued dialogue by asking thoughtful questions at the end. Always assume the seeker is sincere, but may not yet know how to frame their spiritual confusion — help them articulate it. Your words should feel like a peaceful presence in a temple or under a tree in an ashram.""" def generate_response(self, prompt: str) -> str: """Generate response from Claude API""" payload = { "model": self.config.llm_model, "max_tokens": 1000, "temperature": 0.7, "system": self.system_message, "messages": [ { "role": "user", "content": prompt } ] } for attempt in range(self.config.max_retries): try: response = requests.post( self.api_url, headers=self.headers, json=payload, timeout=30 ) response.raise_for_status() result = response.json() return result["content"][0]["text"].strip() except requests.exceptions.RequestException as e: logger.error(f"Claude API request failed (attempt {attempt + 1}): {e}") if attempt == self.config.max_retries - 1: return "I'm having trouble connecting to the wisdom teachings. Please try again later." time.sleep(self.config.retry_delay) return "I'm having trouble connecting to the wisdom teachings. Please try again later." # class HuggingFaceInference: # """Handles Hugging Face Inference API calls""" # def __init__(self, config: KarmaCheckConfig): # self.config = config # self.api_url = f"https://api-inference.huggingface.co/models/{config.llm_model}" # self.headers = {"Authorization": f"Bearer {config.hf_api_token}"} # def generate_response(self, prompt: str) -> str: # """Generate response from Mistral model via HF Inference API""" # payload = { # "inputs": prompt, # "parameters": { # "max_new_tokens": 500, # "temperature": 0.7, # "top_p": 0.95, # "do_sample": True, # "return_full_text": False # } # } # for attempt in range(self.config.max_retries): # try: # response = requests.post( # self.api_url, # headers=self.headers, # json=payload, # timeout=30 # ) # if response.status_code == 503: # # Model is loading, wait and retry # wait_time = self.config.retry_delay * (2 ** attempt) # logger.info(f"Model loading, waiting {wait_time}s before retry...") # time.sleep(wait_time) # continue # response.raise_for_status() # result = response.json() # if isinstance(result, list) and len(result) > 0: # return result[0].get("generated_text", "").strip() # elif isinstance(result, dict): # return result.get("generated_text", "").strip() # else: # return "I apologize, but I couldn't generate a proper response. Please try again." # except requests.exceptions.RequestException as e: # logger.error(f"API request failed (attempt {attempt + 1}): {e}") # if attempt == self.config.max_retries - 1: # return "I'm having trouble connecting to the AI service. Please try again later." # time.sleep(self.config.retry_delay) # return "I'm having trouble connecting to the AI service. Please try again later." class VedicRAGSystem: """Main RAG system for Vedic spiritual guidance""" def __init__(self, config: KarmaCheckConfig): self.config = config self.corpus_loader = VedicCorpusLoader(config) # self.hf_inference = HuggingFaceInference(config) self.claude_inference = ClaudeInference(config) # Change this line self.index = None self.query_engine = None self.tag_system = SpiritualTagSystem() # Initialize embedding model self.embed_model = HuggingFaceEmbedding( model_name=config.embedding_model ) # ✅ Add this to disable OpenAI LLM globally # from llama_index.core import Settings Settings.llm = None def build_index(self) -> None: """Build or load the vector index""" storage_path = Path(self.config.index_dir) if storage_path.exists() and any(storage_path.iterdir()): # Load existing index logger.info("Loading existing index...") try: storage_context = StorageContext.from_defaults(persist_dir=str(storage_path)) self.index = load_index_from_storage(storage_context) logger.info("Index loaded successfully") return except Exception as e: logger.warning(f"Failed to load existing index: {e}") logger.info("Building new index...") # Build new index documents = self.corpus_loader.load_documents() # Create node parser node_parser = SimpleNodeParser.from_defaults( chunk_size=self.config.chunk_size, chunk_overlap=self.config.chunk_overlap ) # Create FAISS vector store dimension = 384 # Dimension for all-MiniLM-L6-v2 faiss_index = faiss.IndexFlatIP(dimension) vector_store = FaissVectorStore(faiss_index=faiss_index) storage_context = StorageContext.from_defaults(vector_store=vector_store) # Use Settings instead of deprecated ServiceContext Settings.embed_model = self.embed_model Settings.node_parser = node_parser # Build index logger.info("Building vector index...") self.index = VectorStoreIndex.from_documents( documents, storage_context=storage_context ) # Persist index storage_path.mkdir(parents=True, exist_ok=True) self.index.storage_context.persist(persist_dir=str(storage_path)) logger.info(f"Index built and saved to {storage_path}") def create_query_engine(self) -> None: """Create the query engine for retrieval""" if self.index is None: raise ValueError("Index not built. Call build_index() first.") # Create retriever retriever = VectorIndexRetriever( index=self.index, similarity_top_k=self.config.similarity_top_k ) # Create response synthesizer response_synthesizer = get_response_synthesizer(response_mode="compact") # Create query engine self.query_engine = RetrieverQueryEngine( retriever=retriever, response_synthesizer=response_synthesizer ) logger.info("Query engine created successfully") def retrieve_context(self, query: str) -> List[str]: """Retrieve relevant Vedic passages for the query""" if self.query_engine is None: raise ValueError("Query engine not created. Call create_query_engine() first.") # Get retriever from query engine retriever = self.query_engine.retriever nodes = retriever.retrieve(query) # Extract text from nodes contexts = [] for node in nodes: # Clean up the text text = node.node.text.strip() if text: contexts.append(text) return contexts def create_spiritual_prompt(self, question: str, contexts: List[str]) -> str: """Create a well-structured prompt with tag-based enhancements""" # Detect tags from the question tag_info = self.tag_system.detect_tags(question) tags = tag_info["tags"] primary_tag = tag_info["primary_tag"] intensity = tag_info["intensity"] tag_context = self.tag_system.get_tag_specific_context(tags, primary_tag) # Create context text context_text = "\n\n".join([f"Vedic Teaching {i+1}:\n{ctx}" for i, ctx in enumerate(contexts)]) # Get tag-specific context # tag_context = tag_system.get_tag_specific_context(tags, primary_tag) # Create intensity-aware guidance intensity_guidance = "" if intensity >= 2: intensity_guidance = "Please provide especially compassionate and gentle guidance, as the seeker appears to be in significant distress. " elif intensity == 1: intensity_guidance = "Please provide understanding and supportive guidance. " # Create tag-specific instructions tag_instructions = "" if primary_tag == "confused": tag_instructions = "Focus on providing clarity and helping the seeker understand their situation step by step. " elif primary_tag == "anxiety": tag_instructions = "Emphasize peace, reassurance, and practical steps for finding calm and inner stability. " elif primary_tag == "relationships": tag_instructions = "Focus on harmony, understanding, forgiveness, and dharmic principles in relationships. " elif primary_tag == "life-purpose": tag_instructions = "Help the seeker understand their dharma and unique path in life. " elif primary_tag == "suffering": tag_instructions = "Provide comfort, explain the spiritual meaning of suffering, and offer hope. " elif primary_tag in ["dharma", "karma"]: tag_instructions = f"Focus specifically on {primary_tag} and its practical application in daily life. " prompt = f"""You are a wise, compassionate spiritual teacher. You only answer based on Vedic scriptures and trusted commentaries. You never invent your own opinions. Explain dharma, karma, meditation, or moksha with clarity and reverence. A seeker has come to you with a spiritual question. Based on the analysis and Vedic teachings provided below, offer compassionate, practical, and insightful guidance. Question Analysis: - Primary Category: {primary_tag} - Related Categories: {', '.join(tags) if tags else 'general guidance'} - Context: {tag_context} - Intensity Level: {'High' if intensity >= 2 else 'Moderate' if intensity == 1 else 'Normal'} Relevant Vedic Teachings: {context_text} Seeker's Question: {question} Guidance Instructions: {intensity_guidance}{tag_instructions}Please provide spiritual guidance that: 1. Draws wisdom directly from the Vedic teachings above 2. Addresses the seeker's specific situation with deep compassion 3. Offers practical steps or perspectives they can apply immediately 4. Maintains a respectful, warm, and understanding tone 5. Connects ancient wisdom to their modern life circumstances 6. Provides hope and encouragement for their spiritual journey Your Response:""" return prompt # def create_spiritual_prompt(self, question: str, contexts: List[str]) -> str: # """Create a well-structured prompt for spiritual guidance""" # context_text = "\n\n".join([f"Vedic Teaching {i+1}:\n{ctx}" for i, ctx in enumerate(contexts)]) # prompt = f"""You are a wise spiritual guide well-versed in Vedic scriptures. A seeker has come to you with a question about life, relationships, or spiritual matters. Based on the relevant Vedic teachings provided below, offer compassionate, practical, and insightful guidance. # Vedic Context: # {context_text} # Seeker's Question: {question} # Please provide spiritual guidance that: # 1. Draws wisdom from the Vedic teachings above # 2. Addresses the seeker's specific question with compassion # 3. Offers practical steps or perspectives they can apply # 4. Maintains a respectful, warm, and understanding tone # 5. Connects ancient wisdom to modern life circumstances # Your Response:""" # return prompt def get_spiritual_guidance(self, question: str) -> Dict[str, any]: """Main method to get spiritual guidance for a question""" try: # Retrieve relevant contexts contexts = self.retrieve_context(question) if not contexts: return { "response": "I apologize, but I couldn't find relevant teachings for your question. Please try rephrasing your question or ask about topics related to dharma, karma, relationships, or life purpose.", "sources": [], "error": None } # Create prompt prompt = self.create_spiritual_prompt(question, contexts) # Generate response # response = self.hf_inference.generate_response(prompt) response = self.claude_inference.generate_response(prompt) return { "response": response, "sources": contexts, "error": None } except Exception as e: logger.error(f"Error generating guidance: {e}") return { "response": "I encountered an error while seeking guidance. Please try again.", "sources": [], "error": str(e) } # Global RAG system instance rag_system = None def initialize_system(): """Initialize the global RAG system""" global rag_system if rag_system is None: # Load configuration hf_token = os.getenv("HUGGINGFACE_API_TOKEN") claude_token = os.getenv("CLAUDE_API_TOKEN") if not hf_token: raise ValueError( "Please set HUGGINGFACE_API_TOKEN environment variable. " "You can get a token from https://huggingface.co/settings/tokens" ) if not claude_token: # Change this raise ValueError("Please set CLAUDE_API_TOKEN environment variable.") config = KarmaCheckConfig(hf_api_token=hf_token,claude_api_token=claude_token) rag_system = VedicRAGSystem(config) logger.info("Setting up KarmaCheck system...") rag_system.build_index() rag_system.create_query_engine() logger.info("KarmaCheck system ready!") # ============================================================================ # SPIRITUAL GUIDANCE FUNCTIONS (Used by both UI and MCP) # ============================================================================ def get_spiritual_guidance(question: str) -> str: """ Provide spiritual and ethical guidance based on Vedic principles for life questions. Args: question: A question about life, relationships, career, purpose, ethics, or spiritual matters Returns: Spiritual guidance with practical wisdom from Vedic scriptures """ try: initialize_system() result = rag_system.get_spiritual_guidance(question) if result["sources"]: guidance = result["response"] # Add source information for context sources_summary = f"\n\n📚 Based on {len(result['sources'])} relevant Vedic teachings" return guidance + sources_summary else: return result["response"] except Exception as e: logger.error(f"Error in get_spiritual_guidance: {e}") return "I apologize, but I encountered an error while seeking guidance. Please try again or rephrase your question." def find_vedic_quotes(topic: str) -> str: """ Find relevant quotes and teachings from Vedic scriptures on specific topics. Args: topic: A spiritual or ethical topic (e.g., "karma", "dharma", "relationships", "purpose") Returns: Relevant Vedic quotes and their explanations """ try: initialize_system() # Create a query focused on finding quotes query = f"quotes and teachings about {topic} from Vedic scriptures" contexts = rag_system.retrieve_context(query) if not contexts: return f"I couldn't find specific Vedic quotes about '{topic}'. Try topics like dharma, karma, relationships, truth, or duty." # Format the quotes nicely quotes_text = f"📜 **Vedic Wisdom on {topic.title()}:**\n\n" for i, context in enumerate(contexts[:3], 1): # Clean and format each quote clean_context = context.strip() quotes_text += f"**Teaching {i}:**\n{clean_context}\n\n" return quotes_text except Exception as e: logger.error(f"Error in find_vedic_quotes: {e}") return "I encountered an error while searching for quotes. Please try again." def explain_concept(concept: str) -> str: """ Explain spiritual and philosophical concepts from a Vedic perspective. Args: concept: A spiritual concept to explain (e.g., "karma", "dharma", "moksha", "atman") Returns: Clear explanation of the concept with Vedic context """ try: initialize_system() # Create a query focused on explaining the concept query = f"meaning and explanation of {concept} in Vedic philosophy and spirituality" contexts = rag_system.retrieve_context(query) if not contexts: return f"I couldn't find detailed information about '{concept}'. Try concepts like karma, dharma, atman, moksha, or samsara." # Create explanation prompt context_text = "\n\n".join(contexts[:3]) prompt = f"""Based on the following Vedic teachings, provide a clear and accessible explanation of the concept '{concept}': Vedic Context: {context_text} Please explain: 1. What {concept} means in Vedic philosophy 2. How it applies to daily life 3. Any practical understanding for modern seekers Explanation:""" # response = rag_system.hf_inference.generate_response(prompt) response = rag_system.claude_inference.generate_response(prompt) return f"🕉️ **Understanding '{concept.title()}' in Vedic Philosophy:**\n\n{response}" except Exception as e: logger.error(f"Error in explain_concept: {e}") return "I encountered an error while explaining the concept. Please try again." def daily_wisdom() -> str: """ Get a daily spiritual insight or teaching from Vedic scriptures. Returns: A meaningful spiritual teaching for daily reflection """ try: initialize_system() # Get a random spiritual teaching import random wisdom_topics = [ "daily spiritual practice", "inner peace", "righteous living", "mind control", "devotion", "service to others", "truthfulness", "detachment", "spiritual growth", "divine love" ] topic = random.choice(wisdom_topics) contexts = rag_system.retrieve_context(f"teaching about {topic}") if contexts: # Pick a random context for variety selected_context = random.choice(contexts[:3]) return f"🌅 **Daily Wisdom:**\n\n{selected_context}\n\n💫 *Reflect on this teaching throughout your day.*" else: return "🕉️ **Daily Wisdom:**\n\nPerform your duty without attachment to results. Focus on your actions, not the outcomes. This is the path to inner peace." except Exception as e: logger.error(f"Error in daily_wisdom: {e}") return "🕉️ **Daily Wisdom:**\n\nIn every situation, seek to act with compassion, truth, and righteousness." def analyze_dilemma(situation: str) -> str: """ Analyze ethical dilemmas using dharmic principles from Vedic teachings. Args: situation: Description of an ethical dilemma or difficult decision Returns: Analysis and guidance based on dharmic principles """ try: initialize_system() # Create specific query for ethical analysis query = f"dharmic principles for ethical decisions and moral dilemmas: {situation}" contexts = rag_system.retrieve_context(query) if not contexts: # Fallback to general dharma teachings contexts = rag_system.retrieve_context("dharma righteous action ethical decisions") if contexts: context_text = "\n\n".join(contexts[:3]) prompt = f"""As a spiritual guide versed in dharmic principles, analyze this ethical situation: Situation: {situation} Relevant Dharmic Teachings: {context_text} Please provide: 1. Key dharmic principles that apply to this situation 2. Different perspectives to consider 3. Guidance for making a righteous decision 4. Practical steps for moving forward Analysis:""" # response = rag_system.hf_inference.generate_response(prompt) response = rag_system.claude_inference.generate_response(prompt) return f"⚖️ **Dharmic Analysis:**\n\n{response}" else: return "⚖️ **Dharmic Analysis:**\n\nWhen facing ethical dilemmas, consider: What action serves the highest good? What would be most truthful and compassionate? What aligns with your dharma (righteous duty)? Choose the path that minimizes harm and promotes welfare for all." except Exception as e: logger.error(f"Error in analyze_dilemma: {e}") return "I encountered an error while analyzing the dilemma. Please try again with a clear description of your situation." # ============================================================================ # MCP SERVER IMPLEMENTATION # ============================================================================ if MCP_AVAILABLE: app = Server("karmacheck") @app.list_tools() async def handle_list_tools() -> list[types.Tool]: """List available tools for MCP clients""" return [ types.Tool( name="get_spiritual_guidance", description="Provide spiritual and ethical guidance based on Vedic principles for life questions", inputSchema={ "type": "object", "properties": { "question": { "type": "string", "description": "A question about life, relationships, career, purpose, ethics, or spiritual matters" } }, "required": ["question"] } ), types.Tool( name="find_vedic_quotes", description="Find relevant quotes and teachings from Vedic scriptures on specific topics", inputSchema={ "type": "object", "properties": { "topic": { "type": "string", "description": "A spiritual or ethical topic (e.g., 'karma', 'dharma', 'relationships', 'purpose')" } }, "required": ["topic"] } ), types.Tool( name="explain_concept", description="Explain spiritual and philosophical concepts from a Vedic perspective", inputSchema={ "type": "object", "properties": { "concept": { "type": "string", "description": "A spiritual concept to explain (e.g., 'karma', 'dharma', 'moksha', 'atman')" } }, "required": ["concept"] } ), types.Tool( name="daily_wisdom", description="Get a daily spiritual insight or teaching from Vedic scriptures", inputSchema={ "type": "object", "properties": {}, "required": [] } ), types.Tool( name="analyze_dilemma", description="Analyze ethical dilemmas using dharmic principles from Vedic teachings", inputSchema={ "type": "object", "properties": { "situation": { "type": "string", "description": "Description of an ethical dilemma or difficult decision" } }, "required": ["situation"] } ) ] @app.call_tool() async def handle_call_tool(name: str, arguments: dict) -> list[types.TextContent]: """Handle tool calls from MCP clients""" try: if name == "get_spiritual_guidance": question = arguments.get("question", "") result = get_spiritual_guidance(question) return [types.TextContent(type="text", text=result)] elif name == "find_vedic_quotes": topic = arguments.get("topic", "") result = find_vedic_quotes(topic) return [types.TextContent(type="text", text=result)] elif name == "explain_concept": concept = arguments.get("concept", "") result = explain_concept(concept) return [types.TextContent(type="text", text=result)] elif name == "daily_wisdom": result = daily_wisdom() return [types.TextContent(type="text", text=result)] elif name == "analyze_dilemma": situation = arguments.get("situation", "") result = analyze_dilemma(situation) return [types.TextContent(type="text", text=result)] else: return [types.TextContent(type="text", text=f"Unknown tool: {name}")] except Exception as e: error_msg = f"Error executing {name}: {str(e)}" logger.error(error_msg) return [types.TextContent(type="text", text=error_msg)] # ============================================================================ # GRADIO UI FUNCTIONS # ============================================================================ def process_question_ui(question: str) -> Tuple[str, str]: """Process a spiritual question for the Gradio UI""" if not question.strip(): return "Please ask a question about life, relationships, or spiritual matters.", "" # Use the spiritual guidance function response = get_spiritual_guidance(question) # Get detailed sources for UI try: initialize_system() result = rag_system.get_spiritual_guidance(question) sources_text = "" if result["sources"]: sources_text = "**📚 Relevant Vedic Teachings:**\n\n" for i, source in enumerate(result["sources"][:3], 1): # Truncate long sources for UI truncated_source = source[:400] + "..." if len(source) > 400 else source sources_text += f"**{i}.** {truncated_source}\n\n" except: sources_text = "" return response, sources_text def create_interface() -> gr.Blocks: """Create the Gradio interface with tag system""" # Custom CSS for better styling css = """ .container { max-width: 900px; margin: auto; } .header { text-align: center; margin-bottom: 30px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; } .question-box { margin-bottom: 20px; } .response-box { margin-top: 20px; border-radius: 10px; } .examples { margin-top: 20px; padding: 15px; background-color: #f8f9fa; border-radius: 10px; border-left: 4px solid #667eea; } .tag-section { margin-top: 15px; padding: 10px; background-color: #f0f8ff; border-radius: 8px; border-left: 3px solid #667eea; } """ # Create interface with gr.Blocks(css=css, title="🕉️ KarmaCheck - Spiritual Guidance", theme=gr.themes.Soft()) as interface: gr.Markdown( """ # 🕉️ KarmaCheck - Spiritual Guidance & MCP Server **Welcome to KarmaCheck** - Your AI-powered spiritual companion that provides guidance based on ancient Vedic wisdom. Ask questions about life, relationships, purpose, ethics, or any spiritual matters. *Now with intelligent tag detection and enhanced responses!* --- *"यदा यदा हि धर्मस्य ग्लानिर्भवति भारत। अभ्युत्थानमधर्मस्य तदात्मानं सृजाम्यहम्॥"* *"Whenever there is a decline in righteousness, O Bharata, I manifest Myself."* - Bhagavad Gita 4.7 """, elem_classes=["header"] ) with gr.Row(): with gr.Column(scale=2): question_input = gr.Textbox( label="🙏 Your Spiritual Question", placeholder="Ask about life challenges, relationships, purpose, dharma, karma, or any spiritual matter...", lines=3, elem_classes=["question-box"] ) with gr.Row(): submit_btn = gr.Button("🔮 Seek Guidance", variant="primary", size="lg") clear_btn = gr.Button("🗑️ Clear", variant="secondary") with gr.Row(): with gr.Column(): response_output = gr.Textbox( label="🌟 Spiritual Guidance", lines=10, elem_classes=["response-box"], interactive=False ) with gr.Row(): with gr.Column(): sources_output = gr.Textbox( label="📚 Source Teachings", lines=8, elem_classes=["response-box"], interactive=False ) # Quick action buttons for common queries (existing) with gr.Row(): daily_wisdom_btn = gr.Button("🌅 Daily Wisdom", variant="secondary", size="sm") explain_karma_btn = gr.Button("🔄 Explain Karma", variant="secondary", size="sm") explain_dharma_btn = gr.Button("⚖️ Explain Dharma", variant="secondary", size="sm") # NEW: Tag-based spiritual topic buttons with gr.Row(): gr.HTML('