CD17 commited on
Commit
e03e6d4
·
verified ·
1 Parent(s): d53033a

Upload functions_hf.py

Browse files
Files changed (1) hide show
  1. functions_hf.py +295 -0
functions_hf.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_community.utilities import SQLDatabase
2
+ from langchain import HuggingFaceHub
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM
4
+ import torch
5
+ from langchain_core.prompts import ChatPromptTemplate
6
+ from langchain_core.output_parsers import StrOutputParser
7
+ from langchain_core.runnables import RunnablePassthrough
8
+ import re
9
+ from typing import Dict, List
10
+
11
+ llm = HuggingFaceHub(repo_id="Qwen/Qwen2.5-72B-Instruct", model_kwargs={"temperature":0, "max_length":64})
12
+
13
+
14
+ # Initialize database connection
15
+ db = SQLDatabase.from_uri("sqlite:///Spring_2025_courses.db", sample_rows_in_table_info=0)
16
+
17
+ # Helper functions
18
+ def get_schema(_):
19
+ """Retrieve database schema"""
20
+ return db.get_table_info()
21
+
22
+ def run_query(query):
23
+ """Execute SQL query"""
24
+ return db.run(query)
25
+
26
+ # SQL generation prompt
27
+ system_prompt = """
28
+ You are a SQLite expert. Given an input question, create one syntactically correct SQLite query to run. Generate only one query. No pre-amble.
29
+
30
+ Here is the relevant table information:
31
+ schema: {schema}
32
+ Departments: 'Applied Math & Statistics', 'ART', 'Biomedical Science (BMS)', 'Computer Science (CS), Computer Networks and Cybersecurity (CNCS)', 'Data Science (DS)', 'Dance', 'General Education (GE)'
33
+ New/Repeat: Have no values (Don't use New/Repeat in queries)
34
+
35
+ Tips:
36
+ - Use LIKE instead of = in the queries
37
+
38
+ Below are a number of examples of questions and their corresponding SQL queries.
39
+
40
+ example 1:
41
+ Question:List all departments.
42
+ SQL query:SELECT Department FROM Spring_2025_courses;
43
+
44
+ example 2:
45
+ Question:Find all classes that are taught by Dr. Qu.
46
+ SQL query:SELECT CourseTitle FROM Spring_2025_courses WHERE Instructor LIKE '%Qu%';
47
+
48
+ example 3:
49
+ Question:List all courses in the Data Science department.
50
+ SQL query:SELECT CourseCode, CourseTitle FROM Spring_2025_courses WHERE Department LIKE '%Data Science%';
51
+
52
+ example 4:
53
+ Question:Find the total number of courses offered for Spring 2025.
54
+ SQL query:SELECT COUNT(CourseCode) FROM Spring_2025_courses;
55
+
56
+ example 5:
57
+ Question:List all professors from Biomed Department.
58
+ SQL query:SELECT Instructor FROM Spring_2025_courses WHERE Department LIKE '%Biomed%';
59
+
60
+ example 6:
61
+ Question:Which courses are available in the Biomed department for Spring 2025?
62
+ SQL query:SELECT CourseTitle FROM Spring_2025_courses WHERE Department LIKE '%Biomed%';
63
+
64
+ example 7:
65
+ Question:How many courses are offered under the Arts Management (BFA) program?
66
+ SQL query:SELECT COUNT(CourseCode) FROM Spring_2025_courses WHERE Department LIKE Program LIKE '%BFA%'
67
+
68
+ example 8:
69
+ Question:Which courses are available for the Master of Science in Applied Math?
70
+ SQL query:SELECT CourseTitle FROM Spring_2025_courses WHERE Program LIKE '%Master of Science%' AND Department LIKE '%Applied Math%';
71
+
72
+ Write only one SQLite query that would answer the user's question. No pre-amble.
73
+ """
74
+
75
+ human_prompt = """Based on the table schema below, write a SQL query that would answer the user's question:
76
+ {schema}
77
+
78
+ Question: {question}
79
+ SQL Query:"""
80
+
81
+ prompt = ChatPromptTemplate.from_messages([
82
+ ("system", system_prompt),
83
+ ("human", human_prompt),
84
+ ])
85
+
86
+ # Build query generation chain
87
+ sql_generator = (
88
+ RunnablePassthrough.assign(schema=get_schema)
89
+ | prompt
90
+ | llm.bind(stop=["\nSQLResult:"])
91
+ | StrOutputParser()
92
+ )
93
+
94
+ # Natural language response generation
95
+ nl_system_prompt = """Given an input question and SQL response, convert it to a natural language answer.
96
+
97
+ Below are a number of examples of questions and their corresponding SQL queries.
98
+
99
+ example 1:
100
+ Question: Which courses are available in the Data Science department?
101
+ SQL Query: SELECT CourseTitle FROM Spring_2025_courses WHERE Department LIKE '%Data Science%';
102
+ SQL Response: [('Introduction to Data Science',), ('Career Development in Data Science',), ('Data Structures',), ('Data Visualization',), ('Data Inference',), ('Data Mining',), ('Big Data Engineering',), ('Independent Study for Data Science',), ('Senior Project',), ('Mathematical Foundation for Data Science (Online)',), ('Computational Foundation for Data Science (Online)',), ('Probability for Data Science (Online)',), ('Exploratory Data Analysis and Visualization',), ('Modern Applied Statistical Learning',), ('Data Mining for Business',), ('Big Data and Data Engineering',), ('Design and Analysis of Experiments',), ('Design and Analysis of Experiments',), ('Computer Vision and Natural Language Processing (Independent Study)',), ('Capstone Project',)]
103
+ Response: The available courses in the Data Science department are Introduction to Data Science, Career Development in Data Science, Data Structures, Data Visualization, Data Inference, Data Mining, Big Data Engineering, Independent Study for Data Science, Senior Project, Mathematical Foundation for Data Science, Computational Foundation for Data Science, Probability for Data Science, Exploratory Data Analysis and Visualization, Modern Applied Statistical Learning, Data Mining for Business, Big Data and Data Engineering, Design and Analysis of Experiments, and Capstone Project.
104
+
105
+ example 2:
106
+ Question: Find all classes that are taught by Dr. Qu.
107
+ SQL Query: SELECT CourseTitle FROM Spring_2025_courses WHERE Instructor LIKE '%Qu%';
108
+ SQL Response: [('Introduction to Data Science',), ('Data Structures',), ('Data Mining',), ('Computational Foundation for Data Science (Online)',), ('Data Mining for Business',), ('Computer Vision and Natural Language Processing (Independent Study)',)]
109
+ Response: Dr. Qu is teaching Introduction to Data Science, Data Structures, Data Mining, Computational Foundation for Data Science, Data Mining for Business, and Computer Vision and Natural Language Processing.
110
+
111
+ Generate only ONE answer based on the SQL response. No pre-amble.
112
+ """
113
+
114
+ response_prompt = """Based on the table schema below, question, sql query, and sql response, write a natural language response. No pre-amble:
115
+ {schema}
116
+
117
+ Question:{question}
118
+ SQL Query:{query}
119
+ SQL Response:{response}
120
+ Response:"""
121
+
122
+ nl_prompt = ChatPromptTemplate.from_messages([
123
+ ("system", nl_system_prompt),
124
+ ("human", response_prompt),
125
+ ])
126
+
127
+ # Complete chain with natural language output
128
+ complete_chain = (
129
+ RunnablePassthrough.assign(query=sql_generator)
130
+ | RunnablePassthrough.assign(
131
+ schema=get_schema,
132
+ response=lambda x: db.run(x['query']),
133
+ )
134
+ | nl_prompt
135
+ | llm
136
+ )
137
+
138
+ class InputValidator:
139
+ """Input validation and sanitization for database queries"""
140
+
141
+ RESTRICTED_WORDS = {
142
+ 'delete', 'drop', 'truncate', 'update', 'insert',
143
+ 'alter', 'create', 'replace', 'modify', 'grant'
144
+ }
145
+
146
+ ALLOWED_TABLES = ['spring_2025_courses']
147
+
148
+ def __init__(self):
149
+ self.error_messages = []
150
+
151
+ def validate_question(self, question: str) -> bool:
152
+ """
153
+ Validate a natural language question
154
+
155
+ Args:
156
+ question (str): User's input question
157
+
158
+ Returns:
159
+ bool: True if valid, False otherwise
160
+ """
161
+ self.error_messages = []
162
+
163
+ # Check if question is empty or too long
164
+ if not question or not question.strip():
165
+ self.error_messages.append("Question cannot be empty")
166
+ return False
167
+
168
+ if len(question) > 500:
169
+ self.error_messages.append("Question is too long (max 500 characters)")
170
+ return False
171
+
172
+ # Check for basic SQL injection attempts
173
+ question_lower = question.lower()
174
+ if any(word in question_lower for word in self.RESTRICTED_WORDS):
175
+ self.error_messages.append("Question contains restricted keywords")
176
+ return False
177
+
178
+ # Check for excessive special characters
179
+ if re.search(r'[;{}\\]', question):
180
+ self.error_messages.append("Question contains invalid characters")
181
+ return False
182
+
183
+ return True
184
+
185
+ def get_error_messages(self) -> List[str]:
186
+ """Get all error messages from validation"""
187
+ return self.error_messages
188
+
189
+ class QueryValidator:
190
+ """Validate generated SQL queries before execution"""
191
+
192
+ def __init__(self, db_connection):
193
+ self.db = db_connection
194
+ self.error_messages = []
195
+
196
+ def get_error_messages(self) -> List[str]:
197
+ """Get all error messages from validation"""
198
+ return self.error_messages
199
+
200
+ def validate_sql(self, sql: str) -> bool:
201
+ """Validate generated SQL query"""
202
+ sql_lower = sql.lower()
203
+
204
+ # Check if query is read-only (SELECT only)
205
+ if not sql_lower.strip().startswith('select'):
206
+ self.error_messages.append("Only SELECT queries are allowed")
207
+ return False
208
+
209
+ # Check for multiple statements
210
+ if ';' in sql[:-1]: # Allow semicolon at the end
211
+ self.error_messages.append("Multiple SQL statements are not allowed")
212
+ return False
213
+
214
+ # Validate table names
215
+ table = self._extract_table_names(sql_lower)
216
+ if table not in InputValidator.ALLOWED_TABLES:
217
+ self.error_messages.append("Query contains invalid table names")
218
+ return False
219
+
220
+ return True
221
+
222
+ def _extract_table_names(self, sql: str) -> str:
223
+ """Extract table names from SQL query"""
224
+ from_matches = re.findall(r'from\s+([a-zA-Z_][a-zA-Z0-9_]*)', sql.lower())
225
+ return from_matches[0]
226
+
227
+ class SafeQueryExecutor:
228
+ """Safe execution of natural language queries"""
229
+
230
+ def __init__(self, db_connection, llm_chain):
231
+ self.input_validator = InputValidator()
232
+ self.query_validator = QueryValidator(db_connection)
233
+ self.db = db_connection
234
+ self.chain = llm_chain
235
+
236
+ def execute_safe_query(self, question: str) -> Dict:
237
+ """
238
+ Safely execute a natural language query
239
+
240
+ Args:
241
+ question (str): User's natural language question
242
+
243
+ Returns:
244
+ dict: Query result and status
245
+ """
246
+ # Validate input
247
+ if not self.input_validator.validate_question(question):
248
+ return {
249
+ 'success': False,
250
+ 'error': self.input_validator.get_error_messages(),
251
+ 'query': None,
252
+ 'result': None
253
+ }
254
+
255
+ try:
256
+ # Generate SQL query
257
+ sql_query = sql_generator.invoke({"question": question})
258
+
259
+ # Validate generated SQL
260
+ if not self.query_validator.validate_sql(sql_query):
261
+ return {
262
+ 'success': False,
263
+ 'error': self.query_validator.get_error_messages(),
264
+ 'query': sql_query,
265
+ 'result': None
266
+ }
267
+
268
+ # Execute query
269
+ result = complete_chain.invoke({"question": question})
270
+
271
+ return {
272
+ 'success': True,
273
+ 'error': None,
274
+ 'query': sql_query,
275
+ 'result': result
276
+ }
277
+
278
+ except Exception as e:
279
+ return {
280
+ 'success': False,
281
+ 'error': [str(e)],
282
+ 'query': None,
283
+ 'result': None
284
+ }
285
+
286
+ # Initialize the safe executor
287
+ safe_executor = SafeQueryExecutor(db, complete_chain)
288
+
289
+ # Example queries
290
+ example_queries = [
291
+ "Which courses are available in the Data Science department for Spring 2025?",
292
+ "What are the details of the course 'Introduction to Python'?",
293
+ "How many courses are offered under the Computer Science (Bachelor of Science) program?",
294
+ "Show me the courses taught by Dr. Qu in Spring 2025."
295
+ ]