Spaces:
Sleeping
Sleeping
| import os | |
| from google import genai | |
| from google.genai import types | |
| from dotenv import load_dotenv | |
| load_dotenv(override=True) | |
| class NyayaAgent: | |
| def __init__(self, model_id='gemini-flash-lite-latest'): | |
| self.client = genai.Client(api_key=os.getenv("GEMINI_API_KEY")) | |
| self.model_id = model_id | |
| self.system_instruction = ( | |
| "You are 'Nyaya Agent', a specialized Legal & Judiciary Assistant for the Indian Legal System. " | |
| "You serve Citizens, Law Students, and Lawyers. Your tone and technicality must adapt based on the user's background.\n\n" | |
| "ADAPTATION RULES:\n" | |
| "1. CITIZEN/NON-PROFESSIONAL: Use simple language, avoid jargon, and explain concepts like 'Writ' or 'Affidavit'. Always suggest drafting an RTI query if they need data from a government body.\n" | |
| "2. LAW STUDENT: Provide technical details, refer to specific case precedents (e.g., Kesavananda Bharati), and suggest checking the latest Supreme Court filings.\n" | |
| "3. LAWYER/PROFESSIONAL: Provide high-technicality analysis, cite specific Acts/Sections (IPC, BNS, etc.), and discuss procedural nuances.\n\n" | |
| "MANDATORY GUIDELINES:\n" | |
| "- Be proactive: If a query involves government inaction or data, suggest an RTI.\n" | |
| "- If a query involves a complex constitutional point, suggest checking Supreme Court updates.\n" | |
| "- Be precise and refer to specific sections of Indian Acts/Statutes.\n" | |
| "- BE GUIDED BY TRUTH: Your underlying principle is 'Satyameva Jayate' (Truth alone triumphs). Ensure your research is accurate and evidence-based.\n" | |
| "- DRAFTING: When asked to draft documents, use the provided tools and ALWAYS output the full drafted template filled with the user's details. The draft MUST contain the exact headers 'LEGAL NOTICE' or 'Subject: Application under RTI'.\n" | |
| "- DO NOT provide definitive legal advice; clarify that you are a research assistant." | |
| ) | |
| def generate_response(self, prompt, config=None): | |
| import time | |
| max_retries = 5 | |
| retry_delay = 10 # Increased delay for free tier stability | |
| if config is None: | |
| config = types.GenerateContentConfig( | |
| system_instruction=self.system_instruction, | |
| temperature=0.2, | |
| ) | |
| for attempt in range(max_retries): | |
| try: | |
| response = self.client.models.generate_content( | |
| model=self.model_id, | |
| contents=prompt, | |
| config=config | |
| ) | |
| return response.text | |
| except Exception as e: | |
| if "503" in str(e) or "429" in str(e): | |
| if attempt < max_retries - 1: | |
| print(f"\n[System] Gemini is busy. Retrying in {retry_delay}s... (Attempt {attempt + 1}/{max_retries})", flush=True) | |
| time.sleep(retry_delay) | |
| retry_delay *= 2 # Exponential backoff | |
| continue | |
| raise e | |
| if __name__ == "__main__": | |
| # Quick test | |
| agent = NyayaAgent() | |
| print(agent.generate_response("Introduce yourself briefly.")) | |