LalitChaudhari3 commited on
Commit
a0a3c5c
Β·
verified Β·
1 Parent(s): 146146a

Update src/sql_generator.py

Browse files
Files changed (1) hide show
  1. src/sql_generator.py +34 -35
src/sql_generator.py CHANGED
@@ -8,17 +8,14 @@ class SQLGenerator:
8
  def __init__(self):
9
  load_dotenv()
10
 
11
- # 1. ROBUSTLY FETCH & CLEAN THE KEY
12
- # We check both names and use .strip() to remove invisible newlines
13
  raw_key = os.getenv("HF_API_KEY") or os.getenv("HUGGINGFACEHUB_API_TOKEN")
14
  self.api_key = raw_key.strip() if raw_key else None
15
 
16
- # 2. USE A RELIABLE FREE TIER MODEL
17
- # We switch to Mistral-7B-Instruct-v0.3 (Supported on Free Tier)
18
- # Qwen-32B is too big and causes 404 errors.
19
- self.repo_id = "mistralai/Mistral-7B-Instruct-v0.3"
20
 
21
- # 3. USE THE NEW ROUTER URL (Fixes 410 Gone errors)
22
  self.api_url = f"https://router.huggingface.co/models/{self.repo_id}"
23
 
24
  def generate_followup_questions(self, question, sql_query):
@@ -27,22 +24,25 @@ class SQLGenerator:
27
  def generate_sql(self, question, context, history=None):
28
  if history is None: history = []
29
 
30
- # 🚨 ERROR CHECK
31
  if not self.api_key:
 
32
  return "SELECT 'Error: HF_API_KEY Missing' as status", "Configuration Error", "Please add HF_API_KEY to your Space Secrets."
 
 
33
 
34
- # πŸ›‘οΈ Safety Layer (Keyword Block)
35
  forbidden = ["DROP", "DELETE", "UPDATE", "INSERT", "ALTER", "TRUNCATE", "GRANT"]
36
  if any(word in question.upper() for word in forbidden):
37
  return "SELECT 'Error: Blocked by Safety Layer' as status", "Safety Alert", "I cannot execute commands that modify data."
38
 
39
- # Format History
40
  history_text = ""
41
  if history:
42
  history_text = "PREVIOUS CONVERSATION:\n" + "\n".join([f"User: {h.get('user')}\nSQL: {h.get('sql')}" for h in history[-2:]])
43
 
44
- # System Prompt (Optimized for JSON output)
45
- system_prompt = f"""<s>[INST] You are an elite SQL Expert.
 
46
  DATABASE SCHEMA:
47
  {context}
48
 
@@ -53,13 +53,13 @@ class SQLGenerator:
53
  2. The SQL query MUST be Read-Only (SELECT).
54
  3. Do not use markdown formatting.
55
 
56
- QUESTION: {question} [/INST]"""
 
57
 
58
- # Payload
59
  payload = {
60
  "inputs": system_prompt,
61
  "parameters": {
62
- "max_new_tokens": 1024,
63
  "temperature": 0.1,
64
  "return_full_text": False
65
  }
@@ -71,19 +71,20 @@ class SQLGenerator:
71
  }
72
 
73
  try:
74
- print(f" ⚑ Generating SQL via Direct API ({self.repo_id})...")
75
 
76
- # πŸš€ DIRECT REQUEST (Bypasses library auth issues)
77
  response = requests.post(self.api_url, headers=headers, json=payload, timeout=25)
78
 
79
- # Handle Errors clearly
80
  if response.status_code != 200:
81
- print(f" ❌ API Status: {response.status_code} - {response.text}")
82
- return f"SELECT 'Error: API returned {response.status_code}' as status", "API Error", f"Model unavailable ({response.status_code})"
 
83
 
84
- # Parse Response
85
  result = response.json()
86
 
 
87
  if isinstance(result, list) and len(result) > 0:
88
  raw_text = result[0].get('generated_text', '')
89
  elif isinstance(result, dict):
@@ -91,38 +92,36 @@ class SQLGenerator:
91
  else:
92
  raw_text = str(result)
93
 
94
- # Clean JSON
95
  sql_query = ""
96
  message = "Here is the data."
97
  explanation = "Query generated successfully."
98
 
99
  try:
100
- # Remove Markdown and extra text
101
- if "[/INST]" in raw_text: raw_text = raw_text.split("[/INST]")[-1]
102
  clean_json = re.sub(r"```json|```", "", raw_text).strip()
103
-
104
- data = json.loads(clean_json)
105
- sql_query = data.get("sql", "")
106
- message = data.get("message", message)
107
- explanation = data.get("explanation", explanation)
 
 
 
 
108
  except:
109
- # Fallback: Regex to find SQL if JSON parsing fails
110
  match = re.search(r"(SELECT[\s\S]+?;)", raw_text, re.IGNORECASE)
111
  if match: sql_query = match.group(1)
112
 
113
- # Final Cleanup
114
  sql_query = sql_query.strip().replace("\n", " ")
115
  if sql_query and not sql_query.endswith(";"): sql_query += ";"
116
 
117
- # πŸ›‘οΈ Final Validation (Allows SELECT or WITH)
118
  clean_check = re.sub(r"/\*.*?\*/|--.*?\n", "", sql_query, flags=re.DOTALL).strip().upper()
119
  if not clean_check.startswith("SELECT") and not clean_check.startswith("WITH"):
120
- print(f" ⚠️ Invalid SQL Blocked: {sql_query}")
121
- return "SELECT 'Error: Invalid Query Type (Non-SELECT)' as status", "Safety Error", "I can only perform read-only operations."
122
 
