CD17 commited on
Commit
6797c6e
·
verified ·
1 Parent(s): c3933bb

Upload 2 files

Browse files

Local test files without gradio and huggingface implementations.

Files changed (2) hide show
  1. functions.py +314 -0
  2. test_chat.ipynb +804 -0
functions.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
test_chat.ipynb ADDED
@@ -0,0 +1,804 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 10,
6
+ "metadata": {},
7
+ "outputs": [],
8
+ "source": [
9
+ "# Configure LLM options\n",
10
+ "#from langchain_community.chat_models import ChatOllama\n",
11
+ "from langchain_ollama import ChatOllama\n",
12
+ "from langchain_community.llms import DeepInfra\n",
13
+ "import os\n",
14
+ "from dotenv import load_dotenv\n",
15
+ "from langchain_community.utilities import SQLDatabase\n",
16
+ "\n",
17
+ "load_dotenv()\n",
18
+ "\n",
19
+ "api = os.getenv(\"DEEPINFRA_API_KEY\")\n",
20
+ "# API setup (optional)\n",
21
+ "deepinfra_model = \"meta-llama/Llama-3.3-70B-Instruct\"\n",
22
+ "# \"https://api.python.langchain.com/en/latest/llms/langchain_community.llms.deepinfra.DeepInfra.html\"\n",
23
+ "\n",
24
+ "di = DeepInfra(model_id=deepinfra_model,\n",
25
+ " deepinfra_api_token=api)\n",
26
+ "\n",
27
+ "# Choose which model to use\n",
28
+ "llm = di \n",
29
+ "\n",
30
+ "# Initialize database connection\n",
31
+ "db = SQLDatabase.from_uri(\"sqlite:///Spring_2025_courses.db\", sample_rows_in_table_info=0)\n",
32
+ "\n",
33
+ "# Helper functions\n",
34
+ "def get_schema(_):\n",
35
+ " \"\"\"Retrieve database schema\"\"\"\n",
36
+ " return db.get_table_info()\n",
37
+ "\n",
38
+ "def run_query(query):\n",
39
+ " \"\"\"Execute SQL query\"\"\"\n",
40
+ " return db.run(query)\n",
41
+ "\n",
42
+ "# print(get_schema(_))"
43
+ ]
44
+ },
45
+ {
46
+ "cell_type": "code",
47
+ "execution_count": 11,
48
+ "metadata": {},
49
+ "outputs": [],
50
+ "source": [
51
+ "from langchain_core.prompts import ChatPromptTemplate\n",
52
+ "from langchain_core.output_parsers import StrOutputParser\n",
53
+ "from langchain_core.runnables import RunnablePassthrough\n",
54
+ "\n",
55
+ "# SQL generation prompt\n",
56
+ "system_prompt = \"\"\" \n",
57
+ "You are a SQLite expert. Given an input question, create one syntactically correct SQLite query to run. Generate only one query. No pre-amble.\n",
58
+ "\n",
59
+ "Here is the relevant table information:\n",
60
+ "schema: {schema}\n",
61
+ "Departments: 'Applied Math & Statistics', 'ART', 'Biomedical Science (BMS)', 'Computer Science (CS), Computer Networks and Cybersecurity (CNCS)', 'Data Science (DS)', 'Dance', 'General Education (GE)'\n",
62
+ "New/Repeat: Have no values \n",
63
+ "\n",
64
+ "Tips:\n",
65
+ "- Use LIKE instead of = in the queries\n",
66
+ "- Don't use New/Repeat in queries\n",
67
+ "\n",
68
+ "Below are a number of examples of questions and their corresponding SQL queries.\n",
69
+ "\n",
70
+ "example 1:\n",
71
+ "Question:List all departments.\n",
72
+ "SQL query:SELECT Department FROM Spring_2025_courses;\n",
73
+ "\n",
74
+ "example 2:\n",
75
+ "Question:Find all classes that are taught by Dr. Qu.\n",
76
+ "SQL query:SELECT CourseTitle FROM Spring_2025_courses WHERE Instructor LIKE '%Qu%';\n",
77
+ "\n",
78
+ "example 3:\n",
79
+ "Question:List all courses in the Data Science department.\n",
80
+ "SQL query:SELECT CourseCode, CourseTitle FROM Spring_2025_courses WHERE Department LIKE '%Data Science%';\n",
81
+ "\n",
82
+ "example 4:\n",
83
+ "Question:Find the total number of courses offered for Spring 2025.\n",
84
+ "SQL query:SELECT COUNT(CourseCode) FROM Spring_2025_courses;\n",
85
+ "\n",
86
+ "example 5:\n",
87
+ "Question:List all professors from Biomed Department.\n",
88
+ "SQL query:SELECT Instructor FROM Spring_2025_courses WHERE Department LIKE '%Biomed%';\n",
89
+ "\n",
90
+ "example 6:\n",
91
+ "Question:Which courses are available in the Biomed department for Spring 2025?\n",
92
+ "SQL query:SELECT CourseTitle FROM Spring_2025_courses WHERE Department LIKE '%Biomed%';\n",
93
+ "\n",
94
+ "example 7:\n",
95
+ "Question:How many courses are offered under the Arts Management (BFA) program?\n",
96
+ "SQL query:SELECT COUNT(CourseCode) FROM Spring_2025_courses WHERE Department LIKE Program LIKE '%BFA%'\n",
97
+ "\n",
98
+ "example 8:\n",
99
+ "Question:Which courses are available for the Master of Science in Applied Math?\n",
100
+ "SQL query:SELECT CourseTitle FROM Spring_2025_courses WHERE Program LIKE '%Master of Science%' AND Department LIKE '%Applied Math%';\n",
101
+ "\n",
102
+ "Write only one SQLite query that would answer the user's question. No pre-amble.\n",
103
+ "\"\"\"\n",
104
+ "\n",
105
+ "human_prompt = \"\"\"Based on the table schema below, write a SQL query that would answer the user's question:\n",
106
+ "{schema}\n",
107
+ "\n",
108
+ "Question: {question}\n",
109
+ "SQL Query:\"\"\"\n",
110
+ "\n",
111
+ "prompt = ChatPromptTemplate.from_messages([\n",
112
+ " (\"system\", system_prompt),\n",
113
+ " (\"human\", human_prompt),\n",
114
+ "])\n",
115
+ "\n",
116
+ "# Build query generation chain\n",
117
+ "sql_generator = (\n",
118
+ " RunnablePassthrough.assign(schema=get_schema)\n",
119
+ " | prompt\n",
120
+ " | llm.bind(stop=[\"\\nSQLResult:\"])\n",
121
+ " | StrOutputParser()\n",
122
+ ")\n",
123
+ "\n",
124
+ "# Natural language response generation\n",
125
+ "nl_system_prompt = \"\"\"Given an input question and SQL response, convert it to a natural language answer. \n",
126
+ "\n",
127
+ "Below are a number of examples of questions and their corresponding SQL queries.\n",
128
+ "\n",
129
+ "example 1: \n",
130
+ "Question: Which courses are available in the Data Science department?\n",
131
+ "SQL Query: SELECT CourseTitle FROM Spring_2025_courses WHERE Department LIKE '%Data Science%';\n",
132
+ "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',)]\n",
133
+ "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.\n",
134
+ "\n",
135
+ "example 2:\n",
136
+ "Question: Find all classes that are taught by Dr. Qu.\n",
137
+ "SQL Query: SELECT CourseTitle FROM Spring_2025_courses WHERE Instructor LIKE '%Qu%';\n",
138
+ "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)',)]\n",
139
+ "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.\n",
140
+ "\n",
141
+ "Generate only ONE answer based on the SQL response. No pre-amble.\n",
142
+ "\"\"\"\n",
143
+ "\n",
144
+ "response_prompt = \"\"\"Based on the table schema below, question, sql query, and sql response, write a natural language response:\n",
145
+ "{schema}\n",
146
+ "\n",
147
+ "Question:{question}\n",
148
+ "SQL Query:{query}\n",
149
+ "SQL Response:{response}\n",
150
+ "Response:\"\"\"\n",
151
+ "\n",
152
+ "nl_prompt = ChatPromptTemplate.from_messages([\n",
153
+ " (\"system\", nl_system_prompt),\n",
154
+ " (\"human\", response_prompt),\n",
155
+ "])\n",
156
+ "\n",
157
+ "# Complete chain with natural language output\n",
158
+ "complete_chain = (\n",
159
+ " RunnablePassthrough.assign(query=sql_generator)\n",
160
+ " | RunnablePassthrough.assign(\n",
161
+ " schema=get_schema,\n",
162
+ " response=lambda x: db.run(x['query']),\n",
163
+ " )\n",
164
+ " | nl_prompt\n",
165
+ " | llm\n",
166
+ ")"
167
+ ]
168
+ },
169
+ {
170
+ "cell_type": "code",
171
+ "execution_count": null,
172
+ "metadata": {},
173
+ "outputs": [],
174
+ "source": [
175
+ "def demonstrate_chain_steps(question: str):\n",
176
+ " \"\"\"\n",
177
+ " Demonstrate each step of the complete chain\n",
178
+ " \n",
179
+ " Args:\n",
180
+ " question (str): Natural language question\n",
181
+ " \"\"\"\n",
182
+ " print(\"\\n=== Chain Demonstration ===\\n\")\n",
183
+ " \n",
184
+ " # Step 1: Initial input\n",
185
+ " print(\"1. Initial Input:\")\n",
186
+ " print({\"question\": question})\n",
187
+ " \n",
188
+ " # Step 2: Generate SQL\n",
189
+ " sql = sql_generator.invoke({\"question\": question})\n",
190
+ " print(\"\\n2. Generated SQL:\")\n",
191
+ " print(sql)\n",
192
+ " \n",
193
+ " # Step 3: Execute SQL\n",
194
+ " db_result = db.run(sql)\n",
195
+ " print(\"\\n3. Database Result:\")\n",
196
+ " print(db_result)\n",
197
+ " \n",
198
+ " # Step 4: Get schema\n",
199
+ " schema = get_schema(None)\n",
200
+ " print(\"\\n4. Database Schema:\")\n",
201
+ " print(schema[:200] + \"...\") # Truncated for readability\n",
202
+ " \n",
203
+ " # Step 5: Complete response\n",
204
+ " final_response = complete_chain.invoke({\"question\": question})\n",
205
+ " print(\"\\n5. Final Natural Language Response:\")\n",
206
+ " print(final_response)\n",
207
+ " \n",
208
+ " print(\"\\n=== End Demonstration ===\\n\")\n",
209
+ "\n",
210
+ "# Example usage\n",
211
+ "demonstrate_chain_steps(\"Find all classes that are taught by Dr. Bess.\")"
212
+ ]
213
+ },
214
+ {
215
+ "cell_type": "code",
216
+ "execution_count": 42,
217
+ "metadata": {},
218
+ "outputs": [],
219
+ "source": [
220
+ "from langchain.memory import ConversationBufferMemory\n",
221
+ "from langchain_core.prompts import MessagesPlaceholder\n",
222
+ "from langchain_core.prompts import ChatPromptTemplate\n",
223
+ "from langchain_core.output_parsers import StrOutputParser\n",
224
+ "from langchain_core.runnables import RunnablePassthrough\n",
225
+ "\n",
226
+ "# SQL generation prompt\n",
227
+ "system_prompt = \"\"\" \n",
228
+ "You are a SQLite expert. Given an input question, create one syntactically correct SQLite query to run. Generate only one query. No preamble.\n",
229
+ "\n",
230
+ "Here is the relevant table information:\n",
231
+ "schema: {schema}\n",
232
+ "Departments: 'Applied Math & Statistics', 'ART', 'Biomedical Science (BMS)', 'Computer Science (CS), Computer Networks and Cybersecurity (CNCS)', 'Data Science (DS)', 'Dance', 'General Education (GE)'\n",
233
+ "New/Repeat: Have no values (Don't use New/Repeat in queries)\n",
234
+ "\n",
235
+ "Tips:\n",
236
+ "- Use LIKE instead of = in the queries\n",
237
+ "\n",
238
+ "Below are a number of examples of questions and their corresponding SQL queries.\n",
239
+ "\n",
240
+ "example 1:\n",
241
+ "Question: List all departments.\n",
242
+ "SQL query: SELECT Department FROM Spring_2025_courses;\n",
243
+ "\n",
244
+ "example 2:\n",
245
+ "Question: Find all classes that are taught by Dr. Qu.\n",
246
+ "SQL query: SELECT CourseTitle FROM Spring_2025_courses WHERE Instructor LIKE '%Qu%';\n",
247
+ "\n",
248
+ "example 3:\n",
249
+ "Question: List all courses in the Data Science department.\n",
250
+ "SQL query: SELECT CourseCode, CourseTitle FROM Spring_2025_courses WHERE Department LIKE '%Data Science%';\n",
251
+ "\n",
252
+ "example 4:\n",
253
+ "Question: Find the total number of courses offered for Spring 2025.\n",
254
+ "SQL query: SELECT COUNT(CourseCode) FROM Spring_2025_courses;\n",
255
+ "\n",
256
+ "example 5:\n",
257
+ "Question: List all professors from Biomed Department.\n",
258
+ "SQL query: SELECT Instructor FROM Spring_2025_courses WHERE Department LIKE '%Biomed%';\n",
259
+ "\n",
260
+ "Write only one SQLite query that would answer the user's question. No preamble.\n",
261
+ "\"\"\"\n",
262
+ "\n",
263
+ "# Initialize memory\n",
264
+ "memory = ConversationBufferMemory(return_messages=True)\n",
265
+ "\n",
266
+ "# Updated prompt with memory\n",
267
+ "memory_prompt = ChatPromptTemplate.from_messages([\n",
268
+ " (\"system\", \"Convert questions to SQL using schema: {schema}\"),\n",
269
+ " MessagesPlaceholder(variable_name=\"history\"),\n",
270
+ " (\"human\", \"{question}\"),\n",
271
+ "])\n",
272
+ "\n",
273
+ "# Memory-enabled query chain\n",
274
+ "def save_context(input_output):\n",
275
+ " \"\"\"Save conversation context\"\"\"\n",
276
+ " output = {\"output\": input_output.pop(\"output\")}\n",
277
+ " memory.save_context(input_output, output)\n",
278
+ " return output[\"output\"]\n",
279
+ "\n",
280
+ "sql_chain_with_memory = (\n",
281
+ " RunnablePassthrough.assign(\n",
282
+ " schema=get_schema,\n",
283
+ " history=lambda x: memory.load_memory_variables(x)[\"history\"],\n",
284
+ " )\n",
285
+ " | memory_prompt\n",
286
+ " | llm.bind(stop=[\"\\nSQLResult:\"])\n",
287
+ " | StrOutputParser()\n",
288
+ ")\n",
289
+ "\n",
290
+ "# Final chain with memory\n",
291
+ "sql_memory_chain = RunnablePassthrough.assign(output=sql_chain_with_memory) | save_context"
292
+ ]
293
+ },
294
+ {
295
+ "cell_type": "code",
296
+ "execution_count": null,
297
+ "metadata": {},
298
+ "outputs": [],
299
+ "source": [
300
+ "import uuid\n",
301
+ "from langchain_core.messages import HumanMessage\n",
302
+ "from langchain_core.output_parsers import StrOutputParser\n",
303
+ "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
304
+ "from langchain.memory import ConversationBufferMemory\n",
305
+ "from langchain_core.runnables import RunnablePassthrough\n",
306
+ "from langgraph.checkpoint.memory import MemorySaver\n",
307
+ "from langgraph.graph import START, MessagesState, StateGraph\n",
308
+ "\n",
309
+ "# SQL generation prompt\n",
310
+ "system_prompt = \"\"\" \n",
311
+ "You are a SQLite expert. Given an input question, create one syntactically correct SQLite query to run. Generate only one query. No pre-amble.\n",
312
+ "\n",
313
+ "Here is the relevant table information:\n",
314
+ "schema: {schema}\n",
315
+ "Departments: 'Applied Math & Statistics', 'ART', 'Biomedical Science (BMS)', 'Computer Science (CS), Computer Networks and Cybersecurity (CNCS)', 'Data Science (DS)', 'Dance', 'General Education (GE)'\n",
316
+ "New/Repeat: Have no values (Don't use New/Repeat in queries)\n",
317
+ "\n",
318
+ "Tips:\n",
319
+ "- Use LIKE instead of = in the queries\n",
320
+ "\n",
321
+ "Below are a number of examples of questions and their corresponding SQL queries.\n",
322
+ "\n",
323
+ "example 1:\n",
324
+ "Question:List all departments.\n",
325
+ "SQL query:SELECT Department FROM Spring_2025_courses;\n",
326
+ "\n",
327
+ "example 2:\n",
328
+ "Question:Find all classes that are taught by Dr. Qu.\n",
329
+ "SQL query:SELECT CourseTitle FROM Spring_2025_courses WHERE Instructor LIKE '%Qu%';\n",
330
+ "\n",
331
+ "example 3:\n",
332
+ "Question:List all courses in the Data Science department.\n",
333
+ "SQL query:SELECT CourseCode, CourseTitle FROM Spring_2025_courses WHERE Department LIKE '%Data Science%';\n",
334
+ "\n",
335
+ "example 4:\n",
336
+ "Question:Find the total number of courses offered for Spring 2025.\n",
337
+ "SQL query:SELECT COUNT(CourseCode) FROM Spring_2025_courses;\n",
338
+ "\n",
339
+ "example 5:\n",
340
+ "Question:List all professors from Biomed Department.\n",
341
+ "SQL query:SELECT Instructor FROM Spring_2025_courses WHERE Department LIKE '%Biomed%';\n",
342
+ "\n",
343
+ "example 6:\n",
344
+ "Question:Which courses are available in the Biomed department for Spring 2025?\n",
345
+ "SQL query:SELECT CourseTitle FROM Spring_2025_courses WHERE Department LIKE '%Biomed%';\n",
346
+ "\n",
347
+ "example 7:\n",
348
+ "Question:How many courses are offered under the Arts Management (BFA) program?\n",
349
+ "SQL query:SELECT COUNT(CourseCode) FROM Spring_2025_courses WHERE Department LIKE Program LIKE '%BFA%'\n",
350
+ "\n",
351
+ "example 8:\n",
352
+ "Question:Which courses are available for the Master of Science in Applied Math?\n",
353
+ "SQL query:SELECT CourseTitle FROM Spring_2025_courses WHERE Program LIKE '%Master of Science%' AND Department LIKE '%Applied Math%';\n",
354
+ "\n",
355
+ "Write only one SQLite query that would answer the user's question. No pre-amble.\n",
356
+ "\"\"\"\n",
357
+ "\n",
358
+ "# Define a new graph\n",
359
+ "workflow = StateGraph(state_schema=MessagesState)\n",
360
+ "\n",
361
+ "# Memory initialization\n",
362
+ "memory = ConversationBufferMemory(return_messages=True)\n",
363
+ "\n",
364
+ "# Define the function that calls the model\n",
365
+ "def call_model(state: MessagesState):\n",
366
+ " response = llm.invoke(state[\"messages\"])\n",
367
+ " return {\"messages\": response}\n",
368
+ "\n",
369
+ "# Define the two nodes we will cycle between\n",
370
+ "workflow.add_edge(START, \"model\")\n",
371
+ "workflow.add_node(\"model\", call_model)\n",
372
+ "\n",
373
+ "# Adding memory is straightforward in langgraph\n",
374
+ "memory_saver = MemorySaver()\n",
375
+ "\n",
376
+ "app = workflow.compile(checkpointer=memory_saver)\n",
377
+ "\n",
378
+ "# The thread id is a unique key that identifies this particular conversation.\n",
379
+ "thread_id = uuid.uuid4()\n",
380
+ "config = {\"configurable\": {\"thread_id\": thread_id}}\n",
381
+ "\n",
382
+ "# Updated prompt with memory\n",
383
+ "memory_prompt = ChatPromptTemplate.from_messages([\n",
384
+ " (\"system\", system_prompt),\n",
385
+ " MessagesPlaceholder(variable_name=\"history\"),\n",
386
+ " (\"human\", \"{question}\"),\n",
387
+ "])\n",
388
+ "\n",
389
+ "# Memory-enabled query chain\n",
390
+ "def save_context(input_output):\n",
391
+ " \"\"\"Save conversation context\"\"\"\n",
392
+ " output = {\"output\": input_output.pop(\"output\")}\n",
393
+ " memory.save_context(input_output, output)\n",
394
+ " return output[\"output\"]\n",
395
+ "\n",
396
+ "sql_chain_with_memory = (\n",
397
+ " RunnablePassthrough.assign(\n",
398
+ " schema=get_schema, # Placeholder function to provide schema\n",
399
+ " history=lambda x: memory.load_memory_variables(x)[\"history\"],\n",
400
+ " )\n",
401
+ " | memory_prompt\n",
402
+ " | llm.bind(stop=[\"\\nSQLResult:\"])\n",
403
+ " | StrOutputParser()\n",
404
+ ")\n",
405
+ "\n",
406
+ "# Final chain with memory\n",
407
+ "sql_memory_chain = RunnablePassthrough.assign(output=sql_chain_with_memory) | save_context\n"
408
+ ]
409
+ },
410
+ {
411
+ "cell_type": "code",
412
+ "execution_count": null,
413
+ "metadata": {},
414
+ "outputs": [],
415
+ "source": [
416
+ "# # Example conversation\n",
417
+ "# input_message = HumanMessage(content=\"Which courses are available for the Bachelor of Science in Data Science?\")\n",
418
+ "# for event in app.stream({\"messages\": [input_message]}, config, stream_mode=\"values\"):\n",
419
+ "# event[\"messages\"][-1].pretty_print()\n",
420
+ "\n",
421
+ "# # Confirming memory functionality\n",
422
+ "# input_message = HumanMessage(content=\"Who is teaching the first course on the list?\")\n",
423
+ "# for event in app.stream({\"messages\": [input_message]}, config, stream_mode=\"values\"):\n",
424
+ "# event[\"messages\"][-1].pretty_print()"
425
+ ]
426
+ },
427
+ {
428
+ "cell_type": "code",
429
+ "execution_count": null,
430
+ "metadata": {},
431
+ "outputs": [],
432
+ "source": [
433
+ "def display_query_result(question, include_sql=False):\n",
434
+ " \"\"\"\n",
435
+ " Display query results in a formatted way\n",
436
+ " \n",
437
+ " Args:\n",
438
+ " question (str): Natural language question\n",
439
+ " include_sql (bool): Whether to show the generated SQL\n",
440
+ " \"\"\"\n",
441
+ " # Generate SQL and get response\n",
442
+ " sql = sql_generator.invoke({\"question\": question})\n",
443
+ " response = complete_chain.invoke({\"question\": question})\n",
444
+ " \n",
445
+ " # Print formatted output\n",
446
+ " print(\"\\n\" + \"=\"*50)\n",
447
+ " print(f\"Question: {question}\")\n",
448
+ " if include_sql:\n",
449
+ " print(f\"\\nGenerated SQL: {sql}\")\n",
450
+ " print(f\"\\nAnswer: {response}\")\n",
451
+ " print(\"=\"*50 + \"\\n\")\n",
452
+ "\n",
453
+ "# Example usage\n",
454
+ "display_query_result(\"Which courses are available in the Data Science department for Spring 2025?\", include_sql=True)"
455
+ ]
456
+ },
457
+ {
458
+ "cell_type": "code",
459
+ "execution_count": null,
460
+ "metadata": {},
461
+ "outputs": [],
462
+ "source": [
463
+ "# Test the chain\n",
464
+ "def display_conversation():\n",
465
+ " \"\"\"Display the current conversation history.\"\"\"\n",
466
+ " history = memory.load_memory_variables({})[\"history\"]\n",
467
+ " print(\"\\nConversation History:\")\n",
468
+ " print(\"=\" * 50)\n",
469
+ " for msg in history:\n",
470
+ " role = \"Human\" if msg.type == \"human\" else \"Assistant\"\n",
471
+ " print(f\"{role}: {msg.content}\\n\")\n",
472
+ "\n",
473
+ "\n",
474
+ "# Test input and output\n",
475
+ "response1 = sql_memory_chain.invoke({\"question\": \"Which courses are available for the Bachelor of Science in Data Science?\"})\n",
476
+ "print(\"First Response:\", response1)\n",
477
+ "\n"
478
+ ]
479
+ },
480
+ {
481
+ "cell_type": "code",
482
+ "execution_count": null,
483
+ "metadata": {},
484
+ "outputs": [],
485
+ "source": [
486
+ "response2 = sql_memory_chain.invoke({\"question\": \"Who is teaching the first course on the list?\"})\n",
487
+ "print(\"Follow-up Response:\", response2)\n",
488
+ "\n",
489
+ "display_conversation()"
490
+ ]
491
+ },
492
+ {
493
+ "cell_type": "code",
494
+ "execution_count": null,
495
+ "metadata": {},
496
+ "outputs": [],
497
+ "source": [
498
+ "def safe_query(question):\n",
499
+ " \"\"\"\n",
500
+ " Safely execute a query with error handling\n",
501
+ " \n",
502
+ " Args:\n",
503
+ " question (str): Natural language question\n",
504
+ " Returns:\n",
505
+ " dict: Result and status\n",
506
+ " \"\"\"\n",
507
+ " try:\n",
508
+ " response = complete_chain.invoke({\"question\": question})\n",
509
+ " return {\n",
510
+ " \"success\": True,\n",
511
+ " \"response\": response\n",
512
+ " }\n",
513
+ " except Exception as e:\n",
514
+ " return {\n",
515
+ " \"success\": False,\n",
516
+ " \"error\": str(e)\n",
517
+ " }\n",
518
+ "\n",
519
+ "# Example usage\n",
520
+ "result = safe_query(\"Which courses are available in the Data Science department for Spring 2025?\")\n",
521
+ "if result[\"success\"]:\n",
522
+ " print(\"Answer:\", result[\"response\"])\n",
523
+ "else:\n",
524
+ " print(\"Error:\", result[\"error\"])"
525
+ ]
526
+ },
527
+ {
528
+ "cell_type": "code",
529
+ "execution_count": 12,
530
+ "metadata": {},
531
+ "outputs": [],
532
+ "source": [
533
+ "import re\n",
534
+ "from typing import Dict, List\n",
535
+ "\n",
536
+ "class InputValidator:\n",
537
+ " \"\"\"Input validation and sanitization for database queries\"\"\"\n",
538
+ " \n",
539
+ " # Restricted words that might indicate harmful queries\n",
540
+ " RESTRICTED_WORDS = {\n",
541
+ " 'delete', 'drop', 'truncate', 'update', 'insert', \n",
542
+ " 'alter', 'create', 'replace', 'modify', 'grant'\n",
543
+ " }\n",
544
+ " \n",
545
+ " # Allowed table names from our database\n",
546
+ " ALLOWED_TABLES = ['spring_2025_courses'] # in lowercase\n",
547
+ " \n",
548
+ " def __init__(self):\n",
549
+ " self.error_messages = []\n",
550
+ " \n",
551
+ " def validate_question(self, question: str) -> bool:\n",
552
+ " \"\"\"\n",
553
+ " Validate a natural language question\n",
554
+ " \n",
555
+ " Args:\n",
556
+ " question (str): User's input question\n",
557
+ " \n",
558
+ " Returns:\n",
559
+ " bool: True if valid, False otherwise\n",
560
+ " \"\"\"\n",
561
+ " self.error_messages = []\n",
562
+ " \n",
563
+ " # Check if question is empty or too long\n",
564
+ " if not question or not question.strip():\n",
565
+ " self.error_messages.append(\"Question cannot be empty\")\n",
566
+ " return False\n",
567
+ " \n",
568
+ " if len(question) > 500:\n",
569
+ " self.error_messages.append(\"Question is too long (max 500 characters)\")\n",
570
+ " return False\n",
571
+ " \n",
572
+ " # Check for basic SQL injection attempts\n",
573
+ " question_lower = question.lower()\n",
574
+ " if any(word in question_lower for word in self.RESTRICTED_WORDS):\n",
575
+ " self.error_messages.append(\"Question contains restricted keywords\")\n",
576
+ " return False\n",
577
+ " \n",
578
+ " # Check for excessive special characters\n",
579
+ " if re.search(r'[;{}\\\\]', question):\n",
580
+ " self.error_messages.append(\"Question contains invalid characters\")\n",
581
+ " return False\n",
582
+ " \n",
583
+ " return True\n",
584
+ " \n",
585
+ " def get_error_messages(self) -> List[str]:\n",
586
+ " \"\"\"Get all error messages from validation\"\"\"\n",
587
+ " return self.error_messages"
588
+ ]
589
+ },
590
+ {
591
+ "cell_type": "code",
592
+ "execution_count": 13,
593
+ "metadata": {},
594
+ "outputs": [],
595
+ "source": [
596
+ "class QueryValidator:\n",
597
+ " \"\"\"Validate generated SQL queries before execution\"\"\"\n",
598
+ "\n",
599
+ " def __init__(self, db_connection):\n",
600
+ " self.db = db_connection\n",
601
+ " self.error_messages = []\n",
602
+ " \n",
603
+ " def get_error_messages(self) -> List[str]:\n",
604
+ " \"\"\"Get all error messages from validation\"\"\"\n",
605
+ " return self.error_messages\n",
606
+ " \n",
607
+ " def validate_sql(self, sql: str) -> bool:\n",
608
+ " \"\"\"Validate generated SQL query\"\"\"\n",
609
+ " sql_lower = sql.lower()\n",
610
+ " \n",
611
+ " # Check if query is read-only (SELECT only)\n",
612
+ " if not sql_lower.strip().startswith('select'):\n",
613
+ " self.error_messages.append(\"Only SELECT queries are allowed\")\n",
614
+ " return False\n",
615
+ " \n",
616
+ " # Check for multiple statements\n",
617
+ " if ';' in sql[:-1]: # Allow semicolon at the end\n",
618
+ " self.error_messages.append(\"Multiple SQL statements are not allowed\")\n",
619
+ " return False\n",
620
+ " \n",
621
+ " # Validate table names\n",
622
+ " table = self._extract_table_names(sql_lower)\n",
623
+ " if table not in InputValidator.ALLOWED_TABLES:\n",
624
+ " self.error_messages.append(\"Query contains invalid table names\")\n",
625
+ " return False\n",
626
+ " \n",
627
+ " return True\n",
628
+ " \n",
629
+ " def _extract_table_names(self, sql: str) -> str:\n",
630
+ " \"\"\"Extract table names from SQL query\"\"\"\n",
631
+ " # Simple regex to extract table names\n",
632
+ " # Note: This is a basic implementation\n",
633
+ " from_matches = re.findall(r'from\\s+([a-zA-Z_][a-zA-Z0-9_]*)', sql.lower())\n",
634
+ " # join_matches = re.findall(r'join\\s+([a-zA-Z_][a-zA-Z0-9_]*)', sql)\n",
635
+ " return from_matches[0]"
636
+ ]
637
+ },
638
+ {
639
+ "cell_type": "code",
640
+ "execution_count": 14,
641
+ "metadata": {},
642
+ "outputs": [],
643
+ "source": [
644
+ "class SafeQueryExecutor:\n",
645
+ " \"\"\"Safe execution of natural language queries\"\"\"\n",
646
+ " \n",
647
+ " def __init__(self, db_connection, llm_chain):\n",
648
+ " self.input_validator = InputValidator()\n",
649
+ " self.query_validator = QueryValidator(db_connection)\n",
650
+ " self.db = db_connection\n",
651
+ " self.chain = llm_chain\n",
652
+ " \n",
653
+ " def execute_safe_query(self, question: str) -> Dict:\n",
654
+ " \"\"\"\n",
655
+ " Safely execute a natural language query\n",
656
+ " \n",
657
+ " Args:\n",
658
+ " question (str): User's natural language question\n",
659
+ " \n",
660
+ " Returns:\n",
661
+ " dict: Query result and status\n",
662
+ " \"\"\"\n",
663
+ " # Validate input\n",
664
+ " if not self.input_validator.validate_question(question):\n",
665
+ " return {\n",
666
+ " 'success': False,\n",
667
+ " 'error': self.input_validator.get_error_messages(),\n",
668
+ " 'query': None,\n",
669
+ " 'result': None\n",
670
+ " }\n",
671
+ " \n",
672
+ " try:\n",
673
+ " # Generate SQL query\n",
674
+ " sql_query = sql_generator.invoke({\"question\": question})\n",
675
+ " \n",
676
+ " # Validate generated SQL\n",
677
+ " if not self.query_validator.validate_sql(sql_query):\n",
678
+ " return {\n",
679
+ " 'success': False,\n",
680
+ " 'error': self.query_validator.get_error_messages(),\n",
681
+ " 'query': sql_query,\n",
682
+ " 'result': None\n",
683
+ " }\n",
684
+ " \n",
685
+ " # Execute query\n",
686
+ " result = complete_chain.invoke({\"question\": question})\n",
687
+ " \n",
688
+ " return {\n",
689
+ " 'success': True,\n",
690
+ " 'error': None,\n",
691
+ " 'query': sql_query,\n",
692
+ " 'result': result\n",
693
+ " }\n",
694
+ " \n",
695
+ " except Exception as e:\n",
696
+ " return {\n",
697
+ " 'success': False,\n",
698
+ " 'error': [str(e)],\n",
699
+ " 'query': None,\n",
700
+ " 'result': None\n",
701
+ " }"
702
+ ]
703
+ },
704
+ {
705
+ "cell_type": "code",
706
+ "execution_count": null,
707
+ "metadata": {},
708
+ "outputs": [],
709
+ "source": [
710
+ "# Initialize the safe executor\n",
711
+ "safe_executor = SafeQueryExecutor(db, complete_chain)\n",
712
+ "\n",
713
+ "result1 = safe_executor.execute_safe_query(\"Which courses are available in the Data Science department for Spring 2025?\")\n",
714
+ "print(\"\\nValid Query Result:\")\n",
715
+ "print(result1)"
716
+ ]
717
+ },
718
+ {
719
+ "cell_type": "code",
720
+ "execution_count": 15,
721
+ "metadata": {},
722
+ "outputs": [
723
+ {
724
+ "name": "stdout",
725
+ "output_type": "stream",
726
+ "text": [
727
+ "\n",
728
+ "Valid Query Result:\n",
729
+ "{'success': True, 'error': None, 'query': \" \\nSELECT CourseTitle FROM Spring_2025_courses WHERE Department LIKE '%Data Science%';\", 'result': ' The available courses in the Data Science department for Spring 2025 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.'}\n",
730
+ "\n",
731
+ "Invalid Query Result:\n",
732
+ "{'success': True, 'error': None, 'query': \" \\nSELECT * FROM Spring_2025_courses WHERE CourseTitle LIKE '%Introduction to Python%';\", 'result': ' The course Introduction to Python is not offered in Spring 2025.'}\n",
733
+ "\n",
734
+ "Restricted Query Result:\n",
735
+ "{'success': False, 'error': ['Multiple SQL statements are not allowed'], 'query': ' \\nSELECT COUNT(CourseCode) FROM Spring_2025_courses WHERE Program LIKE \\'%Bachelor of Science%\\' AND Department LIKE \\'%Computer Science%\\' AND \"New/Repeat\" IS NULL; \\n\\nHowever, since New/Repeat is not supposed to be used in queries according to the prompt, the query should be revised to:\\n\\nSELECT COUNT(CourseCode) FROM Spring_2025_courses WHERE Program LIKE \\'%Bachelor of Science%\\' AND Department LIKE \\'%Computer Science%\\'; \\n\\nHowever, considering the table schema, the query should be revised to:\\n\\nSELECT COUNT(CourseCode) FROM Spring_2025_courses WHERE Program LIKE \\'%Bachelor of Science%\\' AND Department LIKE \\'%Computer Science%\\'; \\n\\nHowever, this query may not be accurate because it does not account for the case where the department is \\'Computer Science (CS), Computer Networks and Cybersecurity (CNCS)\\'. Therefore, the query should be revised to:\\n\\nSELECT COUNT(CourseCode) FROM Spring_2025_courses WHERE Program LIKE \\'%Bachelor of Science%\\' AND (Department LIKE \\'%Computer Science%\\' OR Department LIKE \\'%Computer Networks and Cybersecurity%\\'); \\n\\nHowever, this query may still not be accurate because it does not account for the case where the department is \\'Computer Science (CS), Computer Networks and Cybersecurity (CNCS)\\' and the program is \\'Bachelor of Science\\'. Therefore, the query should be revised to:\\n\\nSELECT COUNT(CourseCode) FROM Spring_2025_courses WHERE Program LIKE \\'%Bachelor of Science%\\' AND Department LIKE \\'%Computer Science (CS), Computer Networks and Cybersecurity (CNCS)%\\'; \\n\\nHowever, this query may still not be accurate because it does not account for the case where the department is \\'Computer Science (CS), Computer Networks and Cybersecurity (CNCS)\\' and the program is \\'Bachelor of Science\\' and the department name may not be exact. Therefore, the query should be revised to:\\n\\nSELECT COUNT(CourseCode) FROM Spring_2025_courses WHERE Program LIKE \\'%Bachelor of Science%\\' AND Department LIKE \\'%Computer Science%\\' AND Department LIKE \\'%Computer Networks and Cybersecurity%\\'; \\n\\nHowever, the query is still not accurate because it requires the department to have both \\'Computer Science\\' and \\'Computer Networks and Cybersecurity\\' which may not be the case. Therefore, the query should be revised to:\\n\\nSELECT COUNT(CourseCode) FROM Spring_2025_courses WHERE Program LIKE \\'%Bachelor of Science%\\' AND (Department LIKE \\'%Computer Science%\\' OR Department LIKE \\'%Computer Networks and Cybersecurity%\\'); \\n\\nHowever, this query may still not be accurate because', 'result': None}\n",
736
+ "\n",
737
+ "Restricted Query Result:\n",
738
+ "{'success': True, 'error': None, 'query': \" \\nSELECT CourseTitle FROM Spring_2025_courses WHERE Instructor LIKE '%Qu%';\", 'result': ' 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 in Spring 2025.'}\n"
739
+ ]
740
+ }
741
+ ],
742
+ "source": [
743
+ "# Initialize the safe executor\n",
744
+ "safe_executor = SafeQueryExecutor(db, complete_chain)\n",
745
+ "\n",
746
+ "# Example queries\n",
747
+ "def test_queries():\n",
748
+ " # Valid query\n",
749
+ " result1 = safe_executor.execute_safe_query(\"Which courses are available in the Data Science department for Spring 2025?\")\n",
750
+ " print(\"\\nValid Query Result:\")\n",
751
+ " print(result1)\n",
752
+ " \n",
753
+ " # Invalid query with SQL injection attempt\n",
754
+ " result2 = safe_executor.execute_safe_query(\"\"\"What are the details of the course ‘Introduction to Python’?\"\"\")\n",
755
+ " print(\"\\nInvalid Query Result:\")\n",
756
+ " print(result2)\n",
757
+ " \n",
758
+ " # Query with restricted words\n",
759
+ " result3 = safe_executor.execute_safe_query(\"How many courses are offered under the Computer Science (Bachelor of Science) program?\")\n",
760
+ " print(\"\\nRestricted Query Result:\")\n",
761
+ " print(result3)\n",
762
+ "\n",
763
+ " # Query with restricted words\n",
764
+ " result4 = safe_executor.execute_safe_query(\"Show me the courses taught by Dr. Qu in Spring 2025.\")\n",
765
+ " print(\"\\nRestricted Query Result:\")\n",
766
+ " print(result4)\n",
767
+ " \n",
768
+ "# Run test queries\n",
769
+ "test_queries()"
770
+ ]
771
+ },
772
+ {
773
+ "cell_type": "code",
774
+ "execution_count": null,
775
+ "metadata": {},
776
+ "outputs": [],
777
+ "source": [
778
+ "result1 = safe_executor.execute_safe_query(\"DROP TABLE courses;\")\n",
779
+ "result1"
780
+ ]
781
+ }
782
+ ],
783
+ "metadata": {
784
+ "kernelspec": {
785
+ "display_name": "COS243",
786
+ "language": "python",
787
+ "name": "python3"
788
+ },
789
+ "language_info": {
790
+ "codemirror_mode": {
791
+ "name": "ipython",
792
+ "version": 3
793
+ },
794
+ "file_extension": ".py",
795
+ "mimetype": "text/x-python",
796
+ "name": "python",
797
+ "nbconvert_exporter": "python",
798
+ "pygments_lexer": "ipython3",
799
+ "version": "3.12.5"
800
+ }
801
+ },
802
+ "nbformat": 4,
803
+ "nbformat_minor": 2
804
+ }