Spaces:
Sleeping
Sleeping
Download backend/layer3_reasoning.py from Lvvbaaal/legalgpt-api: direct link, hf CLI and curl.
- Browser
- Download file 51.9 kB
-
https://huggingface.co/spaces/Lvvbaaal/legalgpt-api/resolve/main/backend/layer3_reasoning.py
- Command line
-
hf download hf://spaces/Lvvbaaal/legalgpt-api/backend/layer3_reasoning.py
-
curl -L -o layer3_reasoning.py https://huggingface.co/spaces/Lvvbaaal/legalgpt-api/resolve/main/backend/layer3_reasoning.py
51.9 kB
| """ | |
| SAULSGPT — LAYER 3: REASONING ENGINE | |
| ======================================= | |
| Techniques: | |
| 1. Chain of Thought (CoT) Prompting | |
| Forces step by step legal reasoning | |
| Facts → Issues → Law → Outcome | |
| 2. Mode Specific Output Formats | |
| Knowledge → plain explanation | |
| Analysis → structured case analysis | |
| Document → formal document draft | |
| Pathfinder → numbered step by step | |
| 3. Ambiguity Handler | |
| If Layer 1 flagged query as ambiguous | |
| returns clarifying question instead | |
| 4. Repealed Law Warning | |
| Checks is_repealed flag from Layer 2 | |
| Forces LLM to warn user prominently | |
| 5. Knowledge Graph Context ← NEW | |
| Reads graph_context from layer1_payload | |
| Appended as SYSTEM RULES block in prompt | |
| Tells LLM about law replacements and | |
| relationships before it generates answer | |
| 6. Groq API inference (replaces local Ollama) | |
| 800+ tokens/second vs 3 minutes locally | |
| 7. Graceful Fallback | |
| If LLM fails returns retrieval summary | |
| Never crashes pipeline | |
| Input: layer1_payload dict + layer2_results list | |
| Output: final validated legal response string | |
| Run standalone to test: | |
| python layer3_reasoning.py | |
| When used by pipeline_orchestrator.py: | |
| from layer3_reasoning import generate_legal_response | |
| response = generate_legal_response(layer1_payload, layer2_results) | |
| """ | |
| import os | |
| import re | |
| import json | |
| from dotenv import load_dotenv | |
| load_dotenv(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ".env")) | |
| from langchain_groq import ChatGroq | |
| from langchain_core.prompts import PromptTemplate | |
| # ───────────────────────────────────────────────────────────── | |
| # CONFIG | |
| # ───────────────────────────────────────────────────────────── | |
| LLM_MODEL = os.environ.get("GROQ_MODEL", "qwen/qwen3.8-27b") | |
| TEMPERATURE = 0.1 | |
| # ───────────────────────────────────────────────────────────── | |
| # ABBREVIATION MAP — Fixes "Keyword Trapped" hallucinations | |
| # Expands _from_db abbreviations to full act names before | |
| # the LLM ever sees them, so it never sees "IEA_from_db" | |
| # and hallucinates "Indian Easements Act" instead of | |
| # "Indian Evidence Act" | |
| # ───────────────────────────────────────────────────────────── | |
| ACT_NAME_MAP = { | |
| "IEA_from_db": "Indian Evidence Act, 1872", | |
| "IPC_from_db": "Indian Penal Code, 1860", | |
| "CRPC_from_db": "Code of Criminal Procedure, 1973", | |
| "CPC_from_db": "Code of Civil Procedure, 1908", | |
| "NIA_from_db": "Negotiable Instruments Act, 1881", | |
| "HMA_from_db": "Hindu Marriage Act, 1955", | |
| "MVA_from_db": "Motor Vehicles Act, 1988", | |
| "IDA_from_db": "Indian Divorce Act, 1869", | |
| "BNS_from_db": "Bharatiya Nyaya Sanhita, 2023 (BNS)", | |
| "BNSS_from_db": "Bharatiya Nagarik Suraksha Sanhita, 2023 (BNSS)", | |
| "BSA_from_db": "Bharatiya Sakshya Adhiniyam, 2023 (BSA)", | |
| "indian_penal_code": "Indian Penal Code, 1860", | |
| "indian_constitution": "Constitution of India", | |
| } | |
| def expand_act_name(raw_name: str) -> str: | |
| """Expand abbreviated act name to full human-readable name.""" | |
| if not raw_name: | |
| return "Unknown Act" | |
| clean = raw_name.strip().replace(".json", "") | |
| return ACT_NAME_MAP.get(clean, raw_name) | |
| import os | |
| from key_context import get_effective_groq_key | |
| def get_reasoning_llm(): | |
| return ChatGroq( | |
| model_name=LLM_MODEL, | |
| api_key=get_effective_groq_key(), | |
| temperature=TEMPERATURE, | |
| max_tokens=2048 | |
| ) | |
| # ───────────────────────────────────────────────────────────── | |
| # PROMPT TEMPLATES — ONE PER MODE | |
| # ───────────────────────────────────────────────────────────── | |
| KNOWLEDGE_PROMPT = """ | |
| You are SaulGPT, an Indian Legal Knowledge Assistant. | |
| Your job is to explain the law clearly based ONLY on the retrieved sections below. | |
| USER QUERY: {user_query} | |
| RETRIEVED LEGAL SECTIONS: | |
| {context} | |
| CHAIN OF THOUGHT — think through these steps before answering: | |
| Step 1: What legal concept is the user asking about? | |
| Step 2: Which retrieved section best explains this concept? | |
| Step 3: What does that section say in simple terms? | |
| Step 4: Are there any important exceptions or conditions? | |
| <strict_rules> | |
| - CRITICAL DIRECTIVE — FACT FIRST: SOURCE blocks are provided. You MUST list the statutory requirements, sections, or facts from the text BEFORE showing empathy or asking follow-up questions. Never summarize away the legal elements. Start with the legal position, then add context. Example: Good — "Under Section 138, you must send a demand notice within 30 days." Bad — "That sounds frustrating. Can you tell me more about what happened?" | |
| - Ground your answer primarily in the provided legal sources. Where specific procedures or constitutional protections (such as arrest rights under Article 22, D.K. Basu guidelines, FIR procedures under Section 154 CrPC / 173 BNSS) are standard settled Indian law, explain them with precision, clarity, and relevant statutory sections. | |
| - AMBIGUOUS SECTION RULE: If the same section number (e.g., Section 10) appears from DIFFERENT Acts (e.g., Contract Act AND CPC), and the user did not specify which Act, acknowledge the ambiguity: "Section 10 appears in multiple Acts. Without specifying the Act, here are all relevant provisions:" then list each with its Act name. | |
| - SOURCE PRIORITY RULE: When SOURCE blocks from "Live Web Search" or external legal guides are present, use the legal principles, consumer rules, and statutory remedies in those sources to answer the query directly. | |
| - If the retrieved sources or web results address the legal topic, treat context_sufficient as true and explain the legal rights, seller/platform obligations, and dispute remedies clearly. | |
| - Calm Authoritative Confidence: Deliver settled Indian legal principles directly and authoritatively. NEVER mention internal retrieval mechanics or tell the user "I do not have enough specific legal context" or "the retrieved sections do not apply". | |
| - If any section has STATUS: WARNING REPEALED you MUST say at the very start: "WARNING: This law has been replaced. Please refer to the updated legislation." | |
| - Match the user's language: If the query is in Hindi / Hinglish or regional language, respond in fluent, accurate, and easy-to-understand Hindi (Devanagari) or bilingual English-Hindi format. Otherwise use plain simple English. | |
| - Cite Act name, Rules, or Section numbers where available from the context. | |
| - PLAIN-ENGLISH CLARITY MANDATE (HEART OF THE MEANING FOR CITIZENS): When technical legal concepts, evidence rules, or procedural terms appear (such as 'Evidence Admissibility', 'Procedural Law', 'Substantive Law', 'Limitation Period', 'Burden of Proof', 'Condition Precedent', 'Estoppel', 'Injunction', 'Ex-Parte', 'Cognizable/Non-Bailable'), you MUST provide the 'heart of the meaning' in simple, everyday English directly in the subheadings or in parentheses (e.g., '### Evidence Admissibility: Evidence which the court allows you to use', '### Procedural Law: Step-by-step rules to file and run a case in court', 'Limitation Period (the legal deadline to file your case before losing the right)'). Ensure everyday citizens can understand every concept instantly. | |
| - Do NOT give personal legal advice. | |
| - Do NOT use phrases like "you should" or "you must". | |
| - Use procedural language: "the law provides", "under the Consumer Protection Act", "the E-Commerce Rules state". | |
| - End with: "Disclaimer: This response provides general procedural information based on Indian law and does not constitute legal advice. Please consult a qualified lawyer for your specific situation." | |
| </strict_rules> | |
| SEMANTIC VERIFICATION GATE — Mandatory before you output any section: | |
| 1. Read the user's scenario carefully. Identify who the parties are (e.g., landlord-tenant, employer-employee, buyer-seller, neutral stakeholder vs claimant). | |
| 2. For EACH retrieved section, check: does the legal relationship described in this statute/source relate to the user's scenario? | |
| 3. If specific factual nuances require clarification, explain the core legal framework directly, then ask relevant questions. Never tell the user that the retrieved texts do not apply. | |
| 4. If confused between Indian Easements Act and Indian Evidence Act: verify the actual ACT name carefully. "IEA" means "Indian Evidence Act, 1872", NOT "Indian Easements Act". | |
| CRITICAL: DO NOT print, echo, or acknowledge the <strict_rules> or SEMANTIC VERIFICATION GATE or CONTENT VERDICT in your final output. Begin your response immediately with the legal explanation. | |
| ═══════════════════════════════ | |
| CONTENT VERDICT — Output this JSON on the very first line of your response. | |
| Then write your answer below it, on a new line. | |
| ═══════════════════════════════ | |
| {{ | |
| "context_sufficient": true | false, | |
| "chunks_are_on_point": true | false, | |
| "reasoning": "<one sentence: do the chunks or web sources provide the answer to the user's query?>" | |
| }} | |
| context_sufficient: true if the local chunks OR web search sources explain the legal topic/rights. false only if completely empty or missing. | |
| chunks_are_on_point: true if the content addresses the user's situation. | |
| Then write your answer on the next line. | |
| ═══════════════════════════════ | |
| YOUR EXPLANATION: | |
| """ | |
| ANALYSIS_PROMPT = """ | |
| You are SaulGPT, an Indian Legal Case Analyst and Counselor. | |
| Analyze the client's situation using the retrieved legal sections below. | |
| USER QUERY: {user_query} | |
| LEGAL DOMAIN: {domain} | |
| RETRIEVED LEGAL SECTIONS: | |
| {context} | |
| CHAIN OF THOUGHT — work through these steps: | |
| Step 1: What is the client's core grievance or question? | |
| Step 2: What legal rights and liabilities arise from these facts? | |
| Step 3: Which retrieved sections directly apply to this relationship? | |
| Step 4: What procedural options or realistic outcomes exist under Indian law? | |
| Step 5: What is the practical, tactical next step for the client? | |
| FORMAT YOUR RESPONSE AS AN AUTHORITATIVE, PRACTICAL LEGAL BRIEF: | |
| ### ⚖️ Legal Assessment & Your Position | |
| [Directly address the user as 'you'. In 2-3 clear sentences, state the legal position under Indian law, their statutory rights, and immediate exposure. NEVER say 'The user states...', 'The user is asking...', or 'FACTS:'. Address the client directly as 'you' on word one.] | |
| ### 📜 Governing Law & Statutory Framework | |
| [Cite each applicable section with Act name, Section number, and core principle with plain-English parentheticals. Explain how the law applies directly to their situation.] | |
| ### 🏛️ Practical Procedure & Realistic Outcome | |
| [Explain the step-by-step procedural reality: what forum to approach, standard timelines, and what the law realistically delivers in terms of recovery, compensation, or penalty.] | |
| ### 🎯 Strategic Next Move | |
| [State the exact immediate procedural move to protect limitation and lock in liability, such as issuing a formal demand notice or lodging a complaint.] | |
| <strict_rules> | |
| - DIRECT ADDRESS MANDATE: Address the client directly as 'you' from word one. NEVER begin with third-person throat-clearing such as "The user is asking...", "The user states...", or "In this matter the user...". | |
| - Answer using the retrieved sections and verified legal principles. | |
| - Calm Authoritative Confidence: Deliver the established legal position under Indian law directly and authoritatively. Never say "I do not have enough specific legal context" or leak retrieval limitations to the client. | |
| - If any section has STATUS: WARNING REPEALED start with a prominent warning. | |
| - CITE BINDING PRECEDENT RATIOS: When SOURCE blocks marked 'BINDING JUDICIAL PRECEDENT' or containing 'Ratio Decidendi' are retrieved, you MUST cite the official case name, Law Report citation (e.g. (2019) 4 SCC 197), and explain how the binding ratio decidendi governs the dispute. | |
| - End with: "Disclaimer: This response provides general procedural information based on Indian law and does not constitute formal legal advice. Please consult a qualified lawyer for your specific situation." | |
| </strict_rules> | |
| SEMANTIC VERIFICATION GATE — Mandatory before you output any section: | |
| 1. Read the client's scenario carefully. Identify who the parties are and the legal relationship involved. | |
| 2. For EACH retrieved section, check: does the legal relationship described in this statute EXACTLY match the client's scenario? | |
| 3. If the relationship does NOT match (e.g., interpleader statute about neutral stakeholders when user is a freelancer demanding their own wages), DISCARD that section. Do NOT mention it. | |
| 4. If specific factual details are needed, state the governing legal standard directly, then ask the relevant question. Never say "The retrieved legal sections do not apply". | |
| 5. "IEA" is "Indian Evidence Act, 1872", NOT "Indian Easements Act". Verify act names carefully. | |
| CRITICAL: DO NOT print, echo, or acknowledge the <strict_rules> or SEMANTIC VERIFICATION GATE or CONTENT VERDICT in your final output. Begin your response immediately with your legal assessment addressing the user directly as "you". | |
| ═══════════════════════════════ | |
| CONTENT VERDICT — Output this JSON on the very first line of your response. | |
| Then write your analysis below it, on a new line. | |
| ═══════════════════════════════ | |
| {{ | |
| "context_sufficient": true | false, | |
| "chunks_are_on_point": true | false, | |
| "reasoning": "<one sentence>" | |
| }} | |
| ═══════════════════════════════ | |
| YOUR ANALYSIS: | |
| """ | |
| CONVERSATIONAL_SPARRING_PROMPT = """ | |
| You are SaulGPT, serving as Senior Legal Counsel and Sparring Partner to the client under Indian Law. | |
| The client is asking a follow-up question, seeking practical clarification, questioning a procedural step, or pushing back against going to court. | |
| USER FOLLOW-UP / CHALLENGE: {user_query} | |
| LEGAL DOMAIN: {domain} | |
| RETRIEVED LEGAL SECTIONS & PRECEDENTS: | |
| {context} | |
| YOUR ROLE AS PRACTICAL COUNSELOR & SPARRING PARTNER: | |
| 1. Direct Address: Address the client directly as "you" from word one. NEVER say "The user is asking...", "The query concerns...", or "In this case...". Speak to them as their senior advocate across the desk. | |
| 2. Adaptive Length: Deliver a crisp, punchy, and authoritative response in 2 to 4 focused paragraphs. Do NOT use giant academic headings or bloated boilerplate. | |
| 3. Tactical "Why": Explain the real-world strategic reasoning behind legal rules (e.g. why statutory demand notice under Sec 138 NI Act is non-negotiable before criminal court, why Section 18 Limitation Act requires written admission, why police need Section 173 BNSS formal complaint, or how litigation costs vs settlement leverage work). | |
| 4. Sparring & Pushback Handling: | |
| - If the client is reluctant to go to court or wants alternatives ("I don't feel like suing", "Can I just settle?"): Acknowledge it candidly, lay out the settlement / ADR / mediation leverage, explain the trade-offs, and show how a sharp legal notice or ombudsman complaint creates maximum settlement pressure without having to step into court immediately. | |
| - If the client questions or challenges a rule ("Why?", "For what?", "What happens if I don't?"): Hold ground firmly on mandatory legal requirements, explain the courtroom consequence of skipping it (e.g. petition dismissed with costs, loss of cause of action), and offer the cleanest pragmatic workaround. | |
| 5. In-line Statutory Grounding: Mention governing Indian Acts and Sections naturally in the prose with simple parenthetical meanings (e.g., Section 138 NI Act, Section 18 Limitation Act, Section 63 BSA). | |
| <strict_rules> | |
| - DIRECT ADDRESS MANDATE: Address the client directly as 'you' from word one. NEVER begin with third-person throat-clearing ("The user asks...", "The client inquires..."). | |
| - Do NOT use rigid headers like FACTS:, LEGAL ISSUES:, APPLICABLE LAW:. Keep it as natural, punchy counselor dialogue. | |
| - End with: "Disclaimer: This guidance provides procedural insights under Indian law and does not constitute formal legal advice. Please consult an advocate for court representation." | |
| </strict_rules> | |
| ═══════════════════════════════ | |
| CONTENT VERDICT — Output this JSON on the very first line of your response. | |
| Then write your answer below it, on a new line. | |
| ═══════════════════════════════ | |
| {{ | |
| "context_sufficient": true | false, | |
| "chunks_are_on_point": true | false, | |
| "reasoning": "<one sentence>" | |
| }} | |
| ═══════════════════════════════ | |
| YOUR COUNSEL: | |
| """ | |
| DOCUMENT_PROMPT = """ | |
| You are SaulGPT, an Indian Legal Document Drafting Assistant. | |
| Draft a formal legal document based ONLY on the retrieved sections and user details below. | |
| USER REQUEST: {user_query} | |
| LEGAL DOMAIN: {domain} | |
| RETRIEVED LEGAL SECTIONS: | |
| {context} | |
| CHAIN OF THOUGHT: | |
| Step 1: What type of document does the user need? | |
| Step 2: Which retrieved sections govern this type of document? | |
| Step 3: What is the correct format and required elements? | |
| Step 4: Draft the document with correct legal language | |
| FORMAT YOUR RESPONSE AS A FORMAL DOCUMENT: | |
| [DOCUMENT TYPE] | |
| Date: [Date] | |
| To: [Recipient Authority] | |
| From: [Sender — user to fill in] | |
| Subject: [Clear subject line] | |
| [BODY — formal legal language citing relevant sections] | |
| [CLOSING] | |
| [Signature block — user to fill in] | |
| <strict_rules> | |
| - Use formal legal language throughout. | |
| - Cite specific Act and Section numbers in the body. | |
| - Mark all blanks clearly with [brackets] for user to fill. | |
| - If any retrieved law is REPEALED warn before the document. | |
| - Never give personal legal advice in the document body. | |
| - End with: "Disclaimer: This is a draft template only. Please verify all legal citations with a qualified lawyer before submission. This does not constitute legal advice." | |
| </strict_rules> | |
| SEMANTIC VERIFICATION GATE — Mandatory before you draft: | |
| 1. Verify the legal relationship in each retrieved section matches the document the user needs. | |
| 2. If a section does not match the document type, discard it. | |
| 3. "IEA" is "Indian Evidence Act, 1872", NOT "Indian Easements Act". Verify act names carefully. | |
| CRITICAL: DO NOT print, echo, or acknowledge the <strict_rules> or SEMANTIC VERIFICATION GATE or CONTENT VERDICT in your final output. Begin your response immediately with the document. | |
| ═══════════════════════════════ | |
| CONTENT VERDICT — Output this JSON on the very first line of your response. | |
| Then write your document below it, on a new line. | |
| ═══════════════════════════════ | |
| {{ | |
| "context_sufficient": true | false, | |
| "chunks_are_on_point": true | false, | |
| "reasoning": "<one sentence>" | |
| }} | |
| ═══════════════════════════════ | |
| YOUR DOCUMENT DRAFT: | |
| """ | |
| PATHFINDER_PROMPT = """ | |
| You are SaulGPT, an Indian Legal Path Finder. | |
| Give clear step by step procedural guidance based ONLY on the retrieved sections below. | |
| USER QUERY: {user_query} | |
| LEGAL DOMAIN: {domain} | |
| RETRIEVED LEGAL SECTIONS: | |
| {context} | |
| CHAIN OF THOUGHT: | |
| Step 1: What legal process is the user asking about? | |
| Step 2: Which retrieved sections describe this process? | |
| Step 3: What is the correct sequence of steps? | |
| Step 4: What documents, timelines, and authorities are involved? | |
| FORMAT YOUR RESPONSE AS NUMBERED STEPS: | |
| LEGAL PROCESS: [Name of the process] | |
| Step 1: [Action to take] | |
| → Where: [Which office or authority] | |
| → What to carry: [Documents needed] | |
| → Timeline: [How long this step takes] | |
| Step 2: [Next action] | |
| → Where: [Which office or authority] | |
| → What to carry: [Documents needed] | |
| → Timeline: [How long this step takes] | |
| [Continue for all steps until process is complete] | |
| IMPORTANT NOTES: | |
| [Any exceptions, limitations, or critical things to know] | |
| <strict_rules> | |
| - Base steps ONLY on retrieved sections. | |
| - Cite the Section number that authorizes each step. | |
| - If any retrieved law is REPEALED warn prominently before steps. | |
| - Use procedural language only — no personal advice. | |
| - If process varies by state note this clearly. | |
| - End with: "Disclaimer: This response provides general procedural information based on Indian law and does not constitute legal advice. Please consult a qualified lawyer for your specific situation." | |
| </strict_rules> | |
| SEMANTIC VERIFICATION GATE — Mandatory before you output steps: | |
| 1. Verify the procedure described in each retrieved section matches the process the user asked about. | |
| 2. If a section describes a different process (e.g., interpleader vs unpaid wages), discard it. | |
| 3. "IEA" is "Indian Evidence Act, 1872", NOT "Indian Easements Act". Verify act names carefully. | |
| CRITICAL: DO NOT print, echo, or acknowledge the <strict_rules> or SEMANTIC VERIFICATION GATE or CONTENT VERDICT in your final output. Begin your response immediately with LEGAL PROCESS: | |
| ═══════════════════════════════ | |
| CONTENT VERDICT — Output this JSON on the very first line of your response. | |
| Then write your guide below it, on a new line. | |
| ═══════════════════════════════ | |
| {{ | |
| "context_sufficient": true | false, | |
| "chunks_are_on_point": true | false, | |
| "reasoning": "<one sentence>" | |
| }} | |
| ═══════════════════════════════ | |
| YOUR STEP BY STEP GUIDE: | |
| """ | |
| # ───────────────────────────────────────────────────────────── | |
| # ELASTIC BREVITY: DIRECT LOOKUP PROMPT (SALT OR SUGAR?) | |
| # ───────────────────────────────────────────────────────────── | |
| DIRECT_LOOKUP_PROMPT = """ | |
| You are SaulGPT, Indian Legal Intelligence. | |
| The user is asking a direct, specific legal question or classification (e.g. definition, comparison, whether an act is cognizable/bailable/illegal, or penalty/limitation). | |
| USER QUERY: {user_query} | |
| LEGAL DOMAIN: {domain} | |
| RETRIEVED LEGAL SECTIONS: | |
| {context} | |
| CRITICAL MANDATE — ELASTIC BREVITY (SALT OR SUGAR?): | |
| Deliver a crisp, punchy, 3 to 4 line micro-dose answer under 120 words total. | |
| DO NOT use giant academic headings like "### ⚖️ Legal Assessment", "### 📜 Governing Law", "### 🏛️ Practical Procedure", or "### 🎯 Strategic Next Move". | |
| DO NOT lecture the user, and NEVER output internal RAG hesitation phrases (e.g. "The retrieved text does not list..."). | |
| STRUCTURE YOUR 3-4 BULLET POINTS AS FOLLOWS: | |
| • **Core Verdict / Legal Definition**: Direct 1-sentence answer to the specific question. | |
| • **Governing Statutory Section**: Specific Section under BNS/BNSS/BSA (post-July 2024) and IPC/CrPC/IEA (pre-July 2024) in parentheses. | |
| • **Classification & Punishment**: Cognizable vs Non-cognizable, Bailable vs Non-bailable, and maximum statutory penalty. Take these ONLY from the OFFICIAL CLASSIFICATION block if present, per subsection where they differ. If no such block is present, say the classification depends on the exact subsection and the BNSS First Schedule; never guess, never say "generally". | |
| • **Citizen Bottom Line**: 1 practical sentence on what this means for an ordinary person. | |
| End with: | |
| Disclaimer: General procedural information under Indian law; does not constitute formal legal counsel. | |
| ═══════════════════════════════ | |
| CONTENT VERDICT — Output this JSON on the very first line of your response. | |
| Then write your answer below it, on a new line. | |
| ═══════════════════════════════ | |
| {{ | |
| "context_sufficient": true, | |
| "chunks_are_on_point": true, | |
| "reasoning": "Direct legal lookup answered crisply." | |
| }} | |
| ═══════════════════════════════ | |
| YOUR CRISP ANSWER: | |
| """ | |
| def is_direct_lookup_query(query: str) -> bool: | |
| """Detects whether a user query is a 'Salt or Sugar?' direct lookup, definition, comparison, or classification.""" | |
| q = query.strip().lower() | |
| words = q.split() | |
| if len(words) > 18: | |
| return False | |
| lookup_patterns = [ | |
| r"^(what|which)\s+(is|are)\s+(the\s+)?(difference|section|punishment|penalty|fine|sentence|law|limitation)", | |
| r"^what\s+about\s+", | |
| r"^is\s+.*(bailable|cognizable|compoundable|illegal|legal|an offence|a crime|punishable|valid|void)", | |
| r"^(can|does)\s+.*(be\s+punished|be\s+jailed|be\s+arrested)", | |
| r"^(tell me about|explain|define)\s+(theft|murder|cheating|robbery|extortion|defamation|assault|rape|bail|fir)", | |
| r".*\b(vs|versus|or)\b.*(murder|theft|robbery|cheating|bailable|cognizable)", | |
| r"^section\s+\d+", | |
| r".*\b(bailable or non-bailable|cognizable or non-cognizable)\b.*", | |
| ] | |
| return any(re.search(pat, q) for pat in lookup_patterns) | |
| MODE_PROMPTS = { | |
| "knowledge": KNOWLEDGE_PROMPT, | |
| "analysis": ANALYSIS_PROMPT, | |
| "document": DOCUMENT_PROMPT, | |
| "pathfinder": PATHFINDER_PROMPT, | |
| "conversational": CONVERSATIONAL_SPARRING_PROMPT, | |
| "sparring": CONVERSATIONAL_SPARRING_PROMPT, | |
| "direct_lookup": DIRECT_LOOKUP_PROMPT, | |
| } | |
| DEFAULT_MODE = "analysis" | |
| # ───────────────────────────────────────────────────────────── | |
| # CONTEXT FORMATTER | |
| # ───────────────────────────────────────────────────────────── | |
| # CHANGE FROM ORIGINAL: | |
| # Added layer1_payload parameter | |
| # Reads graph_context from it | |
| # Appends as SYSTEM RULES block after retrieved sections | |
| # This is the only change from the original file | |
| # Everything else is identical | |
| # ───────────────────────────────────────────────────────────── | |
| def format_context( | |
| layer2_results: list, | |
| layer1_payload: dict = None # ← NEW parameter | |
| ) -> str: | |
| """ | |
| Formats Layer 2 retrieval results into readable prompt context. | |
| Also appends Knowledge Graph insights if available. | |
| Args: | |
| layer2_results : list of result dicts from layer2_retrieval | |
| layer1_payload : dict from Layer 1 | |
| may contain graph_context from Layer 6 | |
| if None graph context is simply skipped | |
| Returns: | |
| formatted string ready for LLM prompt injection | |
| includes SYSTEM RULES block if graph_context present | |
| Example output: | |
| --- SOURCE 1 --- | |
| ACT: Payment of Wages Act | |
| SECTION: 15 | |
| STATUS: Active Law | |
| TEXT: ... | |
| --- KNOWLEDGE GRAPH SYSTEM RULES --- | |
| ⚠️ LAW UPDATE: IPC has been replaced by BNS 2023 | |
| --- END SYSTEM RULES --- | |
| """ | |
| if not layer2_results: | |
| return "No specific database chunks retrieved. Use settled statutory provisions of Indian Law (Constitution of India, Bharatiya Nyaya Sanhita / BNS 2023, Bharatiya Nagarik Suraksha Sanhita / BNSS 2023, Bharatiya Sakshya Adhiniyam / BSA 2023, IPC, CrPC) and landmark Supreme Court jurisprudence." | |
| # Format retrieved sections — same as original | |
| blocks = [] | |
| for i, res in enumerate(layer2_results, 1): | |
| is_repealed = res.get("is_repealed", False) | |
| status = ( | |
| "⚠️ WARNING: THIS LAW HAS BEEN REPEALED OR REPLACED. " | |
| "Refer to updated legislation." | |
| if is_repealed | |
| else "Active Law" | |
| ) | |
| source_type = res.get("source_type", "") | |
| raw_act = res.get('act_name', 'Unknown Act') | |
| law_type = res.get('law_type', '') | |
| if "PRECEDENT" in str(law_type).upper(): | |
| block = ( | |
| f"--- SOURCE {i} [BINDING JUDICIAL PRECEDENT & CONTROLLING RATIO] ---\n" | |
| f"COURT & CITATION: {raw_act}\n" | |
| f"SECTIONS INTERPRETED: {res.get('section_number', 'General')}\n" | |
| f"STATUS: BINDING PRECEDENT RATIO DECIDENDI\n" | |
| f"TEXT: {res.get('content', '')}\n" | |
| ) | |
| else: | |
| block = ( | |
| f"--- SOURCE {i} ---\n" | |
| f"ACT: {expand_act_name(raw_act)}\n" | |
| f"SECTION: {res.get('section_number', 'Unknown')}\n" | |
| f"STATUS: {status}\n" | |
| + (f"SOURCE_TYPE: {source_type}\n" if source_type else "") | |
| + f"TEXT: {res.get('content', '')}\n" | |
| ) | |
| blocks.append(block) | |
| formatted = "\n".join(blocks) | |
| # ── NEW: Append Knowledge Graph insights ── | |
| # graph_context is set by orchestrator from layer6_knowledge_graph | |
| # Appended as SYSTEM RULES so LLM treats as verified facts | |
| # NOT as retrieved legal sections (avoids Layer 4 citation issues) | |
| # If layer1_payload is None or graph_context is empty | |
| # this block is silently skipped — no error | |
| if layer1_payload: | |
| graph_context = layer1_payload.get("graph_context", "").strip() | |
| if graph_context: | |
| formatted += ( | |
| "\n\n--- KNOWLEDGE GRAPH SYSTEM RULES ---\n" | |
| "The following are verified law relationships and updates.\n" | |
| "You MUST factor these into your response:\n\n" | |
| + graph_context | |
| + "\n--- END SYSTEM RULES ---" | |
| ) | |
| print("[Layer 3] 🕸️ Knowledge Graph context injected.") | |
| precedents_context = layer1_payload.get("precedents_context", "").strip() | |
| if precedents_context: | |
| formatted += ( | |
| "\n\n--- BINDING JUDICIAL PRECEDENTS (SUPREME COURT & HIGH COURT) ---\n" | |
| "The following are authoritative, binding landmark judgments interpreting these statutes.\n" | |
| "You MUST highlight these case precedents and their executed relief in your response under a dedicated '### ⚖️ Controlling Judicial Precedents & Real-World Execution' section:\n" | |
| + precedents_context | |
| + "\n--- END BINDING JUDICIAL PRECEDENTS ---" | |
| ) | |
| print("[Layer 3] 🏛️ Judicial Precedents context injected.") | |
| # ── TEMPORAL STATUTORY ROUTING DIRECTIVE (Article 20(1) & BNSS 531) ── | |
| temporal_info = layer1_payload.get("temporal_context", {}) | |
| t_status = temporal_info.get("temporal_status", "UNDATED") | |
| t_date = temporal_info.get("detected_date_str") | |
| query_text = layer1_payload.get("original_query", "") if layer1_payload else "" | |
| if is_direct_lookup_query(query_text): | |
| directive = ( | |
| "\n\n--- ⚖️ STATUTORY DIRECTIVE: DIRECT LEGAL LOOKUP ---\n" | |
| "MANDATE: The user is asking a direct definition, comparison, or classification question. " | |
| "Deliver a crisp 3-4 bullet response under 120 words total. " | |
| "State the governing section under BNS 2023 / BNSS / BSA and mention the corresponding IPC/CrPC section in parentheses. " | |
| "Do NOT output giant dual-track headings or boilerplate.\n" | |
| "--- END STATUTORY DIRECTIVE ---" | |
| ) | |
| print("[Layer 3] ⚡ Injected DIRECT_LOOKUP statutory directive.") | |
| elif t_status == "PRE_2024": | |
| directive = ( | |
| f"\n\n--- ⚖️ TEMPORAL STATUTORY DIRECTIVE: PRE-JULY 2024 INCIDENT ({t_date}) ---\n" | |
| f"MANDATE: The user's query indicates this incident or dispute occurred prior to July 1, 2024 ({t_date}).\n" | |
| "Under Article 20(1) of the Constitution of India (bar on ex-post facto criminal law) and Section 531 of the BNSS, 2023:\n" | |
| "1. You MUST cite and apply the INDIAN PENAL CODE, 1860 (IPC) and CODE OF CRIMINAL PROCEDURE, 1973 (CrPC) as the PRIMARY governing substantive and procedural law.\n" | |
| "2. Explicitly explain to the user that since the offense occurred before July 1, 2024, it is governed by IPC/CrPC pursuant to Article 20(1) and Section 531 BNSS, and cannot be charged under BNS retrospectively.\n" | |
| "3. You may mention the corresponding 2024 BNS/BNSS section only as a secondary comparative note.\n" | |
| "--- END TEMPORAL DIRECTIVE ---" | |
| ) | |
| print(f"[Layer 3] ⏱️ Injected PRE_2024 temporal directive ({t_date}).") | |
| elif t_status == "POST_2024": | |
| directive = ( | |
| f"\n\n--- ⚖️ TEMPORAL STATUTORY DIRECTIVE: POST-JULY 2024 INCIDENT ({t_date}) ---\n" | |
| f"MANDATE: The user's query indicates this incident occurred on or after July 1, 2024 ({t_date}).\n" | |
| "1. You MUST cite and apply the BHARATIYA NYAYA SANHITA, 2023 (BNS), BHARATIYA NAGARIK SURAKSHA SANHITA, 2023 (BNSS), or BHARATIYA SAKSHYA ADHINIYAM, 2023 (BSA) as the PRIMARY governing law.\n" | |
| "2. Do NOT cite IPC or CrPC as the active governing sections for this crime.\n" | |
| "--- END TEMPORAL DIRECTIVE ---" | |
| ) | |
| print(f"[Layer 3] ⏱️ Injected POST_2024 temporal directive ({t_date}).") | |
| else: | |
| directive = ( | |
| "\n\n--- ⚖️ TEMPORAL STATUTORY DIRECTIVE: UNDATED / GENERAL QUERY ---\n" | |
| "MANDATE: The user did not specify an incident date. You MUST organize your response into these exact structural dual-tracks:\n\n" | |
| "### ⚖️ Substantive Law (The Core Offence & Your Rights)\n" | |
| "- **Post-July 1, 2024 Incidents**: Governed by the **Bharatiya Nyaya Sanhita, 2023 (BNS)**. State the specific BNS section, ingredients, and penalties (e.g. Section 318 BNS for cheating, Section 303 BNS for theft).\n" | |
| "- **Pre-July 1, 2024 Incidents**: Governed by the **Indian Penal Code, 1860 (IPC)** as mandated by Article 20(1) of the Constitution and Section 358 BNS. State the corresponding IPC section (e.g. Section 420 IPC, Section 379 IPC).\n\n" | |
| "### 🏛️ Procedural Law (Step-by-Step Rules to File and Run a Case in Court)\n" | |
| "- **New Complaints / FIRs Filed Today**: Governed by the **Bharatiya Nagarik Suraksha Sanhita, 2023 (BNSS)** (e.g. Section 173 BNSS for police station / e-FIR with the 3-day signature rule, preliminary enquiry, and digital procedures).\n" | |
| "- **Pending Investigations Initiated Prior to July 1, 2024**: Governed strictly by the **Code of Criminal Procedure, 1973 (CrPC)** (e.g. Section 154 CrPC) as protected under Section 531(2)(a) of the BNSS.\n\n" | |
| "If evidentiary rules or electronic records are discussed, explain them under:\n" | |
| "### 📁 Evidence Admissibility (Evidence Allowed in Court)\n" | |
| "- State which documents, electronic records (under Section 63 BSA), or proofs the court legally accepts.\n\n" | |
| "Always conclude with the statutory timeline note.\n" | |
| "--- END TEMPORAL DIRECTIVE ---" | |
| ) | |
| print("[Layer 3] ⏱️ Injected UNDATED dual-track temporal directive.") | |
| formatted += directive | |
| # ── GROUNDED ELECTRONIC EVIDENCE (Section 63 BSA) ── | |
| grounded_ev = layer1_payload.get("grounded_evidence") | |
| if grounded_ev: | |
| ev_type = grounded_ev.get("evidence_type", "electronic_record") | |
| sha_hash = grounded_ev.get("sha256_hash", "Verified") | |
| cert_id = grounded_ev.get("certificate", {}).get("certificate_id", "BSA-63") | |
| details = json.dumps(grounded_ev.get("transaction_details") or grounded_ev.get("forensic_admission") or {}, default=str) | |
| formatted += ( | |
| f"\n\n--- 🛡️ VERIFIED ELECTRONIC EVIDENCE (SECTION 63 BSA 2023) ---\n" | |
| f"Evidence Type: {ev_type}\n" | |
| f"SHA-256 Bitstream Hash: {sha_hash}\n" | |
| f"Certificate Ref: {cert_id}\n" | |
| f"Extracted Entities & Facts: {details}\n" | |
| f"MANDATE: Factor this verified electronic evidence directly into your legal strategy and procedural counsel.\n" | |
| f"--- END VERIFIED ELECTRONIC EVIDENCE ---" | |
| ) | |
| print("[Layer 3] 🛡️ Grounded Electronic Evidence injected into context.") | |
| return formatted | |
| # ───────────────────────────────────────────────────────────── | |
| # AMBIGUITY HANDLER | |
| # ───────────────────────────────────────────────────────────── | |
| def handle_non_legal_query(query: str) -> str: | |
| """ | |
| Returns a friendly off-topic response when the query is non-legal. | |
| Encourages the user to ask legal questions within SaulGPT's domain. | |
| """ | |
| return ( | |
| "Thanks for reaching out! I'm SaulGPT, your Indian Legal Intelligence Assistant. " | |
| "I specialize in Indian law — criminal, civil, family, labour, " | |
| "constitutional, and your legal rights.\n\n" | |
| "Your question seems to be about something outside the legal domain, " | |
| "and I want to make sure you get the best help possible. " | |
| "If you have a legal matter you'd like help with — " | |
| "whether it's understanding a law, analysing a situation, " | |
| "drafting a document, or figuring out next steps — " | |
| "I'm here for you. Just tell me about your legal concern!" | |
| ) | |
| def handle_ambiguous_query(layer1_payload: dict) -> str: | |
| """ | |
| Returns clarifying question when query is too ambiguous. | |
| Called before LLM reasoning if is_ambiguous is True. | |
| """ | |
| return ( | |
| "Your query could relate to multiple areas of law. " | |
| "Could you please clarify:\n\n" | |
| "→ Are you asking about a general legal concept " | |
| "(use Knowledge Mode)?\n" | |
| "→ Did something happen to you personally " | |
| "(use Case Analysis Mode)?\n" | |
| "→ Do you need a document drafted " | |
| "(use Document Generator Mode)?\n" | |
| "→ Do you need step by step procedure " | |
| "(use Path Finder Mode)?\n\n" | |
| "The more specific your question, the better " | |
| "SaulGPT can help you.\n\n" | |
| "Disclaimer: This response provides general procedural " | |
| "information based on Indian law and does not constitute " | |
| "legal advice. Please consult a qualified lawyer for " | |
| "your specific situation." | |
| ) | |
| # ───────────────────────────────────────────────────────────── | |
| # MAIN REASONING FUNCTION | |
| # ───────────────────────────────────────────────────────────── | |
| def generate_legal_response( | |
| layer1_payload: dict, | |
| layer2_results: list, | |
| mode: str = None, | |
| triage_context: dict = None, | |
| conversation_history: list = None | |
| ) -> str: | |
| """ | |
| Core Layer 3 function. | |
| Takes Layer 1 understanding + Layer 2 retrieval results | |
| and generates a structured legal response using local LLM. | |
| Args: | |
| layer1_payload: dict from layer1_understanding.analyze_query() | |
| must contain: original_query, domain, | |
| is_ambiguous, ambiguity_reason | |
| may contain: graph_context (from Layer 6) | |
| layer2_results: list of dicts from layer2_retrieval | |
| must contain: act_name, section_number, | |
| is_repealed, content | |
| mode: one of knowledge/analysis/document/pathfinder | |
| if None defaults to analysis | |
| triage_context: optional dict from Triage Agent | |
| contains role, goal, chosen_path, intake_fields | |
| conversation_history: optional list of previous turn dicts | |
| each dict: {"role": str, "content": str, ...} | |
| Returns: | |
| final legal response string ready for Layer 4 validation | |
| """ | |
| original_query = layer1_payload.get("original_query", "") | |
| domain = layer1_payload.get("domain", "legal") | |
| is_ambiguous = layer1_payload.get("is_ambiguous", False) | |
| # Handle non-legal queries with a friendly off-topic response | |
| # This bypasses LLM entirely — no tokens wasted | |
| if layer1_payload.get("is_non_legal"): | |
| print("[Layer 3] Non-legal query detected. Returning friendly off-topic response.") | |
| return handle_non_legal_query(original_query) | |
| # Handle ambiguous queries first | |
| if is_ambiguous: | |
| print("[Layer 3] Query flagged as ambiguous. Returning clarification.") | |
| return handle_ambiguous_query(layer1_payload) | |
| # Auto-detect follow-up questions / pushback / sparring when history is present | |
| is_followup = False | |
| if conversation_history and len(conversation_history) > 0: | |
| q_lower = original_query.strip().lower() | |
| word_count = len(q_lower.split()) | |
| followup_signals = [ | |
| "why", "how", "what if", "can i", "can we", "what happens", | |
| "is there", "what about", "i don't", "i dont", "settle", | |
| "settlement", "other option", "explain", "tell me", "for what", | |
| "does it mean", "will it", "cost", "how much", "really", "alternative", | |
| "avoid", "skip", "necessary", "compulsory", "mandatory" | |
| ] | |
| if word_count < 35 or any(q_lower.startswith(s) or f" {s} " in f" {q_lower} " for s in followup_signals): | |
| is_followup = True | |
| if is_direct_lookup_query(original_query) and mode in (None, "knowledge", "analysis"): | |
| selected_mode = "direct_lookup" | |
| elif mode in ("conversational", "sparring") or (mode in (None, "analysis") and is_followup): | |
| selected_mode = "conversational" | |
| elif mode in MODE_PROMPTS: | |
| selected_mode = mode | |
| else: | |
| selected_mode = DEFAULT_MODE | |
| prompt_template = MODE_PROMPTS[selected_mode] | |
| print(f"[Layer 3] Mode selected: {selected_mode} (is_followup={is_followup})") | |
| # Format context — passes layer1_payload so graph_context | |
| # gets injected into prompt automatically | |
| print("[Layer 3] Formatting retrieved sections as context...") | |
| formatted_context = format_context(layer2_results, layer1_payload) | |
| # ── Inject Conversation History into prompt context ── | |
| if conversation_history: | |
| ch_lines = ["\n\n--- PREVIOUS CONVERSATION (for context) ---"] | |
| for turn in conversation_history: | |
| role = turn.get("role", "unknown") | |
| content = turn.get("content", "") | |
| # Truncate long assistant responses to avoid bloat | |
| if role == "assistant" and len(content) > 500: | |
| content = content[:500] + "..." | |
| ch_lines.append(f"{role.title()}: {content}") | |
| ch_lines.append("--- END PREVIOUS CONVERSATION ---\n") | |
| formatted_context = "\n".join(ch_lines) + "\n" + formatted_context | |
| print(f"[Layer 3] Conversation history injected ({len(conversation_history)} turns).") | |
| # ── Inject Triage Context into prompt context ── | |
| if triage_context: | |
| tc_lines = ["\n\n--- USER CASE CONTEXT (from Triage) ---"] | |
| if triage_context.get("role"): | |
| tc_lines.append(f"User Role: {triage_context['role']}") | |
| if triage_context.get("goal"): | |
| tc_lines.append(f"Goal: {triage_context['goal']}") | |
| if triage_context.get("chosen_path"): | |
| tc_lines.append(f"Chosen Strategy: {triage_context['chosen_path']}") | |
| intake = triage_context.get("intake_fields", {}) | |
| for k, v in intake.items(): | |
| if v: | |
| label = k.replace("_", " ").title() | |
| tc_lines.append(f"{label}: {v}") | |
| tc_lines.append("--- END CASE CONTEXT ---\n") | |
| formatted_context = "\n".join(tc_lines) + "\n" + formatted_context | |
| print("[Layer 3] Triage context injected into prompt.") | |
| # ── Ground offence classification (the law DB has section text, not cognizable/bailable facts) ── | |
| try: | |
| from offence_schedule import schedule_notes | |
| _notes = schedule_notes(layer1_payload.get("original_query", ""), layer2_results) | |
| if _notes: | |
| formatted_context = _notes + "\n\n" + formatted_context | |
| print("[Layer 3] Official offence classification injected.") | |
| except Exception as e: | |
| print(f"[Layer 3] Offence classification skipped: {e}") | |
| # Log repealed law warning | |
| repealed_laws = [ | |
| r.get("act_name") for r in layer2_results | |
| if r.get("is_repealed", False) | |
| ] | |
| if repealed_laws: | |
| print(f"[Layer 3] WARNING: Repealed laws in context: {repealed_laws}") | |
| # Build and invoke LLM chain | |
| print(f"[Layer 3] Generating response with {LLM_MODEL}...") | |
| prompt = PromptTemplate( | |
| input_variables=["user_query", "domain", "context"], | |
| template=prompt_template | |
| ) | |
| try: | |
| chain = prompt | get_reasoning_llm() | |
| print("\n" + "=" * 40) | |
| print("🧠 SAULGPT IS TYPING...") | |
| print("=" * 40 + "\n") | |
| final_answer = "" | |
| # .stream() outputs word by word to terminal | |
| for chunk in chain.stream({ | |
| "user_query": original_query, | |
| "domain": domain, | |
| "context": formatted_context | |
| }): | |
| print(chunk.content, end="", flush=True) | |
| final_answer += chunk.content | |
| print("\n\n" + "=" * 40 + "\n") | |
| clean_answer = re.sub(r'^\s*\{[\s\S]*?context_sufficient[\s\S]*?\}\s*', '', final_answer).strip() | |
| return clean_answer if clean_answer else final_answer.strip() | |
| except Exception as e: | |
| print(f"[Layer 3] Primary LLM call failed: {e}") | |
| # Graceful model fallback | |
| for fb_model in ["openai/gpt-oss-120b", "openai/gpt-oss-20b"]: | |
| try: | |
| print(f"[Layer 3] Retrying generation with fallback model: {fb_model}...") | |
| fb_llm = ChatGroq( | |
| model_name=fb_model, | |
| api_key=get_effective_groq_key(), | |
| temperature=TEMPERATURE, | |
| max_tokens=2048 | |
| ) | |
| fb_chain = prompt | fb_llm | |
| fb_res = fb_chain.invoke({ | |
| "user_query": original_query, | |
| "domain": domain, | |
| "context": formatted_context | |
| }).content | |
| clean_fb = re.sub(r'^\s*\{[\s\S]*?context_sufficient[\s\S]*?\}\s*', '', fb_res).strip() | |
| if clean_fb: | |
| return clean_fb | |
| except Exception as fb_err: | |
| print(f"[Layer 3] Fallback {fb_model} failed: {fb_err}") | |
| print("[Layer 3] Falling back to retrieval summary...") | |
| fallback_lines = [ | |
| "SaulGPT was unable to generate a full response at this time.", | |
| "Based on retrieved legal sections, the following may be relevant:\n" | |
| ] | |
| for res in layer2_results[:3]: | |
| fallback_lines.append( | |
| f"• {res.get('act_name')} — " | |
| f"Section {res.get('section_number')}: " | |
| f"{res.get('content', '')[:150]}..." | |
| ) | |
| fallback_lines.append( | |
| "\nDisclaimer: This response provides general procedural " | |
| "information based on Indian law and does not constitute " | |
| "legal advice. Please consult a qualified lawyer for " | |
| "your specific situation." | |
| ) | |
| return "\n".join(fallback_lines) | |
| # ───────────────────────────────────────────────────────────── | |
| # TEST RUNNER | |
| # ───────────────────────────────────────────────────────────── | |
| if __name__ == "__main__": | |
| mock_layer1 = { | |
| "original_query": ( | |
| "What are the legal conditions for a valid marriage " | |
| "regarding age and living spouses under " | |
| "Section 5 of the Hindu Marriage Act?" | |
| ), | |
| "domain": "family", | |
| "is_ambiguous": False, | |
| "ambiguity_reason": "", | |
| # Simulated graph_context from layer6_knowledge_graph | |
| # In production set by orchestrator after Layer 6 runs | |
| "graph_context": ( | |
| "📖 DEFINITION: Hindu Marriage Act Section 5 requires " | |
| "reading with Section 11 (void marriages) and " | |
| "Section 12 (voidable marriages) for complete understanding." | |
| ), | |
| } | |
| mock_layer2 = [ | |
| { | |
| "act_name": "Hindu Marriage Act, 1955", | |
| "section_number": "5", | |
| "is_repealed": False, | |
| "content": ( | |
| "[Act: Hindu Marriage Act, 1955] " | |
| "[Section 5: Conditions for a Hindu marriage]. " | |
| "A marriage may be solemnized between any two Hindus " | |
| "if the following conditions are fulfilled: " | |
| "(i) neither party has a spouse living at the time " | |
| "of the marriage; " | |
| "(iii) the bridegroom has completed the age of " | |
| "twenty-one years and the bride, the age of " | |
| "eighteen years at the time of the marriage." | |
| ) | |
| }, | |
| { | |
| "act_name": "Hindu Marriage Act, 1955", | |
| "section_number": "18", | |
| "is_repealed": False, | |
| "content": ( | |
| "[Act: Hindu Marriage Act, 1955] " | |
| "[Section 18: Punishment for contravention]. " | |
| "Every person who procures a marriage in contravention " | |
| "of conditions in Section 5 shall be punishable with " | |
| "rigorous imprisonment which may extend to two years " | |
| "or with fine which may extend to one lakh rupees " | |
| "or with both." | |
| ) | |
| } | |
| ] | |
| print("-" * 55) | |
| print("SaulGPT — Layer 3 Reasoning Test") | |
| print("-" * 55) | |
| print("\nTesting MODE: analysis (with Knowledge Graph context)") | |
| response = generate_legal_response( | |
| mock_layer1, | |
| mock_layer2, | |
| mode="analysis" | |
| ) | |
| print("\n" + "=" * 55) | |
| print("LAYER 3 — FINAL RESPONSE (analysis mode)") | |
| print("=" * 55) | |
| print(response) | |
| print("=" * 55) | |
| print("\nLayer 3 complete. Response ready for Layer 4 validation.") |