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

Delete llm_logic.py

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