Spaces:
Sleeping
Sleeping
Update src/sql_generator.py
Browse files7 unmodified lines891011121314151617181920212223242 unmodified lines272829303132333435363738394041424344454647484 unmodified lines535455565758596061626364655 unmodified lines717273747576777879808182838485868788891 unmodified line9192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271287 unmodified linesdef __init__(self):load_dotenv()# 1. ROBUSTLY FETCH & CLEAN THE KEY# We check both names and use .strip() to remove invisible newlinesraw_key = os.getenv("HF_API_KEY") or os.getenv("HUGGINGFACEHUB_API_TOKEN")self.api_key = raw_key.strip() if raw_key else None# 2. USE A RELIABLE FREE TIER MODEL# We switch to Mistral-7B-Instruct-v0.3 (Supported on Free Tier)# Qwen-32B is too big and causes 404 errors.self.repo_id = "mistralai/Mistral-7B-Instruct-v0.3"# 3. USE THE NEW ROUTER URL (Fixes 410 Gone errors)self.api_url = f"https://router.huggingface.co/models/{self.repo_id}"def generate_followup_questions(self, question, sql_query):2 unmodified linesdef generate_sql(self, question, context, history=None):if history is None: history = []# π¨ ERROR CHECKif not self.api_key:return "SELECT 'Error: HF_API_KEY Missing' as status", "Configuration Error", "Please add HF_API_KEY to your Space Secrets."# π‘οΈ Safety Layer (Keyword Block)forbidden = ["DROP", "DELETE", "UPDATE", "INSERT", "ALTER", "TRUNCATE", "GRANT"]if any(word in question.upper() for word in forbidden):return "SELECT 'Error: Blocked by Safety Layer' as status", "Safety Alert", "I cannot execute commands that modify data."# Format Historyhistory_text = ""if history:history_text = "PREVIOUS CONVERSATION:\n" + "\n".join([f"User: {h.get('user')}\nSQL: {h.get('sql')}" for h in history[-2:]])# System Prompt (Optimized for JSON output)system_prompt = f"""<s>[INST] You are an elite SQL Expert.DATABASE SCHEMA:{context}4 unmodified lines2. The SQL query MUST be Read-Only (SELECT).3. Do not use markdown formatting.QUESTION: {question} [/INST]"""# Payloadpayload = {"inputs": system_prompt,"parameters": {"max_new_tokens": 1024,"temperature": 0.1,"return_full_text": False}5 unmodified lines}try:print(f" β‘ Generating SQL via Direct API ({self.repo_id})...")# π DIRECT REQUEST (Bypasses library auth issues)response = requests.post(self.api_url, headers=headers, json=payload, timeout=25)# Handle Errors clearlyif response.status_code != 200:print(f" β API Status: {response.status_code} - {response.text}")return f"SELECT 'Error: API returned {response.status_code}' as status", "API Error", f"Model unavailable ({response.status_code})"# Parse Responseresult = response.json()if isinstance(result, list) and len(result) > 0:raw_text = result[0].get('generated_text', '')elif isinstance(result, dict):1 unmodified lineelse:raw_text = str(result)# Clean JSONsql_query = ""message = "Here is the data."explanation = "Query generated successfully."try:# Remove Markdown and extra textif "[/INST]" in raw_text: raw_text = raw_text.split("[/INST]")[-1]clean_json = re.sub(r"```json|```", "", raw_text).strip()data = json.loads(clean_json)sql_query = data.get("sql", "")message = data.get("message", message)explanation = data.get("explanation", explanation)except:# Fallback: Regex to find SQL if JSON parsing failsmatch = re.search(r"(SELECT[\s\S]+?;)", raw_text, re.IGNORECASE)if match: sql_query = match.group(1)# Final Cleanupsql_query = sql_query.strip().replace("\n", " ")if sql_query and not sql_query.endswith(";"): sql_query += ";"# π‘οΈ Final Validation (Allows SELECT or WITH)clean_check = re.sub(r"/\*.*?\*/|--.*?\n", "", sql_query, flags=re.DOTALL).strip().upper()if not clean_check.startswith("SELECT") and not clean_check.startswith("WITH"):print(f" β οΈ Invalid SQL Blocked: {sql_query}")return "SELECT 'Error: Invalid Query Type (Non-SELECT)' as status", "Safety Error", "I can only perform read-only operations."return sql_query, explanation, messageexcept Exception as e:print(f" β Model Error: {e}")safe_e = str(e).replace("'", "").replace('"', "")return f"SELECT 'Error: {safe_e}' as status", "System Error", "An unexpected error occurred."7 unmodified lines891011121314151617181920212 unmodified lines242526272829303132333435363738394041424344454647484 unmodified lines535455565758596061626364655 unmodified lines71727374757677787980818283848586878889901 unmodified line92939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261277 unmodified linesdef __init__(self):load_dotenv()# 1. GET KEYraw_key = os.getenv("HF_API_KEY") or os.getenv("HUGGINGFACEHUB_API_TOKEN")self.api_key = raw_key.strip() if raw_key else None# 2. USE ZEPHYR (No License Agreement Required - 100% Free)self.repo_id = "HuggingFaceH4/zephyr-7b-beta"# 3. Router URLself.api_url = f"https://router.huggingface.co/models/{self.repo_id}"def generate_followup_questions(self, question, sql_query):2 unmodified linesdef generate_sql(self, question, context, history=None):if history is None: history = []# π¨ DEBUG: Print Key Status (Safe)if not self.api_key:print(" β FATAL: HF_API_KEY is missing from environment.")return "SELECT 'Error: HF_API_KEY Missing' as status", "Configuration Error", "Please add HF_API_KEY to your Space Secrets."else:print(f" β API Key loaded (starts with {self.api_key[:4]}...)")# π‘οΈ Safetyforbidden = ["DROP", "DELETE", "UPDATE", "INSERT", "ALTER", "TRUNCATE", "GRANT"]if any(word in question.upper() for word in forbidden):return "SELECT 'Error: Blocked by Safety Layer' as status", "Safety Alert", "I cannot execute commands that modify data."history_text = ""if history:history_text = "PREVIOUS CONVERSATION:\n" + "\n".join([f"User: {h.get('user')}\nSQL: {h.get('sql')}" for h in history[-2:]])# System Prompt (Optimized for Zephyr)system_prompt = f"""<|system|>You are an elite SQL Expert.DATABASE SCHEMA:{context}4 unmodified lines2. The SQL query MUST be Read-Only (SELECT).3. Do not use markdown formatting.QUESTION: {question} </s><|assistant|>"""payload = {"inputs": system_prompt,"parameters": {"max_new_tokens": 512,"temperature": 0.1,"return_full_text": False}5 unmodified lines}try:print(f" β‘ Generating SQL using {self.repo_id}...")# π DIRECT REQUESTresponse = requests.post(self.api_url, headers=headers, json=payload, timeout=25)# π¨ PRINT EXACT ERROR IF IT FAILSif response.status_code != 200:print(f" β API FAILURE: {response.status_code}")print(f" β RESPONSE: {response.text}")return f"SELECT 'Error: API returned {response.status_code}' as status", "API Error", f"Model Error: {response.status_code}"result = response.json()# Helper to extract textif isinstance(result, list) and len(result) > 0:raw_text = result[0].get('generated_text', '')elif isinstance(result, dict):1 unmodified lineelse:raw_text = str(result)# JSON Parsingsql_query = ""message = "Here is the data."explanation = "Query generated successfully."try:clean_json = re.sub(r"```json|```", "", raw_text).strip()# Regex to find the JSON object if there is extra textjson_match = re.search(r"\{.*\}", clean_json, re.DOTALL)if json_match:data = json.loads(json_match.group(0))sql_query = data.get("sql", "")message = data.get("message", message)explanation = data.get("explanation", explanation)else:raise ValueError("No JSON found")except:match = re.search(r"(SELECT[\s\S]+?;)", raw_text, re.IGNORECASE)if match: sql_query = match.group(1)sql_query = sql_query.strip().replace("\n", " ")if sql_query and not sql_query.endswith(";"): sql_query += ";"clean_check = re.sub(r"/\*.*?\*/|--.*?\n", "", sql_query, flags=re.DOTALL).strip().upper()if not clean_check.startswith("SELECT") and not clean_check.startswith("WITH"):return "SELECT 'Error: Invalid Query Type' as status", "Safety Error", "I can only perform read-only operations."return sql_query, explanation, messageexcept Exception as e:print(f" β SYSTEM EXCEPTION: {e}")safe_e = str(e).replace("'", "").replace('"', "")return f"SELECT 'Error: {safe_e}' as status", "System Error", "An unexpected error occurred."
src/sql_generator.py+34-35