File size: 81,287 Bytes
ef1317f b50f920 ef1317f 1755432 ef1317f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 |
"""
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('<h3 style="text-align: left; color: #667eea; margin: 10px 0;">🏷️ Quick Spiritual Topics</h3>')
# NEW: Tag-based spiritual topic buttons (without problematic markdown)
# gr.Markdown("---") # Just a simple separator
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")
# MCP Server Info
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
"""
)
# Example questions
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?"
"""
)
# Set up interactions for main functionality
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]
)
# Quick action button functions (existing)
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, ""
# Tag-based question functions
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
# Set up existing button handlers
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]
)
# Set up NEW tag-based button handlers
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]
)
# Footer
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
# def create_interface() -> gr.Interface:
# """Create the Gradio interface"""
# # 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;
# }
# """
# # 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 also available as an MCP server for Claude Desktop integration!*
# ---
# *"यदा यदा हि धर्मस्य ग्लानिर्भवति भारत।
# अभ्युत्थानमधर्मस्य तदात्मानं सृजाम्यहम्॥"*
# *"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
# )
# # MCP Server Info
# 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": {"HUGGINGFACE_API_TOKEN": "your_hf_token_here"}
# }
# }
# ```
# **Available MCP Tools:**
# - `get_spiritual_guidance(question)` - Main spiritual guidance
# - `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
# """
# )
# # Example questions
# 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:**
# - "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?"
# """
# )
# # Quick action buttons for common queries
# with gr.Row():
# daily_wisdom_btn = gr.Button("🌅 Daily Wisdom", variant="secondary")
# explain_karma_btn = gr.Button("🔄 Explain Karma", variant="secondary")
# explain_dharma_btn = gr.Button("⚖️ Explain Dharma", variant="secondary")
# # Set up interactions
# 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]
# )
# # Quick action button functions
# 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 create_tag_interface_additions():
# # Quick tag buttons for common spiritual topics
# with gr.Row():
# gr.Markdown("### 🏷️ Quick Spiritual Topics")
# 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")
# dharma_btn = gr.Button("⚖️ Dharma Questions", variant="secondary", size="sm")
# with gr.Row():
# karma_btn = gr.Button("🔄 Understanding Karma", variant="secondary", size="sm")
# suffering_btn = gr.Button("💔 Dealing with Suffering", variant="secondary", size="sm")
# practice_btn = gr.Button("🧘 Spiritual Practice", variant="secondary", size="sm")
# confused_btn = gr.Button("❓ Feeling Confused", variant="secondary", size="sm")
# return {
# 'purpose_btn': purpose_btn,
# 'anxiety_btn': anxiety_btn,
# 'relationship_btn': relationship_btn,
# 'dharma_btn': dharma_btn,
# 'karma_btn': karma_btn,
# 'suffering_btn': suffering_btn,
# 'practice_btn': practice_btn,
# 'confused_btn': confused_btn
# }
# def setup_tag_button_handlers(buttons, question_input, response_output, sources_output):
# """Setup click handlers for tag buttons"""
# 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_dharma_question():
# question = "I'm facing a moral dilemma and don't know what's right. How do I understand my dharma?"
# response, sources = process_question_ui(question)
# return question, response, sources
# def ask_karma_question():
# question = "I want to understand karma better. How does it work in daily life and relationships?"
# 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_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_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
# # Set up click handlers
# buttons['purpose_btn'].click(
# fn=ask_purpose_question,
# outputs=[question_input, response_output, sources_output]
# )
# buttons['anxiety_btn'].click(
# fn=ask_anxiety_question,
# outputs=[question_input, response_output, sources_output]
# )
# buttons['relationship_btn'].click(
# fn=ask_relationship_question,
# outputs=[question_input, response_output, sources_output]
# )
# buttons['dharma_btn'].click(
# fn=ask_dharma_question,
# outputs=[question_input, response_output, sources_output]
# )
# buttons['karma_btn'].click(
# fn=ask_karma_question,
# outputs=[question_input, response_output, sources_output]
# )
# buttons['suffering_btn'].click(
# fn=ask_suffering_question,
# outputs=[question_input, response_output, sources_output]
# )
# buttons['practice_btn'].click(
# fn=ask_practice_question,
# outputs=[question_input, response_output, sources_output]
# )
# buttons['confused_btn'].click(
# fn=ask_confused_question,
# outputs=[question_input, response_output, sources_output]
# )
# 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]
# )
# # Footer
# 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.
# **Features:**
# - 🔮 Spiritual guidance based on Vedic principles
# - 📚 Direct quotes from sacred texts
# - 🤖 MCP server for Claude Desktop integration
# - 🌟 Daily wisdom and concept explanations
# - ⚖️ Ethical dilemma analysis
# *"सर्वे भवन्तु सुखिनः सर्वे सन्तु निरामयाः।
# सर्वे भद्राणि पश्यन्तु मा कश्चिद्दुःखभाग्भवेत्॥"*
# *"May all beings be happy, may all beings be healthy.
# May all beings experience prosperity, may none suffer."*
# ---
# Built with ❤️ using Gradio, LlamaIndex, 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...")
# Initialize the system for MCP
try:
initialize_system()
logger.info("✅ KarmaCheck system initialized for MCP")
except Exception as e:
logger.error(f"❌ Failed to initialize system: {e}")
return
# Import MCP server utilities
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"""
# Check for MCP mode
if "--mcp" in sys.argv:
if not MCP_AVAILABLE:
print("❌ MCP not installed. Install with: pip install mcp")
sys.exit(1)
# Run MCP server
asyncio.run(run_mcp_server())
return
try:
# Check for required environment variable
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("1. Get a Hugging Face API token: https://huggingface.co/settings/tokens")
# print("2. Create a .env file with: HUGGINGFACE_API_TOKEN=your_token_here")
# print("3. Or set environment variable: export HUGGINGFACE_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
# Initialize the system
logger.info("🕉️ Initializing KarmaCheck...")
initialize_system()
# Create and launch interface
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")
# Launch Gradio interface
interface.launch(
share=False, # Creates public URL for sharing
server_name="0.0.0.0", # Localhost access
server_port=7860,
show_error=True,
inbrowser=True # Automatically opens browser
)
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()
|