CD17 commited on
Commit
cfe911b
·
verified ·
1 Parent(s): 8eb218e

Delete functions_qwen.py

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