Spaces:
Sleeping
Sleeping
Update src/sql_generator.py
Browse files11 unmodified lines1213141516171819202116 unmodified lines383940414243444546474849505152535455565758597 unmodified lines676869707172737475767778798011 unmodified lines929394959697989910010110210311 unmodified linesraw_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 Qwen 2.5 Coderself.repo_id = "Qwen/Qwen2.5-Coder-32B-Instruct"# β FIX: Updated to the new Hugging Face Router URLself.api_url = f"https://router.huggingface.co/models/{self.repo_id}"def generate_followup_questions(self, question, sql_query):16 unmodified linesif history:history_text = "PREVIOUS CONVERSATION:\n" + "\n".join([f"User: {h.get('user')}\nSQL: {h.get('sql')}" for h in history[-2:]])# System Promptsystem_prompt = f"""You are an elite SQL Expert.Schema:{context}{history_text}Rules:1. Output JSON: {{ "sql": "SELECT ...", "message": "Friendly text", "explanation": "Brief summary" }}2. Query MUST be Read-Only (SELECT).3. Do not include markdown formatting like ```json."""# Payloadpayload = {"inputs": f"<|im_start|>system\n{system_prompt}<|im_end|>\n<|im_start|>user\n{question}<|im_end|>\n<|im_start|>assistant\n","parameters": {"max_new_tokens": 1024,"temperature": 0.1,7 unmodified lines}try:print(f" β‘ Generating SQL via Direct API...")# π DIRECT REQUESTresponse = requests.post(self.api_url, headers=headers, json=payload, timeout=25)if 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", "The AI model is currently unavailable."# Parse Responseresult = response.json()11 unmodified linesexplanation = "Query generated successfully."try: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:match = re.search(r"(SELECT[\s\S]+?;)", raw_text, re.IGNORECASE)if match: sql_query = match.group(1)11 unmodified lines12131415161718192021222316 unmodified lines40414243444546474849505152535455565758596061627 unmodified lines707172737475767778798081828311 unmodified lines959697989910010110210310410510610710810911011111 unmodified linesraw_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 MODEL THAT IS DEFINITELY FREE & ONLINE# The 32B model caused the 404. We switch to Mistral-7B-Instruct-v0.3# It is excellent for SQL and 100% supported on the free tier.self.repo_id = "mistralai/Mistral-7B-Instruct-v0.3"# 3. USE THE NEW ROUTER URLself.api_url = f"https://router.huggingface.co/models/{self.repo_id}"def generate_followup_questions(self, question, sql_query):16 unmodified linesif 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 Mistral)system_prompt = f"""<s>[INST] You are an expert SQL Assistant.DATABASE SCHEMA:{context}{history_text}RULES:1. Output ONLY a valid JSON object. Format: {{ "sql": "SELECT ...", "message": "Friendly text", "explanation": "Brief summary" }}2. 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,7 unmodified lines}try:print(f" β‘ Generating SQL via Direct API ({self.repo_id})...")# π DIRECT REQUESTresponse = requests.post(self.api_url, headers=headers, json=payload, timeout=25)if 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 Error: {response.status_code}"# Parse Responseresult = response.json()11 unmodified linesexplanation = "Query generated successfully."try:# Mistral sometimes keeps the prompt. Split by [/INST] if present.if "[/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)
src/sql_generator.py+22-14