Spaces:
Sleeping
Sleeping
| import os | |
| import json | |
| import logging | |
| from flask import Flask, request, jsonify | |
| from flask_cors import CORS | |
| from datetime import datetime | |
| import requests | |
| # Configure logging | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| app = Flask(__name__) | |
| CORS(app) # Enable CORS for all routes | |
| # Configure Groq API (LLaMA 3.1 8B Instant) | |
| GROQ_API_KEY = os.getenv("GROQ_API_KEY") | |
| GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions" | |
| MODEL_NAME = "llama-3.1-8b-instant" | |
| # ISKCON Knowledge Base Summary | |
| ISKCON_KNOWLEDGE_BASE = """ | |
| You are an ISKCON monk trained in Srila Prabhupada's teachings. | |
| Speak with devotion, humility, and deep Vedic insight. | |
| Your tone should be compassionate, scholarly, and practical. | |
| Core principles: | |
| - Krishna is the Supreme Personality of Godhead. | |
| - The soul is an eternal servant of Krishna. | |
| - Chanting the holy names purifies the heart. | |
| - Bhakti (devotion) is the ultimate goal of life. | |
| Avoid irrelevant topics; stay spiritually meaningful. | |
| """ | |
| def get_spiritual_response(question): | |
| """Generate spiritual response using LLaMA 3.1 8B via Groq API""" | |
| prompt = f""" | |
| {ISKCON_KNOWLEDGE_BASE} | |
| Question: {question} | |
| Please respond as an enlightened ISKCON monk. | |
| Answer in at least **three meaningful paragraphs**, beginning with "Answer -". | |
| Each paragraph should have a distinct purpose: | |
| 1. Explain the philosophical foundation from scriptures. | |
| 2. Give a practical devotional perspective or real-life application. | |
| 3. Conclude with an uplifting or meditative reflection encouraging bhakti and remembrance of Krishna. | |
| 4.answer in less than 3-4 lines. | |
| Use a warm, humble tone infused with devotion. | |
| """ | |
| headers = { | |
| "Authorization": f"Bearer {GROQ_API_KEY}", | |
| "Content-Type": "application/json" | |
| } | |
| data = { | |
| "model": MODEL_NAME, | |
| "messages": [ | |
| {"role": "system", "content": ISKCON_KNOWLEDGE_BASE}, | |
| {"role": "user", "content": prompt} | |
| ], | |
| "temperature": 0.8, | |
| "max_tokens": 500 | |
| } | |
| try: | |
| response = requests.post(GROQ_API_URL, headers=headers, json=data) | |
| response.raise_for_status() | |
| result = response.json() | |
| answer = result["choices"][0]["message"]["content"].strip() | |
| return answer | |
| except Exception as e: | |
| logger.error(f"Error generating response: {str(e)}") | |
| return ( | |
| "Answer - Apologies, I’m experiencing technical issues. " | |
| "Please try again soon. Continue chanting Hare Krishna. Hare Krishna." | |
| ) | |
| def health_check(): | |
| return jsonify({ | |
| 'status': 'healthy', | |
| 'service': 'ISKCON Spiritual Bot (LLaMA 3.1)', | |
| 'timestamp': datetime.now().isoformat() | |
| }) | |
| def chat(): | |
| try: | |
| data = request.get_json() | |
| if not data or 'question' not in data: | |
| return jsonify({'success': False, 'error': 'No question provided'}), 400 | |
| question = data['question'].strip() | |
| if not question: | |
| return jsonify({'success': False, 'error': 'Question cannot be empty'}), 400 | |
| if len(question) > 1000: | |
| return jsonify({'success': False, 'error': 'Question too long (max 1000 chars)'}), 400 | |
| inappropriate_keywords = ['sex', 'drug', 'alcohol', 'violence', 'hate'] | |
| if any(word in question.lower() for word in inappropriate_keywords): | |
| return jsonify({ | |
| 'success': True, | |
| 'answer': 'Answer - Please ask spiritual or philosophical questions within Vedic principles. Hare Krishna.' | |
| }) | |
| logger.info(f"Processing spiritual question: {question[:100]}...") | |
| answer = get_spiritual_response(question) | |
| logger.info("Spiritual response generated successfully") | |
| return jsonify({ | |
| 'success': True, | |
| 'answer': answer, | |
| 'timestamp': datetime.now().isoformat() | |
| }) | |
| except Exception as e: | |
| logger.error(f"Error in chat endpoint: {str(e)}") | |
| return jsonify({ | |
| 'success': False, | |
| 'error': 'Technical issue. Please try again later. Hare Krishna.' | |
| }), 500 | |
| def get_examples(): | |
| examples = [ | |
| "What is the purpose of human life according to Vedic scriptures?", | |
| "How can I develop devotion to Krishna in daily life?", | |
| "What is the role of a spiritual master in Krishna consciousness?", | |
| "How do we understand karma and its effects?", | |
| "What is the difference between the soul and the body?", | |
| "How can one balance material responsibilities with spiritual practice?", | |
| "What is the significance of chanting Hare Krishna?", | |
| "How does one surrender to Krishna while living in the material world?", | |
| "What is the meaning of bhakti yoga?", | |
| "How should a devotee deal with material attachments?" | |
| ] | |
| return jsonify({'success': True, 'examples': examples}) | |
| def about(): | |
| return jsonify({ | |
| 'name': 'ISKCON Spiritual Bot', | |
| 'description': 'AI-powered spiritual guidance based on ISKCON teachings using LLaMA 3.1 8B Instant', | |
| 'teachings_based_on': [ | |
| 'Srila Prabhupada\'s books', | |
| 'Bhagavad Gita', | |
| 'Srimad Bhagavatam', | |
| 'Chaitanya Charitamrita', | |
| 'Vedic scriptures' | |
| ], | |
| 'capabilities': [ | |
| 'Spiritual philosophy questions', | |
| 'Practical devotional guidance', | |
| 'Scriptural explanations', | |
| 'Bhakti-based life advice' | |
| ], | |
| 'version': '1.2.0' | |
| }) | |
| def not_found(error): | |
| return jsonify({'success': False, 'error': 'Endpoint not found'}), 404 | |
| def internal_error(error): | |
| return jsonify({'success': False, 'error': 'Internal server error. Hare Krishna.'}), 500 | |
| if __name__ == '__main__': | |
| port = int(os.environ.get('PORT', 5000)) | |
| debug_mode = os.environ.get('FLASK_ENV') == 'development' | |
| logger.info("Starting ISKCON Spiritual Bot API server with LLaMA 3.1...") | |
| app.run(host='0.0.0.0', port=port, debug=debug_mode) | |