File size: 11,715 Bytes
e03e6d4
c1915cc
e03e6d4
 
 
 
 
554f05c
 
 
 
c1915cc
 
 
 
 
 
e03e6d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
from langchain_community.utilities import SQLDatabase
from langchain_community.llms import DeepInfra
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
import re
from typing import Dict, List
import os
from dotenv import load_dotenv

load_dotenv()

api = os.getenv("DEEPINFRA_TOKEN")
deepinfra_model = "meta-llama/Llama-3.3-70B-Instruct"

llm = DeepInfra(model_id=deepinfra_model,
                    deepinfra_api_token=api)


# Initialize database connection
db = SQLDatabase.from_uri("sqlite:///Spring_2025_courses.db", sample_rows_in_table_info=0)

# Helper functions 
def get_schema(_):
    """Retrieve database schema"""
    return db.get_table_info()

def run_query(query):
    """Execute SQL query"""
    return db.run(query)

# SQL generation prompt
system_prompt = """
You are a SQLite expert. Given an input question, create one syntactically correct SQLite query to run. Generate only one query. No pre-amble.

Here is the relevant table information:
schema: {schema}
Departments: 'Applied Math & Statistics', 'ART', 'Biomedical Science (BMS)', 'Computer Science (CS), Computer Networks and Cybersecurity (CNCS)', 'Data Science (DS)', 'Dance', 'General Education (GE)'
New/Repeat: Have no values (Don't use New/Repeat in queries)

Tips:
- Use LIKE instead of = in the queries

Below are a number of examples of questions and their corresponding SQL queries.

example 1:
Question:List all departments.
SQL query:SELECT Department FROM Spring_2025_courses;

example 2:
Question:Find all classes that are taught by Dr. Qu.
SQL query:SELECT CourseTitle FROM Spring_2025_courses WHERE Instructor LIKE '%Qu%';

example 3:
Question:List all courses in the Data Science department.
SQL query:SELECT CourseCode, CourseTitle FROM Spring_2025_courses WHERE Department LIKE '%Data Science%';

example 4:
Question:Find the total number of courses offered for Spring 2025.
SQL query:SELECT COUNT(CourseCode) FROM Spring_2025_courses;

example 5:
Question:List all professors from Biomed Department.
SQL query:SELECT Instructor FROM Spring_2025_courses WHERE Department LIKE '%Biomed%';

example 6:
Question:Which courses are available in the Biomed department for Spring 2025?
SQL query:SELECT CourseTitle FROM Spring_2025_courses WHERE Department LIKE '%Biomed%';

example 7:
Question:How many courses are offered under the Arts Management (BFA) program?
SQL query:SELECT COUNT(CourseCode) FROM Spring_2025_courses WHERE Department LIKE Program LIKE '%BFA%'

example 8:
Question:Which courses are available for the Master of Science in Applied Math?
SQL query:SELECT CourseTitle FROM Spring_2025_courses WHERE Program LIKE '%Master of Science%' AND Department LIKE '%Applied Math%';

Write only one SQLite query that would answer the user's question. No pre-amble.
"""

human_prompt = """Based on the table schema below, write a SQL query that would answer the user's question:
{schema}

Question: {question}
SQL Query:"""

prompt = ChatPromptTemplate.from_messages([
    ("system", system_prompt),
    ("human", human_prompt),
])

# Build query generation chain
sql_generator = (
    RunnablePassthrough.assign(schema=get_schema)
    | prompt
    | llm.bind(stop=["\nSQLResult:"])
    | StrOutputParser()
)

# Natural language response generation
nl_system_prompt = """Given an input question and SQL response, convert it to a natural language answer. 

Below are a number of examples of questions and their corresponding SQL queries.

example 1: 
Question: Which courses are available in the Data Science department?
SQL Query: SELECT CourseTitle FROM Spring_2025_courses WHERE Department LIKE '%Data Science%';
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',)]
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.

example 2:
Question: Find all classes that are taught by Dr. Qu.
SQL Query: SELECT CourseTitle FROM Spring_2025_courses WHERE Instructor LIKE '%Qu%';
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)',)]
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.

Generate only ONE answer based on the SQL response. No pre-amble.
"""

response_prompt = """Based on the table schema below, question, sql query, and sql response, write a natural language response. No pre-amble:
{schema}

Question:{question}
SQL Query:{query}
SQL Response:{response}
Response:"""

nl_prompt = ChatPromptTemplate.from_messages([
    ("system", nl_system_prompt),
    ("human", response_prompt),
])

