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." ]