123
  return sql_query, explanation, message
124
 
125
  except Exception as e:
126
- print(f" ❌ Model Error: {e}")
127
  safe_e = str(e).replace("'", "").replace('"', "")
128
  return f"SELECT 'Error: {safe_e}' as status", "System Error", "An unexpected error occurred."
 
8
  def __init__(self):
9
  load_dotenv()
10
 
11
+ # 1. GET KEY
 
12
  raw_key = os.getenv("HF_API_KEY") or os.getenv("HUGGINGFACEHUB_API_TOKEN")
13
  self.api_key = raw_key.strip() if raw_key else None
14
 
15
+ # 2. USE ZEPHYR (No License Agreement Required - 100% Free)
16
+ self.repo_id = "HuggingFaceH4/zephyr-7b-beta"
 
 
17
 
18
+ # 3. Router URL
19
  self.api_url = f"https://router.huggingface.co/models/{self.repo_id}"
20
 
21
  def generate_followup_questions(self, question, sql_query):
 
24
  def generate_sql(self, question, context, history=None):
25
  if history is None: history = []
26
 
27
+ # 🚨 DEBUG: Print Key Status (Safe)
28
  if not self.api_key:
29
+ print(" ❌ FATAL: HF_API_KEY is missing from environment.")
30
  return "SELECT 'Error: HF_API_KEY Missing' as status", "Configuration Error", "Please add HF_API_KEY to your Space Secrets."
31
+ else:
32
+ print(f" βœ… API Key loaded (starts with {self.api_key[:4]}...)")
33
 
34
+ # πŸ›‘οΈ Safety
35
  forbidden = ["DROP", "DELETE", "UPDATE", "INSERT", "ALTER", "TRUNCATE", "GRANT"]
36
  if any(word in question.upper() for word in forbidden):
37
  return "SELECT 'Error: Blocked by Safety Layer' as status", "Safety Alert", "I cannot execute commands that modify data."
38
 
 
39
  history_text = ""
40
  if history:
41
  history_text = "PREVIOUS CONVERSATION:\n" + "\n".join([f"User: {h.get('user')}\nSQL: {h.get('sql')}" for h in history[-2:]])
42
 
43
+ # System Prompt (Optimized for Zephyr)
44
+ system_prompt = f"""<|system|>
45
+ You are an elite SQL Expert.
46
  DATABASE SCHEMA:
47
  {context}
48
 
 
53
  2. The SQL query MUST be Read-Only (SELECT).
54
  3. Do not use markdown formatting.
55
 
56
+ QUESTION: {question} </s>
57
+ <|assistant|>"""
58
 
 
59
  payload = {
60
  "inputs": system_prompt,
61
  "parameters": {
62
+ "max_new_tokens": 512,
63
  "temperature": 0.1,
64
  "return_full_text": False
65
  }
 
71
  }
72
 
73
  try:
74
+ print(f" ⚑ Generating SQL using {self.repo_id}...")
75
 
76
+ # πŸš€ DIRECT REQUEST
77
  response = requests.post(self.api_url, headers=headers, json=payload, timeout=25)
78
 
79
+ # 🚨 PRINT EXACT ERROR IF IT FAILS
80
  if response.status_code != 200:
81
+ print(f" ❌ API FAILURE: {response.status_code}")
82
+ print(f" ❌ RESPONSE: {response.text}")
83
+ return f"SELECT 'Error: API returned {response.status_code}' as status", "API Error", f"Model Error: {response.status_code}"
84
 
 
85
  result = response.json()
86
 
87
+ # Helper to extract text
88
  if isinstance(result, list) and len(result) > 0:
89
  raw_text = result[0].get('generated_text', '')
90
  elif isinstance(result, dict):
 
92
  else:
93
  raw_text = str(result)
94
 
95
+ # JSON Parsing
96
  sql_query = ""
97
  message = "Here is the data."
98
  explanation = "Query generated successfully."
99
 
100
  try:
 
 
101
  clean_json = re.sub(r"```json|```", "", raw_text).strip()
102
+ # Regex to find the JSON object if there is extra text
103
+ json_match = re.search(r"\{.*\}", clean_json, re.DOTALL)
104
+ if json_match:
105
+ data = json.loads(json_match.group(0))
106
+ sql_query = data.get("sql", "")
107
+ message = data.get("message", message)
108
+ explanation = data.get("explanation", explanation)
109
+ else:
110
+ raise ValueError("No JSON found")
111
  except:
 
112
  match = re.search(r"(SELECT[\s\S]+?;)", raw_text, re.IGNORECASE)
113
  if match: sql_query = match.group(1)
114
 
 
115
  sql_query = sql_query.strip().replace("\n", " ")
116
  if sql_query and not sql_query.endswith(";"): sql_query += ";"
117
 
 
118
  clean_check = re.sub(r"/\*.*?\*/|--.*?\n", "", sql_query, flags=re.DOTALL).strip().upper()
119
  if not clean_check.startswith("SELECT") and not clean_check.startswith("WITH"):
120
+ return "SELECT 'Error: Invalid Query Type' as status", "Safety Error", "I can only perform read-only operations."
 
121
 
122
  return sql_query, explanation, message
123
 
124
  except Exception as e:
125
+ print(f" ❌ SYSTEM EXCEPTION: {e}")
126
  safe_e = str(e).replace("'", "").replace('"', "")
127
  return f"SELECT 'Error: {safe_e}' as status", "System Error", "An unexpected error occurred."