# Complete chain with natural language output
complete_chain = (
    RunnablePassthrough.assign(query=sql_generator)
    | RunnablePassthrough.assign(
        schema=get_schema,
        response=lambda x: db.run(x['query']),
    )
    | nl_prompt
    | llm
)

class InputValidator:
    """Input validation and sanitization for database queries"""
    
    RESTRICTED_WORDS = {
        'delete', 'drop', 'truncate', 'update', 'insert', 
        'alter', 'create', 'replace', 'modify', 'grant'
    }
    
    ALLOWED_TABLES = ['spring_2025_courses']
    
    def __init__(self):
        self.error_messages = []
    
    def validate_question(self, question: str) -> bool:
        """
        Validate a natural language question
        
        Args:
            question (str): User's input question
            
        Returns:
            bool: True if valid, False otherwise
        """
        self.error_messages = []
        
        # Check if question is empty or too long
        if not question or not question.strip():
            self.error_messages.append("Question cannot be empty")
            return False
            
        if len(question) > 500:
            self.error_messages.append("Question is too long (max 500 characters)")
            return False
        
        # Check for basic SQL injection attempts
        question_lower = question.lower()
        if any(word in question_lower for word in self.RESTRICTED_WORDS):
            self.error_messages.append("Question contains restricted keywords")
            return False
        
        # Check for excessive special characters
        if re.search(r'[;{}\\]', question):
            self.error_messages.append("Question contains invalid characters")
            return False
            
        return True
    
    def get_error_messages(self) -> List[str]:
        """Get all error messages from validation"""
        return self.error_messages

class QueryValidator:
    """Validate generated SQL queries before execution"""

    def __init__(self, db_connection):
        self.db = db_connection
        self.error_messages = []
    
    def get_error_messages(self) -> List[str]:
        """Get all error messages from validation"""
        return self.error_messages
    
    def validate_sql(self, sql: str) -> bool:
        """Validate generated SQL query"""
        sql_lower = sql.lower()
        
        # Check if query is read-only (SELECT only)
        if not sql_lower.strip().startswith('select'):
            self.error_messages.append("Only SELECT queries are allowed")
            return False
        
        # Check for multiple statements
        if ';' in sql[:-1]:  # Allow semicolon at the end
            self.error_messages.append("Multiple SQL statements are not allowed")
            return False
        
        # Validate table names
        table = self._extract_table_names(sql_lower)
        if table not in InputValidator.ALLOWED_TABLES:
            self.error_messages.append("Query contains invalid table names")
            return False
            
        return True
    
    def _extract_table_names(self, sql: str) -> str:
        """Extract table names from SQL query"""
        from_matches = re.findall(r'from\s+([a-zA-Z_][a-zA-Z0-9_]*)', sql.lower())
        return from_matches[0]

class SafeQueryExecutor:
    """Safe execution of natural language queries"""
    
    def __init__(self, db_connection, llm_chain):
        self.input_validator = InputValidator()
        self.query_validator = QueryValidator(db_connection)
        self.db = db_connection
        self.chain = llm_chain
        
    def execute_safe_query(self, question: str) -> Dict:
        """
        Safely execute a natural language query
        
        Args:
            question (str): User's natural language question
            
        Returns:
            dict: Query result and status
        """
        # Validate input
        if not self.input_validator.validate_question(question):
            return {
                'success': False,
                'error': self.input_validator.get_error_messages(),
                'query': None,
                'result': None
            }
        
        try:
            # Generate SQL query
            sql_query = sql_generator.invoke({"question": question})
            
            # Validate generated SQL
            if not self.query_validator.validate_sql(sql_query):
                return {
                    'success': False,
                    'error': self.query_validator.get_error_messages(),
                    'query': sql_query,
                    'result': None
                }
            
            # Execute query
            result = complete_chain.invoke({"question": question})
            
            return {
                'success': True,
                'error': None,
                'query': sql_query,
                'result': result
            }
            
        except Exception as e:
            return {
                'success': False,
                'error': [str(e)],
                'query': None,
                'result': None
            }

# Initialize the safe executor
safe_executor = SafeQueryExecutor(db, complete_chain)

# Example queries
example_queries = [
    "Which courses are available in the Data Science department for Spring 2025?",
    "What are the details of the course 'Introduction to Python'?",
    "How many courses are offered under the Computer Science (Bachelor of Science) program?",
    "Show me the courses taught by Dr. Qu in Spring 2025."
]