DebopamC commited on
Commit
0074668
·
verified ·
1 Parent(s): cb5a9ff

Update utils/llm_logic.py

Browse files
Files changed (1) hide show
  1. utils/llm_logic.py +262 -262
utils/llm_logic.py CHANGED
@@ -1,262 +1,262 @@
1
- # llm_logic.py
2
- # from langchain_ollama import ChatOllama
3
- from langchain_core.messages import HumanMessage, SystemMessage, AIMessage
4
- import streamlit as st
5
- import multiprocessing
6
- from langchain_community.chat_models import ChatLlamaCpp
7
- from langchain_google_genai import ChatGoogleGenerativeAI
8
-
9
- local_model = "qwen2.5-coder-3b-instruct-q4_k_m.gguf"
10
-
11
- stop = [
12
- "<|image_pad|>",
13
- "<|endoftext|>",
14
- "<|quad_end|>",
15
- "<|object_ref_end|>",
16
- "<|object_ref_start|>",
17
- "<|file_sep|>",
18
- "<|repo_name|>",
19
- "<|PAD_TOKEN|>",
20
- "<|quad_start|>",
21
- "<|box_start|>",
22
- "<|box_end|>",
23
- "<|im_start|>",
24
- "</tool_call>",
25
- "<|video_pad|>",
26
- "<tool_call>",
27
- "<|im_end|>",
28
- "<|vision_",
29
- "<|fim_",
30
- ]
31
-
32
-
33
- def get_local_llm():
34
- llm = ChatLlamaCpp(
35
- temperature=0.0,
36
- model_path=local_model,
37
- n_ctx=10000,
38
- n_gpu_layers=0,
39
- n_batch=1024,
40
- max_tokens=500,
41
- n_threads=multiprocessing.cpu_count() - 1,
42
- top_p=0.95,
43
- verbose=False,
44
- stop=stop,
45
- )
46
- # llm = ChatOllama(
47
- # model="qwen2.5-coder:3b",
48
- # temperature=0.0,
49
- # num_predict=150,
50
- # top_p=0.95,
51
- # stop=stop,
52
- # )
53
-
54
- return llm
55
-
56
-
57
- local_llm = get_local_llm()
58
-
59
-
60
- def get_gemini_llm():
61
- gemini = ChatGoogleGenerativeAI(
62
- model="gemini-2.0-flash-exp",
63
- temperature=0,
64
- max_tokens=None,
65
- timeout=None,
66
- max_retries=2,
67
- top_p=0.95,
68
- )
69
- return gemini
70
-
71
-
72
- gemini_llm = get_gemini_llm()
73
-
74
-
75
- db_schema = """### **customers**
76
- | | customer_id | customer_zip_code_prefix | customer_city | customer_state |
77
- |------:|:--------------|---------------------------:|:----------------|:-----------------|
78
- | 21921 | 0tgYlOTGgpO6 | 79230 | russas | CE |
79
- | 9748 | jGhRQF3CIew4 | 81460 | joao monlevade | MG |
80
- | 22679 | 1UutQTIhBvcP | 94480 | pelotas | RS |
81
-
82
- Rows: 38279, Columns: 4
83
-
84
- ---
85
-
86
- ### **order_items**
87
- | | order_id | product_id | seller_id | price | shipping_charges |
88
- |------:|:-------------|:-------------|:-------------|--------:|-------------------:|
89
- | 19729 | PDEzZdebLSn3 | aBpYjaBcwz6e | bzfcwRPnZzVO | 55.83 | 27.8 |
90
- | 6001 | R7bIPjjYqlHP | ZM2JJXV5m9hl | Ivbw25fb5t2Z | 100 | 42.05 |
91
- | 282 | Biqo21nETaMO | XqmdGKRbTetH | P2nCHWuo0HC0 | 113.49 | 91.32 |
92
-
93
- Rows: 38279, Columns: 5
94
-
95
- ---
96
-
97
- ### **orders**
98
-
99
- | | order_id | customer_id | order_purchase_timestamp | order_approved_at |
100
- |------:|:-------------|:--------------|:---------------------------|:--------------------|
101
- | 7294 | PMqwQc01iDTJ | c9ueC6k6V5WS | 2018-06-19 21:23:48 | 2018-06-20 08:38:30 |
102
- | 13800 | P4l8R2Qat5n7 | ovKkGaXi5TmN | 2018-01-05 08:26:03 | 2018-01-05 08:47:20 |
103
- | 17679 | NxIseZjAQCdC | o9qzmUQVJOxA | 2018-01-28 23:46:53 | 2018-01-28 23:58:31 |
104
-
105
- Rows: 38279, Columns: 4
106
-
107
- ---
108
-
109
- ### **payments**
110
- | | order_id | payment_sequential | payment_type | payment_installments | payment_value |
111
- |------:|:-------------|---------------------:|:---------------|-----------------------:|----------------:|
112
- | 35526 | cQXl0pQtiMad | 1 | wallet | 1 | 172.58 |
113
- | 35799 | olImD2k316Gz | 1 | credit_card | 3 | 16.78 |
114
- | 13278 | G9MJYXXtPZSz | 1 | credit_card | 10 | 221.86 |
115
-
116
- Rows: 38279, Columns: 5
117
-
118
- ---
119
-
120
- ### **products**
121
- | | product_id | product_category_name | product_weight_g | product_length_cm | product_height_cm | product_width_cm |
122
- |------:|:-------------|:------------------------|-------------------:|--------------------:|--------------------:|-------------------:|
123
- | 18191 | hpiXwRzTkhkL | bed_bath_table | 1150 | 40 | 9 | 50 |
124
- | 2202 | iPoRkE7dkmlc | toys | 15800 | 38 | 62 | 57 |
125
- | 27442 | hrjNaMt3Wyo5 | toys | 1850 | 37 | 22 | 40 |
126
-
127
- Rows: 38279, Columns: 6
128
-
129
- """
130
-
131
- # Improved SQL generation prompt
132
- sql_system_prompt = """You are a highly skilled natural language to SQL translator. Your goal is to generate accurate SQL queries based on the provided database schema. You must only return the SQL query and no other text or explanations.
133
- DATABASE SCHEMA:
134
- {db_schema}
135
-
136
- The timestamp columns are of type 'VarChar'. I am using DuckDB to execute the queries.
137
- """
138
- sql_chat_template = """
139
-
140
- Translate the following natural language question into an accurate SQL query. Return only the SQL query.
141
-
142
- QUESTION: {question}
143
-
144
- ### assistant:
145
-
146
- """
147
-
148
- # Improved prompt for classifying the question
149
- classification_system_prompt = """You are an expert at classifying user questions as requiring a SQL query or being generic based on the provided database schema. Your response should be ONLY 'SQL' or 'GENERIC'.
150
-
151
- A question requires a SQL query if it asks for specific data that can be retrieved from the tables in the schema. A question is generic if it asks for explanations, definitions, or information not directly retrievable through a SQL query on the given schema.
152
-
153
- Consider the following database schema:
154
- {db_schema}
155
-
156
- Here are some examples:
157
-
158
- Question: What are the names of all customers?
159
- Response: SQL
160
-
161
- Question: Tell me about the sales table.
162
- Response: GENERIC
163
-
164
- Question: How much did product 'Product A' sell for?
165
- Response: SQL
166
-
167
- Question: What is a primary key?
168
- Response: GENERIC
169
- """
170
- classification_chat_template = """
171
-
172
- Determine if the following question requires a SQL query based on the database schema. Respond with 'SQL' or 'GENERIC'.
173
-
174
- QUESTION: {question}
175
-
176
- ### assistant:
177
- """
178
-
179
-
180
- def classify_question(question: str, llm, use_default_schema: bool = True):
181
- classification_system_prompt_local = classification_system_prompt # Initialize here
182
- if use_default_schema:
183
- classification_system_prompt_local = classification_system_prompt_local.format(
184
- db_schema=db_schema
185
- )
186
- else:
187
- uploaded_schema = st.session_state.uploaded_df_schema
188
- classification_system_prompt_local = classification_system_prompt_local.format(
189
- db_schema=uploaded_schema
190
- )
191
- classification_messages = [
192
- SystemMessage(content=classification_system_prompt_local),
193
- HumanMessage(content=classification_chat_template.format(question=question)),
194
- ]
195
- response = llm.invoke(classification_messages)
196
- return response.content.strip().upper()
197
-
198
-
199
- def generate_llm_response(prompt: str, llm: str, use_default_schema: bool = True):
200
-
201
- if llm == "gemini":
202
- llm = gemini_llm
203
- else:
204
- llm = local_llm
205
-
206
- question_type = classify_question(prompt, llm, use_default_schema)
207
- chosen_schema = None
208
- if use_default_schema:
209
- chosen_schema = db_schema
210
- sql_system_prompt_local = sql_system_prompt.format(db_schema=chosen_schema)
211
- else:
212
- uploaded_schema = st.session_state.uploaded_df_schema
213
- chosen_schema = uploaded_schema
214
- sql_system_prompt_local = sql_system_prompt.format(db_schema=chosen_schema)
215
-
216
- # Retrieve the chat history from the session state
217
- chat_history = st.session_state.get("chat_history", [])
218
-
219
- if "SQL" in question_type:
220
- print("SQL question detected")
221
- st.toast("Detected Task: SQL Query Generation", icon="🚨")
222
- formatted_prompt = sql_chat_template.format(question=prompt)
223
-
224
- # Create the messages list, including the system prompt and the chat history
225
- messages_for_llm = [SystemMessage(content=sql_system_prompt_local)]
226
- for message in chat_history:
227
- if isinstance(message, HumanMessage):
228
- messages_for_llm.append(HumanMessage(content=message.content))
229
- elif isinstance(message, AIMessage):
230
- # Only include the assistant's text response, not the additional kwargs
231
- messages_for_llm.append(AIMessage(content=message.content))
232
- messages_for_llm.append(HumanMessage(content=formatted_prompt))
233
-
234
- full_response = ""
235
- for chunk in llm.stream(messages_for_llm):
236
- full_response += chunk.content
237
- yield f"<sql>\n```sql\n{full_response.strip()}\n```\n</sql>"
238
- elif "GENERIC" in question_type:
239
- print("Generic question detected")
240
- st.toast("Detected Task: Generic QA", icon="🚨")
241
- generic_prompt = f"Answer the following question related to SQL or coding:\n\nQUESTION: {prompt}\n\n### assistant:"
242
-
243
- # Create the messages list, including the system prompt and the chat history
244
- messages_for_generic = [
245
- SystemMessage(
246
- content=f"You are a helpful assistant finetuned from Qwen2.5-coder:3B-Instruct for answering questions about SQL.\nYou have a database with the Database Schema:\n{chosen_schema}.\n"
247
- )
248
- ]
249
- for message in chat_history:
250
- if isinstance(message, HumanMessage):
251
- messages_for_generic.append(HumanMessage(content=message.content))
252
- elif isinstance(message, AIMessage):
253
- # Only include the assistant's text response, not the additional kwargs
254
- messages_for_generic.append(AIMessage(content=message.content))
255
- messages_for_generic.append(HumanMessage(content=generic_prompt))
256
-
257
- generic_response = ""
258
- for chunk in llm.stream(messages_for_generic):
259
- generic_response += chunk.content
260
- yield generic_response
261
- else:
262
- yield "I am sorry, I am small language model fine-tuned specifically to answer questions that can be solved using SQL. I won't be able to answer this question."
 
