|
""" |
|
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 |
|
|
|
|
|
import gradio as gr |
|
from dotenv import load_dotenv |
|
|
|
|
|
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.") |
|
|
|
|
|
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 |
|
|
|
|
|
import faiss |
|
|
|
|
|
|
|
|
|
|
|
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 |
|
embedding_model: str = "sentence-transformers/all-MiniLM-L6-v2" |
|
|
|
llm_model: str = "claude-3-5-sonnet-20241022" |
|
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 |
|
|
|
class SpiritualTagSystem: |
|
"""Handles automatic tagging of spiritual questions""" |
|
|
|
def __init__(self): |
|
|
|
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" |
|
] |
|
} |
|
|
|
|
|
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""" |
|
|
|
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 |
|
|
|
|
|
for tag, keywords in self.tag_patterns.items(): |
|
for keyword in keywords: |
|
if keyword in question_lower: |
|
detected_tags.append(tag) |
|
break |
|
|
|
|
|
detected_tags = list(dict.fromkeys(detected_tags)) |
|
|
|
|
|
for intensity_word in self.intensity_words: |
|
if intensity_word in question_lower: |
|
intensity_level += 1 |
|
|
|
|
|
primary_tag = self._determine_primary_tag(detected_tags, question_lower) |
|
|
|
return { |
|
"tags": detected_tags if detected_tags else [], |
|
"intensity": min(intensity_level, 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 = [ |
|
"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" |
|
|
|
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." |
|
} |
|
|
|
|
|
if not tags: |
|
tags = [] |
|
if not primary_tag: |
|
primary_tag = "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 |
|
|
|
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) |
|
|
|
|
|
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. |
|
""" |
|
|
|
|
|
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. |
|
""" |
|
|
|
|
|
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. |
|
""" |
|
|
|
|
|
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""" |
|
|
|
|
|
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 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 VedicRAGSystem: |
|
"""Main RAG system for Vedic spiritual guidance""" |
|
|
|
def __init__(self, config: KarmaCheckConfig): |
|
self.config = config |
|
self.corpus_loader = VedicCorpusLoader(config) |
|
|
|
self.claude_inference = ClaudeInference(config) |
|
self.index = None |
|
self.query_engine = None |
|
self.tag_system = SpiritualTagSystem() |
|
|
|
|
|
self.embed_model = HuggingFaceEmbedding( |
|
model_name=config.embedding_model |
|
) |
|
|
|
|
|
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()): |
|
|
|
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...") |
|
|
|
|
|
documents = self.corpus_loader.load_documents() |
|
|
|
|
|
node_parser = SimpleNodeParser.from_defaults( |
|
chunk_size=self.config.chunk_size, |
|
chunk_overlap=self.config.chunk_overlap |
|
) |
|
|
|
|
|
dimension = 384 |
|
faiss_index = faiss.IndexFlatIP(dimension) |
|
vector_store = FaissVectorStore(faiss_index=faiss_index) |
|
storage_context = StorageContext.from_defaults(vector_store=vector_store) |
|
|
|
|
|
|
|
Settings.embed_model = self.embed_model |
|
Settings.node_parser = node_parser |
|
|
|
|
|
logger.info("Building vector index...") |
|
self.index = VectorStoreIndex.from_documents( |
|
documents, |
|
storage_context=storage_context |
|
) |
|
|
|
|
|
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.") |
|
|
|
|
|
retriever = VectorIndexRetriever( |
|
index=self.index, |
|
similarity_top_k=self.config.similarity_top_k |
|
) |
|
|
|
|
|
response_synthesizer = get_response_synthesizer(response_mode="compact") |
|
|
|
|
|
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.") |
|
|
|
|
|
retriever = self.query_engine.retriever |
|
nodes = retriever.retrieve(query) |
|
|
|
|
|
contexts = [] |
|
for node in nodes: |
|
|
|
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""" |
|
|
|
|
|
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) |
|
|
|
|
|
context_text = "\n\n".join([f"Vedic Teaching {i+1}:\n{ctx}" for i, ctx in enumerate(contexts)]) |
|
|
|
|
|
|
|
|
|
|
|
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. " |
|
|
|
|
|
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 get_spiritual_guidance(self, question: str) -> Dict[str, any]: |
|
"""Main method to get spiritual guidance for a question""" |
|
try: |
|
|
|
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 |
|
} |
|
|
|
|
|
prompt = self.create_spiritual_prompt(question, contexts) |
|
|
|
|
|
|
|
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) |
|
} |
|
|
|
|
|
rag_system = None |
|
|
|
def initialize_system(): |
|
"""Initialize the global RAG system""" |
|
global rag_system |
|
|
|
if rag_system is None: |
|
|
|
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: |
|
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!") |
|
|
|
|
|
|
|
|
|
|
|
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"] |
|
|
|
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() |
|
|
|
|
|
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." |
|
|
|
|
|
quotes_text = f"📜 **Vedic Wisdom on {topic.title()}:**\n\n" |
|
for i, context in enumerate(contexts[:3], 1): |
|
|
|
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() |
|
|
|
|
|
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." |
|
|
|
|
|
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.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() |
|
|
|
|
|
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: |
|
|
|
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() |
|
|
|
|
|
query = f"dharmic principles for ethical decisions and moral dilemmas: {situation}" |
|
contexts = rag_system.retrieve_context(query) |
|
|
|
if not contexts: |
|
|
|
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.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." |
|
|
|
|
|
|
|
|
|
|
|
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)] |
|
|
|
|
|
|
|
|
|
|
|
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.", "" |
|
|
|
|
|
response = get_spiritual_guidance(question) |
|
|
|
|
|
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): |
|
|
|
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""" |
|
|
|
|
|
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; |
|
} |
|
""" |
|
|
|
|
|
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 |
|
) |
|
|
|
|
|
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") |
|
|
|
|
|
with gr.Row(): |
|
gr.HTML('<h3 style="text-align: left; color: #667eea; margin: 10px 0;">🏷️ Quick Spiritual Topics</h3>') |
|
|
|
|
|
with gr.Row(): |
|
purpose_btn = gr.Button("🎯 Life Purpose", variant="secondary", size="sm") |
|
anxiety_btn = gr.Button("😰 Anxiety Help", variant="secondary", size="sm") |
|
relationship_btn = gr.Button("💕 Relationships", variant="secondary", size="sm") |
|
suffering_btn = gr.Button("💔 Dealing with Suffering", variant="secondary", size="sm") |
|
|
|
with gr.Row(): |
|
confused_btn = gr.Button("❓ Feeling Confused", variant="secondary", size="sm") |
|
practice_btn = gr.Button("🧘 Spiritual Practice", variant="secondary", size="sm") |
|
career_btn = gr.Button("💼 Career Guidance", variant="secondary", size="sm") |
|
moral_btn = gr.Button("⚖️ Moral Dilemmas", variant="secondary", size="sm") |
|
|
|
|
|
with gr.Accordion("🔧 MCP Server Integration", open=False): |
|
gr.Markdown( |
|
""" |
|
### Claude Desktop Integration |
|
|
|
This app also runs as an MCP server! Add this to your Claude Desktop MCP settings: |
|
|
|
```json |
|
{ |
|
"karmacheck": { |
|
"command": "python", |
|
"args": ["path/to/karma_check.py", "--mcp"], |
|
"env": {"CLAUDE_API_TOKEN": "your_claude_token_here"} |
|
} |
|
} |
|
``` |
|
|
|
**Available MCP Tools:** |
|
- `get_spiritual_guidance(question)` - Main spiritual guidance with tag detection |
|
- `find_vedic_quotes(topic)` - Find quotes on specific topics |
|
- `explain_concept(concept)` - Explain spiritual concepts |
|
- `daily_wisdom()` - Get daily spiritual insight |
|
- `analyze_dilemma(situation)` - Analyze ethical dilemmas |
|
""" |
|
) |
|
|
|
|
|
with gr.Accordion("💡 Example Questions", open=True): |
|
gr.Markdown( |
|
""" |
|
### Try These Questions: |
|
|
|
**🎯 Life Purpose & Direction:** |
|
- "How can I find my life's true purpose?" |
|
- "I feel lost and confused about my career path. What should I do?" |
|
- "How do I know if I'm following my dharma?" |
|
|
|
**💕 Relationships & Family:** |
|
- "I'm struggling with a difficult relationship. How should I respond?" |
|
- "How can I deal with family conflicts while maintaining harmony?" |
|
- "What does love mean from a spiritual perspective?" |
|
|
|
**😰 Personal Growth & Anxiety:** |
|
- "How can I overcome anxiety and find inner peace?" |
|
- "What is the spiritual significance of suffering?" |
|
- "How do I develop detachment without becoming indifferent?" |
|
|
|
**⚖️ Ethics & Decision Making:** |
|
- "I'm facing an ethical dilemma at work. What should I do?" |
|
- "How do I balance personal desires with duty to others?" |
|
- "What does it mean to live righteously in modern times?" |
|
|
|
**🧘 Spiritual Practice:** |
|
- "How should I start a spiritual practice?" |
|
- "What is the meaning of karma and how does it work?" |
|
- "How can I cultivate devotion and surrender?" |
|
""" |
|
) |
|
|
|
|
|
submit_btn.click( |
|
fn=process_question_ui, |
|
inputs=[question_input], |
|
outputs=[response_output, sources_output] |
|
) |
|
|
|
question_input.submit( |
|
fn=process_question_ui, |
|
inputs=[question_input], |
|
outputs=[response_output, sources_output] |
|
) |
|
|
|
clear_btn.click( |
|
fn=lambda: ("", "", ""), |
|
outputs=[question_input, response_output, sources_output] |
|
) |
|
|
|
|
|
def get_daily_wisdom_ui(): |
|
wisdom = daily_wisdom() |
|
return wisdom, "" |
|
|
|
def explain_karma_ui(): |
|
explanation = explain_concept("karma") |
|
return explanation, "" |
|
|
|
def explain_dharma_ui(): |
|
explanation = explain_concept("dharma") |
|
return explanation, "" |
|
|
|
|
|
def ask_purpose_question(): |
|
question = "I feel lost and don't know my life's purpose. How can I find my dharma and calling in life?" |
|
response, sources = process_question_ui(question) |
|
return question, response, sources |
|
|
|
def ask_anxiety_question(): |
|
question = "I'm struggling with anxiety and constant worry. How can I find inner peace according to Vedic teachings?" |
|
response, sources = process_question_ui(question) |
|
return question, response, sources |
|
|
|
def ask_relationship_question(): |
|
question = "I'm having conflicts in my relationships. How should I handle difficult people with dharmic principles?" |
|
response, sources = process_question_ui(question) |
|
return question, response, sources |
|
|
|
def ask_suffering_question(): |
|
question = "I'm going through a very difficult time and suffering. What is the spiritual meaning of suffering?" |
|
response, sources = process_question_ui(question) |
|
return question, response, sources |
|
|
|
def ask_confused_question(): |
|
question = "I feel completely confused about life and spirituality. Where do I even begin my spiritual journey?" |
|
response, sources = process_question_ui(question) |
|
return question, response, sources |
|
|
|
def ask_practice_question(): |
|
question = "How should I start and maintain a spiritual practice? What does the Bhagavad Gita teach about this?" |
|
response, sources = process_question_ui(question) |
|
return question, response, sources |
|
|
|
def ask_career_question(): |
|
question = "I'm unhappy with my career and don't know if I should change paths. How do I make dharmic career decisions?" |
|
response, sources = process_question_ui(question) |
|
return question, response, sources |
|
|
|
def ask_moral_question(): |
|
question = "I'm facing a moral dilemma where I don't know what's right. How do I understand dharma in difficult situations?" |
|
response, sources = process_question_ui(question) |
|
return question, response, sources |
|
|
|
|
|
daily_wisdom_btn.click( |
|
fn=get_daily_wisdom_ui, |
|
outputs=[response_output, sources_output] |
|
) |
|
|
|
explain_karma_btn.click( |
|
fn=explain_karma_ui, |
|
outputs=[response_output, sources_output] |
|
) |
|
|
|
explain_dharma_btn.click( |
|
fn=explain_dharma_ui, |
|
outputs=[response_output, sources_output] |
|
) |
|
|
|
|
|
purpose_btn.click( |
|
fn=ask_purpose_question, |
|
outputs=[question_input, response_output, sources_output] |
|
) |
|
|
|
anxiety_btn.click( |
|
fn=ask_anxiety_question, |
|
outputs=[question_input, response_output, sources_output] |
|
) |
|
|
|
relationship_btn.click( |
|
fn=ask_relationship_question, |
|
outputs=[question_input, response_output, sources_output] |
|
) |
|
|
|
suffering_btn.click( |
|
fn=ask_suffering_question, |
|
outputs=[question_input, response_output, sources_output] |
|
) |
|
|
|
confused_btn.click( |
|
fn=ask_confused_question, |
|
outputs=[question_input, response_output, sources_output] |
|
) |
|
|
|
practice_btn.click( |
|
fn=ask_practice_question, |
|
outputs=[question_input, response_output, sources_output] |
|
) |
|
|
|
career_btn.click( |
|
fn=ask_career_question, |
|
outputs=[question_input, response_output, sources_output] |
|
) |
|
|
|
moral_btn.click( |
|
fn=ask_moral_question, |
|
outputs=[question_input, response_output, sources_output] |
|
) |
|
|
|
|
|
gr.Markdown( |
|
""" |
|
--- |
|
|
|
### 🙏 About KarmaCheck |
|
|
|
KarmaCheck combines ancient Vedic wisdom with modern AI to provide spiritual guidance for contemporary life. |
|
The system uses RAG (Retrieval-Augmented Generation) to find relevant teachings from scriptures like the |
|
Bhagavad Gita and Upanishads, then provides contextual guidance through advanced language models. |
|
|
|
**✨ Enhanced Features:** |
|
- 🔮 Spiritual guidance based on Vedic principles |
|
- 📚 Direct quotes from sacred texts |
|
- 🏷️ **NEW**: Intelligent tag detection for personalized responses |
|
- 🤖 MCP server for Claude Desktop integration |
|
- 🌟 Daily wisdom and concept explanations |
|
- ⚖️ Ethical dilemma analysis |
|
- 🎯 Quick spiritual topic buttons |
|
|
|
**🏷️ Tag System:** KarmaCheck now automatically detects the type of spiritual question you're asking |
|
(anxiety, relationships, life purpose, etc.) and provides more targeted, compassionate guidance. |
|
|
|
*"सर्वे भवन्तु सुखिनः सर्वे सन्तु निरामयाः। |
|
सर्वे भद्राणि पश्यन्तु मा कश्चिद्दुःखभाग्भवेत्॥"* |
|
|
|
*"May all beings be happy, may all beings be healthy. |
|
May all beings experience prosperity, may none suffer."* |
|
|
|
--- |
|
|
|
Built with ❤️ using Gradio, LlamaIndex, Claude API, and Hugging Face. |
|
|
|
""" |
|
) |
|
|
|
return interface |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def run_mcp_server(): |
|
"""Run the MCP server""" |
|
if not MCP_AVAILABLE: |
|
print("❌ MCP not available. Install with: pip install mcp") |
|
return |
|
|
|
logger.info("🔧 Starting KarmaCheck MCP Server...") |
|
|
|
|
|
try: |
|
initialize_system() |
|
logger.info("✅ KarmaCheck system initialized for MCP") |
|
except Exception as e: |
|
logger.error(f"❌ Failed to initialize system: {e}") |
|
return |
|
|
|
|
|
from mcp.server.stdio import stdio_server |
|
|
|
async with stdio_server() as (read_stream, write_stream): |
|
await app.run( |
|
read_stream, |
|
write_stream, |
|
InitializationOptions( |
|
server_name="karmacheck", |
|
server_version="1.0.0", |
|
capabilities=app.get_capabilities( |
|
notification_options=NotificationOptions(), |
|
experimental_capabilities={}, |
|
), |
|
), |
|
) |
|
|
|
def main(): |
|
"""Main entry point""" |
|
|
|
if "--mcp" in sys.argv: |
|
if not MCP_AVAILABLE: |
|
print("❌ MCP not installed. Install with: pip install mcp") |
|
sys.exit(1) |
|
|
|
|
|
asyncio.run(run_mcp_server()) |
|
return |
|
|
|
try: |
|
|
|
hf_token = os.getenv("HUGGINGFACE_API_TOKEN") |
|
if not hf_token: |
|
print("\n" + "="*70) |
|
print("🚨 SETUP REQUIRED:") |
|
print("1. Get a Claude API token: https://console.anthropic.com/") |
|
print("2. Create a .env file with: CLAUDE_API_TOKEN=your_token_here") |
|
print("3. Or set environment variable: export CLAUDE_API_TOKEN=your_token") |
|
|
|
|
|
|
|
print("\n📋 For Claude Desktop MCP integration:") |
|
print("4. Install MCP: pip install mcp") |
|
print("5. Add this to your Claude Desktop MCP settings:") |
|
print(""" |
|
{ |
|
"karmacheck": { |
|
"command": "python", |
|
"args": ["path/to/karma_check.py", "--mcp"], |
|
"env": {"HUGGINGFACE_API_TOKEN": "your_token_here"} |
|
} |
|
}""") |
|
print("="*70) |
|
return |
|
|
|
|
|
logger.info("🕉️ Initializing KarmaCheck...") |
|
initialize_system() |
|
|
|
|
|
interface = create_interface() |
|
|
|
logger.info("🚀 Launching KarmaCheck Gradio interface...") |
|
logger.info("📱 Web UI: http://localhost:7860") |
|
|
|
if MCP_AVAILABLE: |
|
logger.info("🔧 MCP Server: Ready for Claude Desktop integration") |
|
logger.info(" Use --mcp flag to run in MCP server mode") |
|
else: |
|
logger.info("⚠️ MCP not installed. Install with 'pip install mcp' for Claude Desktop integration") |
|
|
|
|
|
interface.launch( |
|
share=False, |
|
server_name="0.0.0.0", |
|
server_port=7860, |
|
show_error=True, |
|
inbrowser=True |
|
) |
|
|
|
except Exception as e: |
|
logger.error(f"❌ Application error: {e}") |
|
print(f"\n❌ Error: {e}") |
|
print("\n💡 Troubleshooting:") |
|
print("- Ensure HUGGINGFACE_API_TOKEN is set correctly") |
|
print("- Check your internet connection") |
|
print("- Verify all dependencies are installed: pip install -r requirements.txt") |
|
|
|
if __name__ == "__main__": |
|
main() |
|
|