import os import sys import re import json from pathlib import Path from dotenv import load_dotenv # Force load .env from project root env_path = Path(__file__).parent.parent / '.env' load_dotenv(dotenv_path=env_path) from typing import Dict, Any, Optional, List from core.pydantic_models import PlannerOutput, VerificationReport from core.database import query_chainage_at, query_chainages from core.hybrid_search import HybridSearchEngine from core.engineering import calculate_lift_value, calculate_slue_value, calculate_cant_value, NR_LIMITS from agent.verifier import SeniorVerifier try: import google.generativeai as genai GEMINI_AVAILABLE = True except ImportError: GEMINI_AVAILABLE = False class LocalEngineeringAgent: def __init__(self, session_state=None): self.session_state = session_state self.history = [] self.verifier = SeniorVerifier() self._gemini_available = self._check_gemini() def _check_gemini(self) -> bool: if not GEMINI_AVAILABLE: return False try: api_key = os.environ.get("GEMINI_API_KEY") if not api_key: return False genai.configure(api_key=api_key) model = genai.GenerativeModel('gemini-3.6-flash') model.generate_content("Test") return True except Exception: return False def _call_gemini(self, prompt: str, model="gemini-3.6-flash", temperature=0.0) -> str: if not self._gemini_available: return "" try: # Ensure key is set if not os.environ.get("GEMINI_API_KEY"): env_path = Path(__file__).parent.parent / '.env' load_dotenv(dotenv_path=env_path) api_key = os.environ.get("GEMINI_API_KEY") if not api_key: raise ValueError("GEMINI_API_KEY not found in environment or .env") genai.configure(api_key=api_key) print("⏳ Calling Gemini...") model = genai.GenerativeModel(model) response = model.generate_content(prompt, generation_config={"temperature": temperature}) print("✅ Gemini responded.") return response.text.strip() except Exception as e: print(f"Gemini error: {e}") return "" def _plan_query(self, query: str) -> PlannerOutput: prompt = f""" You are a railway track engineering assistant. Extract the following fields from the query: - chainage (float, if present) - alignment (string, if mentioned) - fields (list of strings, e.g., ["lift", "cant"]) - standard_id (string, e.g., "NR/L2/TRK/2500") - action (lookup, compliance, why, design, definition, update) - comparison_value (float, if user asks "why not X") - new_parameter (dict, e.g., {{"speed": 80}} for what-if) Query: "{query}" Output ONLY valid JSON (no markdown, no extra text) matching this schema: {{ "chainage": null, "alignment": null, "fields": [], "standard_id": "NR/L2/TRK/2500", "action": "lookup", "comparison_value": null, "new_parameter": null }} """ response = self._call_gemini(prompt, model="gemini-3.6-flash", temperature=0.0) # Strip markdown code fences json_match = re.search(r'```(?:json)?\s*([\s\S]*?)\s*```', response, re.DOTALL) if json_match: response = json_match.group(1).strip() try: data = json.loads(response) return PlannerOutput(**data) except Exception as e: print(f"Planner error: {e}") return self._fallback_plan(query) def _fallback_plan(self, query: str) -> PlannerOutput: q = query.lower() ch = None ch_match = re.search(r'(?:ch|chainage)\s*([\d.]+)', q, re.I) if ch_match: ch = float(ch_match.group(1)) fields = [] for f in ["lift", "slue", "slew", "cant", "radius", "twist"]: if f in q: fields.append(f) if "compliance" in q or "check" in q or "pass" in q or "fail" in q or "limit" in q: action = "compliance" elif "update" in q or "set" in q or "change" in q: action = "update" elif "why" in q: action = "why" else: action = "lookup" comp_match = re.search(r'(\d+)\s*(?:mm|m|mph)', q) comp_val = float(comp_match.group(1)) if comp_match else None return PlannerOutput( chainage=ch, alignment=None, fields=fields, standard_id="NR/L2/TRK/2500", action=action, comparison_value=comp_val, new_parameter=None ) def _execute_plan(self, plan: dict) -> Dict: # Stub – replace with your actual deterministic logic return {"status": "PASS", "calculated": {"lift": 25.0}, "row": {"chainage": 340}} def _verify_deterministic(self, plan: dict, technical: dict) -> dict: complexity = "simple" if plan.get("comparison_value") is not None or plan.get("new_parameter") is not None: complexity = "complex" return {"complexity": complexity, "warnings": []} def _synthesize_draft(self, query: str, plan: dict, technical: dict) -> str: prompt = f""" You are a Track Design Engineer. Based on the technical data below, write a clear, concise answer to the user. User query: {query} Technical data: {technical} Include exact numbers and units. Cite standards where applicable. """ return self._call_gemini(prompt, model="gemini-3.6-flash", temperature=0.3) def _call_verifier(self, query: str, plan: dict, technical: dict, draft: str) -> VerificationReport: return self.verifier.verify(query, plan, technical, draft) def process_query(self, query: str) -> dict: # 1. Plan plan = self._plan_query(query) if plan.chainage is None and plan.action != "definition": return { "answer": "Please provide a specific chainage (e.g., CH 1050) for numerical queries.", "verification": None } # 2. Deterministic execution technical = self._execute_plan(plan.model_dump()) # 3. Deterministic verification verified = self._verify_deterministic(plan.model_dump(), technical) complexity = verified.get("complexity", "simple") # 4. Synthesize draft draft = self._synthesize_draft(query, plan.model_dump(), technical) # 5. Verify with Senior Verifier report = self._call_verifier(query, plan.model_dump(), technical, draft) return { "answer": report.corrected_answer, "verification": report.model_dump() } def is_available(self) -> bool: return True def clear_history(self): self.history = [] def get_history(self): return self.history def get_or_create_agent(session_state): return LocalEngineeringAgent(session_state)