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

Delete functions.py

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