Update app.py
Browse files7 unmodified lines89101112131 unmodified line151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251267 unmodified linesfrom groq import Groqlogging.basicConfig(stream=sys.stdout, level=logging.INFO)app = Flask(__name__)CORS(app, resources={r"/*": {"origins": "*"}})1 unmodified linellm = Nonedef load_mPAIRS_engine():global db, llmif db is None:try:logging.info("Starting mPAIRS Brain Sync...")embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2",model_kwargs={'device': 'cpu'},encode_kwargs={'normalize_embeddings': True})# Checks the folder first, falls back to root if necessarydb_path = "GST_Stable_Brain"if not os.path.exists(db_path):db_path = "."db = FAISS.load_local(db_path,embeddings,allow_dangerous_deserialization=True)llm = Groq(api_key=os.getenv("GROQ_API_KEY"))logging.info(" β mPAIRS Brain Synchronized (V2)")except Exception as e:logging.error(f"Initialization Error: {str(e)}")db = Noneraise ereturn db, llm@app.route("/", methods=["GET"])def home():return jsonify({"status": "mPAIRS V2 Online"})@app.route('/ask', methods=['POST', 'OPTIONS'])def ask():if request.method == 'OPTIONS':response = make_response()response.headers.add("Access-Control-Allow-Origin", "*")response.headers.add("Access-Control-Allow-Headers", "Content-Type")response.headers.add("Access-Control-Allow-Methods", "POST, OPTIONS")return responsetry:engine_db, engine_llm = load_mPAIRS_engine()data = request.jsonuser_query = data.get("query") or data.get("question") or ""docs = engine_db.similarity_search(user_query, k=15)context_text = "\n".join([d.page_content for d in docs])# RESTORED: Your original personality profile and institutional instructionsfull_prompt = f"""You are mPAIRS, a Senior GST Advisor. Your personality is helpful, insightful, and supportiveβlike a senior colleague who knows the SOP by heart.[INSTRUCTION]1. Primary Goal: Answer the user's question using the SOP CONTEXT provided.2. Smart Reasoning: Agar exact "Step-by-step" procedure nahi hai, toh context mein di gayi Rules, Section numbers, Eligibility, aur Annexures ki information use karke ek professional Advisor like advice dein.3. [b]1-3-1 Institutional Roles:[/b]: Answer mein batayein ki responsibility of Accounts Manager-AIAM , responsibility of CFO-AICFO aur responsibility of CEO-AICEO ko kya dhyaan rakhna hai (Audit-proof approach).(Do NOT use generic advice. For each role, mention a specific document or "Step" they must execute, form, or action found in the context as mentioned below for each role as an example. Include the steps for each role as mentioned in the Monthly artifacts.)- [b]AIAM (Account Manager Responsibility):[/b] Identify the specific "Artifact" and mention their work like, a) GSTR-3B Draft Worksheet b) ITC Reconciliation Statement (Books vs GSTR-2B) c) Blocked Credit Register- [b]AICFO (CFO Responsibility):[/b] Specify what they must cross-check against the Law or SOP like, a) Cash Flow Projection (including GST outflow) b) GSTR-3B Approval Sheet with comments (e.g., 'Reconcile CMP-08 with Bank records').- [b]AICEO (CEO Responsibility):[/b] State the oversight required to prevent penalties like, a) Executive GST Compliance Summary (1-page) b) Compliance status (π’ Green / π‘ Amber / π΄ Red) c) Key metrics (ITC %, GST cost %, Pending issues)4. Strictly NO Internet: Sirf context ki baatein karein. Agar context bilkul silent hai, tabhi "Not covered" bolein.[STRICT AUDIT FILING TEMPLATE]Every response must follow this EXACT structure without exception:1. [b]Direct Advisor Answer[/b]: (Concise summary)2. [b]Procedural Steps[/b]: (Numbered 1, 2, 3... sequence of actions)3. [b]Institutional Roles (1-3-1)[/b]: (AIAM, AICFO, AICEO specific duties)4. [b]Mandatory Artifacts[/b]: (List of documents required for the audit trail)5. [b]Compliance Status[/b]: (π’ Green / π‘ Amber / π΄ Red logic)6. [b]Reference[/b]: (SOP Page numbers)STYLE RULES:- Answer in the same language as question.- Use [b]BBCode bolding[/b] for key terms.- Direct answer first.CONTEXT:{context_text}QUESTION:{user_query}"""chat_completion = engine_llm.chat.completions.create(messages=[{"role": "user", "content": full_prompt}],model="llama-3.1-8b-instant",temperature=0.0)res = jsonify({"answer": chat_completion.choices[0].message.content,"status": "success"})res.headers.add("Access-Control-Allow-Origin", "*")return resexcept Exception as e:logging.error(f"Handshake Error: {str(e)}")return jsonify({"error": str(e)}), 500if __name__ == "__main__":app.run(host="0.0.0.0", port=7860)7 unmodified lines891011121314151 unmodified line17181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022037 unmodified linesfrom groq import Groqlogging.basicConfig(stream=sys.stdout, level=logging.INFO)logger = logging.getLogger(__name__)app = Flask(__name__)CORS(app, resources={r"/*": {"origins": "*"}})1 unmodified linellm = Nonedef load_mPAIRS_engine():"""Load or initialize the mPAIRS brain and LLM."""global db, llmif db is not None and llm is not None:logger.info("β mPAIRS engine already loaded")return db, llmtry:logger.info("π Starting mPAIRS Brain Sync...")# Initialize embeddingslogger.info("π¦ Loading HuggingFace embeddings (all-MiniLM-L6-v2)...")embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2",model_kwargs={'device': 'cpu'},encode_kwargs={'normalize_embeddings': True})logger.info("β Embeddings loaded")# Find FAISS databasedb_paths = ["GST_Stable_Brain","./GST_Stable_Brain","/app/GST_Stable_Brain",".",]loaded_db = Nonefor db_path in db_paths:if os.path.exists(db_path):try:logger.info(f"π Attempting to load FAISS from: {db_path}")loaded_db = FAISS.load_local(db_path,embeddings,allow_dangerous_deserialization=True)logger.info(f"β FAISS database loaded from: {db_path}")db = loaded_dbbreakexcept Exception as e:logger.warning(f"β οΈ Failed to load from {db_path}: {str(e)}")continueif db is None:raise Exception(f"FAISS database not found in any of: {db_paths}")# Initialize GROQ LLMgroq_api_key = os.getenv("GROQ_API_KEY")if not groq_api_key:raise Exception("GROQ_API_KEY environment variable not set")logger.info("π€ Initializing GROQ LLM...")llm = Groq(api_key=groq_api_key)logger.info("β GROQ LLM initialized")logger.info("β β β mPAIRS V2 Brain Synchronized Successfully!")return db, llmexcept Exception as e:logger.error(f"β Initialization Error: {str(e)}")db = Nonellm = Noneraise e@app.route("/", methods=["GET"])def home():"""Health check endpoint."""return jsonify({"status": "mPAIRS V2 Online","version": "2.0","engine": "llama-3.1-8b-instant"})@app.route('/ask', methods=['POST', 'OPTIONS'])def ask():"""Main GST advisory endpoint."""# Handle CORS preflightif request.method == 'OPTIONS':response = make_response()response.headers.add("Access-Control-Allow-Origin", "*")response.headers.add("Access-Control-Allow-Headers", "Content-Type")response.headers.add("Access-Control-Allow-Methods", "POST, OPTIONS")return response, 200try:# Load enginesengine_db, engine_llm = load_mPAIRS_engine()# Parse requestdata = request.jsonif not data:return jsonify({"error": "No JSON body provided"}), 400user_query = data.get("query") or data.get("question") or ""if not user_query or user_query.strip() == "":return jsonify({"error": "Empty query"}), 400logger.info(f"[QUERY] {user_query[:100]}...")# Similarity searchlogger.info("π Performing similarity search...")docs = engine_db.similarity_search(user_query, k=15)logger.info(f"π Retrieved {len(docs)} documents")context_text = "\n".join([d.page_content for d in docs])# Build prompt with mPAIRS institutional frameworkfull_prompt = f"""You are mPAIRS, a Senior GST Advisor. Your personality is helpful, insightful, and supportiveβlike a senior colleague who knows the SOP by heart.[INSTRUCTION]1. Primary Goal: Answer the user's question using the SOP CONTEXT provided.2. Smart Reasoning: Agar exact "Step-by-step" procedure nahi hai, toh context mein di gayi Rules, Section numbers, Eligibility, aur Annexures ki information use karke ek professional Advisor like advice dein.3. [b]1-3-1 Institutional Roles:[/b]: Answer mein batayein ki responsibility of Accounts Manager-AIAM , responsibility of CFO-AICFO aur responsibility of CEO-AICEO ko kya dhyaan rakhna hai (Audit-proof approach).(Do NOT use generic advice. For each role, mention a specific document or "Step" they must execute, form, or action found in the context as mentioned below for each role as an example. Include the steps for each role as mentioned in the Monthly artifacts.)- [b]AIAM (Account Manager Responsibility):[/b] Identify the specific "Artifact" and mention their work like, a) GSTR-3B Draft Worksheet b) ITC Reconciliation Statement (Books vs GSTR-2B) c) Blocked Credit Register- [b]AICFO (CFO Responsibility):[/b] Specify what they must cross-check against the Law or SOP like, a) Cash Flow Projection (including GST outflow) b) GSTR-3B Approval Sheet with comments (e.g., 'Reconcile CMP-08 with Bank records').- [b]AICEO (CEO Responsibility):[/b] State the oversight required to prevent penalties like, a) Executive GST Compliance Summary (1-page) b) Compliance status (π’ Green / π‘ Amber / π΄ Red) c) Key metrics (ITC %, GST cost %, Pending issues)4. Strictly NO Internet: Sirf context ki baatein karein. Agar context bilkul silent hai, tabhi "Not covered" bolein.[STRICT AUDIT FILING TEMPLATE]Every response must follow this EXACT structure without exception:1. [b]Direct Advisor Answer[/b]: (Concise summary)2. [b]Procedural Steps[/b]: (Numbered 1, 2, 3... sequence of actions)3. [b]Institutional Roles (1-3-1)[/b]: (AIAM, AICFO, AICEO specific duties)4. [b]Mandatory Artifacts[/b]: (List of documents required for the audit trail)5. [b]Compliance Status[/b]: (π’ Green / π‘ Amber / π΄ Red logic)6. [b]Reference[/b]: (SOP Page numbers)STYLE RULES:- Answer in the same language as question.- Use [b]BBCode bolding[/b] for key terms.- Direct answer first.CONTEXT:{context_text}QUESTION:{user_query}"""logger.info("π¬ Calling GROQ LLM...")# Call LLMchat_completion = engine_llm.chat.completions.create(messages=[{"role": "user", "content": full_prompt}],model="llama-3.1-8b-instant",temperature=0.0)answer = chat_completion.choices[0].message.contentlogger.info(f"β Answer generated ({len(answer)} chars)")# Return response with CORS headersres = jsonify({"answer": answer,"status": "success","model": "llama-3.1-8b-instant"})res.headers.add("Access-Control-Allow-Origin", "*")return res, 200except Exception as e:error_msg = str(e)logger.error(f"β Handshake Error: {error_msg}")res = jsonify({"error": error_msg,"status": "failed"})res.headers.add("Access-Control-Allow-Origin", "*")return res, 500if __name__ == "__main__":logger.info("π Starting mPAIRS Flask Server...")app.run(host="0.0.0.0", port=7860, debug=False)
app.py+142-65