LalitChaudhari3 commited on
Commit
5d48e70
·
verified ·
1 Parent(s): a0a3c5c

Update src/sql_generator.py

Browse files
Files changed (1) hide show
  1. src/sql_generator.py +79 -62
src/sql_generator.py CHANGED
@@ -8,15 +8,22 @@ class SQLGenerator:
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):
22
  return ["Visualize this result", "Export as CSV", "Compare with last year"]
@@ -24,14 +31,10 @@ class SQLGenerator:
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."
@@ -40,7 +43,7 @@ class SQLGenerator:
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:
@@ -70,58 +73,72 @@ class SQLGenerator:
70
  "Content-Type": "application/json"
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):
91
- raw_text = result.get('generated_text', '')
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."
 
8
  def __init__(self):
9
  load_dotenv()
10
 
11
+ # 1. GET KEY (Cleaned)
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. MODEL LIST (The "Shotgun" Strategy)
16
+ # We try 4 different models. If one fails (404/429), it instantly tries the next.
17
+ self.models = [
18
+ "mistralai/Mistral-7B-Instruct-v0.3", # Most popular free model
19
+ "google/gemma-1.1-7b-it", # Highly reliable backup
20
+ "microsoft/Phi-3-mini-4k-instruct", # Very fast, almost always online
21
+ "HuggingFaceH4/zephyr-7b-beta" # Old reliable (last resort)
22
+ ]
23
 
24
+ # 3. BASE URLs (Try Router first, then Legacy)
25
+ self.router_url = "https://router.huggingface.co/models/"
26
+ self.legacy_url = "https://api-inference.huggingface.co/models/"
27
 
28
  def generate_followup_questions(self, question, sql_query):
29
  return ["Visualize this result", "Export as CSV", "Compare with last year"]
 
31
  def generate_sql(self, question, context, history=None):
32
  if history is None: history = []
33
 
 
34
  if not self.api_key:
 
35
  return "SELECT 'Error: HF_API_KEY Missing' as status", "Configuration Error", "Please add HF_API_KEY to your Space Secrets."
 
 
36
 
37
+ # 🛡️ Safety Layer
38
  forbidden = ["DROP", "DELETE", "UPDATE", "INSERT", "ALTER", "TRUNCATE", "GRANT"]
39
  if any(word in question.upper() for word in forbidden):
40
  return "SELECT 'Error: Blocked by Safety Layer' as status", "Safety Alert", "I cannot execute commands that modify data."
 
43
  if history:
44
  history_text = "PREVIOUS CONVERSATION:\n" + "\n".join([f"User: {h.get('user')}\nSQL: {h.get('sql')}" for h in history[-2:]])
45
 
46
+ # System Prompt
47
  system_prompt = f"""<|system|>
48
  You are an elite SQL Expert.
49
  DATABASE SCHEMA:
 
73
  "Content-Type": "application/json"
74
  }
75
 
76
+ # 🔄 ROBUST RETRY LOOP
77
+ last_error = ""
78
+
79
+ for model in self.models:
80
+ # Try Router URL first, then Legacy URL
81
+ urls_to_try = [self.router_url + model, self.legacy_url + model]
82
 
83
+ for api_url in urls_to_try:
84
+ try:
85
+ print(f" ⚡ Trying {model} at {api_url}...")
86
+
87
+ response = requests.post(api_url, headers=headers, json=payload, timeout=20)
88
+
89
+ if response.status_code == 200:
90
+ print(f" ✅ SUCCESS with {model}!")
91
+ return self._process_response(response.json())
92
+
93
+ # If 404/410/500, we log and continue to next
94
+ print(f" ❌ Failed ({response.status_code}). Trying next...")
95
+ last_error = f"{response.status_code}: {response.text}"
96
+
97
+ except Exception as e:
98
+ print(f" ⚠️ Connection Error: {e}")
99
+ last_error = str(e)
100
+
101
+ # If ALL models fail
102
+ return f"SELECT 'Error: {last_error}' as status", "System Error", "All AI models are currently unavailable. Check your HF_API_KEY."
103
+
104
+ def _process_response(self, result):
105
+ """Helper to parse the AI response cleanly"""
106
+ if isinstance(result, list) and len(result) > 0:
107
+ raw_text = result[0].get('generated_text', '')
108
+ elif isinstance(result, dict):
109
+ raw_text = result.get('generated_text', '')
110
+ else:
111
+ raw_text = str(result)
112
 
113
+ sql_query = ""
114
+ message = "Here is the data."
115
+ explanation = "Query generated successfully."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
 
117
+ try:
118
+ # Clean Markdown
119
+ clean_json = re.sub(r"```json|```", "", raw_text).strip()
120
+ # Attempt to find JSON object
121
+ json_match = re.search(r"\{.*\}", clean_json, re.DOTALL)
122
+ if json_match:
123
+ data = json.loads(json_match.group(0))
124
+ sql_query = data.get("sql", "")
125
+ message = data.get("message", message)
126
+ explanation = data.get("explanation", explanation)
127
+ else:
128
+ # Fallback regex
129
+ match = re.search(r"(SELECT[\s\S]+?;)", raw_text, re.IGNORECASE)
130
+ if match: sql_query = match.group(1)
131
+ except:
132
+ match = re.search(r"(SELECT[\s\S]+?;)", raw_text, re.IGNORECASE)
133
+ if match: sql_query = match.group(1)
134
+
135
+ # Final Cleanup
136
+ sql_query = sql_query.strip().replace("\n", " ")
137
+ if sql_query and not sql_query.endswith(";"): sql_query += ";"
138
+
139
+ clean_check = re.sub(r"/\*.*?\*/|--.*?\n", "", sql_query, flags=re.DOTALL).strip().upper()
140
+ if not clean_check.startswith("SELECT") and not clean_check.startswith("WITH"):
141
+ # Last resort fallback for clean "SELECT"
142
+ return "SELECT 'Error: Invalid Query Type' as status", "Safety Error", "I can only perform read-only operations."
143
 
144
+ return sql_query, explanation, message