CD17 commited on
Commit
1644ab7
·
verified ·
1 Parent(s): 554f05c

Delete functions_llama.py

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