1
+ # llm_logic.py
2
+ # from langchain_ollama import ChatOllama
3
+ from langchain_core.messages import HumanMessage, SystemMessage, AIMessage
4
+ import streamlit as st
5
+ import multiprocessing
6
+ from langchain_community.chat_models import ChatLlamaCpp
7
+ from langchain_google_genai import ChatGoogleGenerativeAI
8
+
9
+ local_model = "qwen2.5-coder-3b-instruct-q4_k_m.gguf"
10
+
11
+ stop = [
12
+ "<|image_pad|>",
13
+ "<|endoftext|>",
14
+ "<|quad_end|>",
15
+ "<|object_ref_end|>",
16
+ "<|object_ref_start|>",
17
+ "<|file_sep|>",
18
+ "<|repo_name|>",
19
+ "<|PAD_TOKEN|>",
20
+ "<|quad_start|>",
21
+ "<|box_start|>",
22
+ "<|box_end|>",
23
+ "<|im_start|>",
24
+ "</tool_call>",
25
+ "<|video_pad|>",
26
+ "<tool_call>",
27
+ "<|im_end|>",
28
+ "<|vision_",
29
+ "<|fim_",
30
+ ]
31
+
32
+
33
+ def get_local_llm():
34
+ llm = ChatLlamaCpp(
35
+ temperature=0.0,
36
+ model_path=local_model,
37
+ n_ctx=10000,
38
+ n_gpu_layers=0,
39
+ n_batch=1024,
40
+ max_tokens=500,
41
+ n_threads=multiprocessing.cpu_count() - 1,
42
+ top_p=0.95,
43
+ verbose=False,
44
+ stop=stop,
45
+ )
46
+ # llm = ChatOllama(
47
+ # model="qwen2.5-coder:3b",
48
+ # temperature=0.0,
49
+ # num_predict=150,
50
+ # top_p=0.95,
51
+ # stop=stop,
52
+ # )
53
+
54
+ return llm
55
+
56
+
57
+ local_llm = get_local_llm()
58
+
59
+
60
+ def get_gemini_llm():
61
+ gemini = ChatGoogleGenerativeAI(
62
+ model="gemini-2.0-flash",
63
+ temperature=0,
64
+ max_tokens=None,
65
+ timeout=None,
66
+ max_retries=2,
67
+ top_p=0.95,
68
+ )
69
+ return gemini
70
+
71
+
72
+ gemini_llm = get_gemini_llm()
73
+
74
+
75
+ db_schema = """### **customers**
76
+ | | customer_id | customer_zip_code_prefix | customer_city | customer_state |
77
+ |------:|:--------------|---------------------------:|:----------------|:-----------------|
78
+ | 21921 | 0tgYlOTGgpO6 | 79230 | russas | CE |
79
+ | 9748 | jGhRQF3CIew4 | 81460 | joao monlevade | MG |
80
+ | 22679 | 1UutQTIhBvcP | 94480 | pelotas | RS |
81
+
82
+ Rows: 38279, Columns: 4
83
+
84
+ ---
85
+
86
+ ### **order_items**
87
+ | | order_id | product_id | seller_id | price | shipping_charges |
88
+ |------:|:-------------|:-------------|:-------------|--------:|-------------------:|
89
+ | 19729 | PDEzZdebLSn3 | aBpYjaBcwz6e | bzfcwRPnZzVO | 55.83 | 27.8 |
90
+ | 6001 | R7bIPjjYqlHP | ZM2JJXV5m9hl | Ivbw25fb5t2Z | 100 | 42.05 |
91
+ | 282 | Biqo21nETaMO | XqmdGKRbTetH | P2nCHWuo0HC0 | 113.49 | 91.32 |
92
+
93
+ Rows: 38279, Columns: 5
94
+
95
+ ---
96
+
97
+ ### **orders**
98
+
99
+ | | order_id | customer_id | order_purchase_timestamp | order_approved_at |
100
+ |------:|:-------------|:--------------|:---------------------------|:--------------------|
101
+ | 7294 | PMqwQc01iDTJ | c9ueC6k6V5WS | 2018-06-19 21:23:48 | 2018-06-20 08:38:30 |
102
+ | 13800 | P4l8R2Qat5n7 | ovKkGaXi5TmN | 2018-01-05 08:26:03 | 2018-01-05 08:47:20 |
103
+ | 17679 | NxIseZjAQCdC | o9qzmUQVJOxA | 2018-01-28 23:46:53 | 2018-01-28 23:58:31 |
104
+
105
+ Rows: 38279, Columns: 4
106
+
107
+ ---
108
+
109
+ ### **payments**
110
+ | | order_id | payment_sequential | payment_type | payment_installments | payment_value |
111
+ |------:|:-------------|---------------------:|:---------------|-----------------------:|----------------:|
112
+ | 35526 | cQXl0pQtiMad | 1 | wallet | 1 | 172.58 |
113
+ | 35799 | olImD2k316Gz | 1 | credit_card | 3 | 16.78 |
114
+ | 13278 | G9MJYXXtPZSz | 1 | credit_card | 10 | 221.86 |
115
+
116
+ Rows: 38279, Columns: 5
117
+
118
+ ---
119
+
120
+ ### **products**
121
+ | | product_id | product_category_name | product_weight_g | product_length_cm | product_height_cm | product_width_cm |
122
+ |------:|:-------------|:------------------------|-------------------:|--------------------:|--------------------:|-------------------:|
123
+ | 18191 | hpiXwRzTkhkL | bed_bath_table | 1150 | 40 | 9 | 50 |
124
+ | 2202 | iPoRkE7dkmlc | toys | 15800 | 38 | 62 | 57 |
125
+ | 27442 | hrjNaMt3Wyo5 | toys | 1850 | 37 | 22 | 40 |
126
+
127
+ Rows: 38279, Columns: 6
128
+
129
+ """
130
+
131
+ # Improved SQL generation prompt
132
+ sql_system_prompt = """You are a highly skilled natural language to SQL translator. Your goal is to generate accurate SQL queries based on the provided database schema. You must only return the SQL query and no other text or explanations.
133
+ DATABASE SCHEMA:
134
+ {db_schema}
135
+
136
+ The timestamp columns are of type 'VarChar'. I am using DuckDB to execute the queries.
137
+ """
138
+ sql_chat_template = """
139
+
140
+ Translate the following natural language question into an accurate SQL query. Return only the SQL query.
141
+
142
+ QUESTION: {question}
143
+
144
+ ### assistant:
145
+
146
+ """
147
+
148
+ # Improved prompt for classifying the question
149
+ classification_system_prompt = """You are an expert at classifying user questions as requiring a SQL query or being generic based on the provided database schema. Your response should be ONLY 'SQL' or 'GENERIC'.
150
+
151
+ A question requires a SQL query if it asks for specific data that can be retrieved from the tables in the schema. A question is generic if it asks for explanations, definitions, or information not directly retrievable through a SQL query on the given schema.
152
+
153
+ Consider the following database schema:
154
+ {db_schema}
155
+
156
+ Here are some examples:
157
+
158
+ Question: What are the names of all customers?
159
+ Response: SQL
160
+
161
+ Question: Tell me about the sales table.
162
+ Response: GENERIC
163
+
164
+ Question: How much did product 'Product A' sell for?
165
+ Response: SQL
166
+
167
+ Question: What is a primary key?
168
+ Response: GENERIC
169
+ """
170
+ classification_chat_template = """
171
+
172
+ Determine if the following question requires a SQL query based on the database schema. Respond with 'SQL' or 'GENERIC'.
173
+
174
+ QUESTION: {question}
175
+
176
+ ### assistant:
177
+ """
178
+
179
+
180
+ def classify_question(question: str, llm, use_default_schema: bool = True):
181
+ classification_system_prompt_local = classification_system_prompt # Initialize here
182
+ if use_default_schema:
183
+ classification_system_prompt_local = classification_system_prompt_local.format(
184
+ db_schema=db_schema
185
+ )
186
+ else:
187
+ uploaded_schema = st.session_state.uploaded_df_schema
188
+ classification_system_prompt_local = classification_system_prompt_local.format(
189
+ db_schema=uploaded_schema
190
+ )
191
+ classification_messages = [
192
+ SystemMessage(content=classification_system_prompt_local),
193
+ HumanMessage(content=classification_chat_template.format(question=question)),
194
+ ]
195
+ response = llm.invoke(classification_messages)
196
+ return response.content.strip().upper()
197
+
198
+
199
+ def generate_llm_response(prompt: str, llm: str, use_default_schema: bool = True):
200
+
201
+ if llm == "gemini":
202
+ llm = gemini_llm
203
+ else:
204
+ llm = local_llm
205
+
206
+ question_type = classify_question(prompt, llm, use_default_schema)
207
+ chosen_schema = None
208
+ if use_default_schema:
209
+ chosen_schema = db_schema
210
+ sql_system_prompt_local = sql_system_prompt.format(db_schema=chosen_schema)
211
+ else:
212
+ uploaded_schema = st.session_state.uploaded_df_schema
213
+ chosen_schema = uploaded_schema
214
+ sql_system_prompt_local = sql_system_prompt.format(db_schema=chosen_schema)
215
+
216
+ # Retrieve the chat history from the session state
217
+ chat_history = st.session_state.get("chat_history", [])
218
+
219
+ if "SQL" in question_type:
220
+ print("SQL question detected")
221
+ st.toast("Detected Task: SQL Query Generation", icon="🚨")
222
+ formatted_prompt = sql_chat_template.format(question=prompt)
223
+
224
+ # Create the messages list, including the system prompt and the chat history
225
+ messages_for_llm = [SystemMessage(content=sql_system_prompt_local)]
226
+ for message in chat_history:
227
+ if isinstance(message, HumanMessage):
228
+ messages_for_llm.append(HumanMessage(content=message.content))
229
+ elif isinstance(message, AIMessage):
230
+ # Only include the assistant's text response, not the additional kwargs
231
+ messages_for_llm.append(AIMessage(content=message.content))
232
+ messages_for_llm.append(HumanMessage(content=formatted_prompt))
233
+
234
+ full_response = ""
235
+ for chunk in llm.stream(messages_for_llm):
236
+ full_response += chunk.content
237
+ yield f"<sql>\n```sql\n{full_response.strip()}\n```\n</sql>"
238
+ elif "GENERIC" in question_type:
239
+ print("Generic question detected")
240
+ st.toast("Detected Task: Generic QA", icon="🚨")
241
+ generic_prompt = f"Answer the following question related to SQL or coding:\n\nQUESTION: {prompt}\n\n### assistant:"
242
+
243
+ # Create the messages list, including the system prompt and the chat history
244
+ messages_for_generic = [
245
+ SystemMessage(
246
+ content=f"You are a helpful assistant finetuned from Qwen2.5-coder:3B-Instruct for answering questions about SQL.\nYou have a database with the Database Schema:\n{chosen_schema}.\n"
247
+ )
248
+ ]
249
+ for message in chat_history:
250
+ if isinstance(message, HumanMessage):
251
+ messages_for_generic.append(HumanMessage(content=message.content))
252
+ elif isinstance(message, AIMessage):
253
+ # Only include the assistant's text response, not the additional kwargs
254
+ messages_for_generic.append(AIMessage(content=message.content))
255
+ messages_for_generic.append(HumanMessage(content=generic_prompt))
256
+
257
+ generic_response = ""
258
+ for chunk in llm.stream(messages_for_generic):
259
+ generic_response += chunk.content
260
+ yield generic_response
261
+ else:
262
+ yield "I am sorry, I am small language model fine-tuned specifically to answer questions that can be solved using SQL. I won't be able to answer this question."