File size: 17,877 Bytes
4db8795
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34a5262
 
 
 
4db8795
34a5262
 
 
 
 
 
 
 
4db8795
 
34a5262
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4db8795
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34a5262
 
 
4db8795
34a5262
4db8795
34a5262
 
4db8795
 
 
34a5262
 
4db8795
34a5262
 
 
 
4db8795
34a5262
 
 
4db8795
 
 
34a5262
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4db8795
 
 
34a5262
4db8795
 
 
 
 
 
34a5262
 
 
 
4db8795
34a5262
 
4db8795
34a5262
4db8795
 
 
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
# ## creating database tools 
# from langchain_core.tools import tool
# from app.schemas.agent_state import SQLAgentState
# from typing import Dict
# from langchain_core.messages import AIMessage, HumanMessage
# from app.utils.database_connection import DatabaseConnection
# from langchain_community.agent_toolkits import SQLDatabaseToolkit
# from app.schemas.agent_state import DBQuery
# from langchain_core.prompts import ChatPromptTemplate

# class DatabaseTools:
#     def __init__(self,db = None, llm = None):
#         self.db = db 
#         self.llm = llm
#         self._create_query_tool = self._create_query_tool()
#         try:
#                 # Initialize toolkit and tools
#                 self.toolkit = SQLDatabaseToolkit(db=self.db, llm=self.llm)
#                 self.tools = self.toolkit.get_tools()
#                 for tool in self.tools:
#                     print(f"Initialized tool: {tool.name}")

#                 # Create instances of the tools
#                 self.list_tables_tool = next((tool for tool in self.tools if tool.name == "sql_db_list_tables"), None)
#                 self.query_tool = next((tool for tool in self.tools if tool.name == "sql_db_query"), None)
#                 self.get_schema_tool = next((tool for tool in self.tools if tool.name == "sql_db_schema"), None)
#                 self.query_checker_tool = next((tool for tool in self.tools if tool.name == "sql_db_query_checker"), None)
#                 if not all([self.list_tables_tool, self.query_tool, self.get_schema_tool, self.query_checker_tool]):
#                     raise ValueError("Failed to initialize one or more required database tools")

#                 # # Initialize workflow and compile it into an app
#                 # self.initialize_workflow()
                
#         except Exception as e:
#             print(f"Error initializing tools and workflow: {str(e)}")
#             raise ValueError(f"Failed to initialize database tools: {str(e)}")
    
#     def _create_query_tool(self):
#             """Create the query tool bound to this instance"""
#             print("creating _create_query_tool")
#             @tool
#             def query_to_database(query: str) -> str:
#                 """
#                 Execute a SQL query against the database and return the result.
#                 If the query is invalid or returns no result, an error message will be returned.
#                 In case of an error, the user is advised to rewrite the query and try again.
#                 """
#                 if self.db is None:
#                     return "Error: Database connection not established. Please set up the connection first."
#                 result = self.db.run_no_throw(query)
#                 if not result:
#                     return "Error: Query failed. Please rewrite your query and try again."
#                 return result
            
#             return query_to_database

#     def list_table_tools(self, state: SQLAgentState = None) -> Dict:
#             """List all the tables"""
#             tables_list = self.list_tables_tool.invoke("")
#             print(f"Tables found: {tables_list}")
#             return {
#                 "messages": [AIMessage(content=f"Tables found: {tables_list}")],
#                 "tables_list": tables_list,
#                 "next_tool": "sql_agent"
#             }
    
#     def get_schema(self,state: SQLAgentState) -> Dict:
#             """Get the schema of required tables"""
#             print("πŸ“˜ Getting schema...")
#             tables_list = state.get("tables_list", "")
#             if not tables_list:
#                 tables_list = self.list_tables_tool.invoke("")
            
#             tables = [table.strip() for table in tables_list.split(",")]
#             full_schema = ""
            
#             for table in tables:
#                 try:
#                     schema = self.get_schema_tool.invoke(table)
#                     full_schema += f"\nTable: {table}\n{schema}\n"
#                 except Exception as e:
#                     print(f"Error getting schema for {table}: {e}")
            
#             print(f"πŸ“˜ Schema collected for tables: {tables}")
#             return {
#                 "messages": [AIMessage(content=f"Schema retrieved: {full_schema}")],
#                 "schema_of_table": full_schema,
#                 "tables_list": tables_list,
#                 "next_tool": "sql_agent"
#             }
#     def generate_query(self, state: SQLAgentState) -> Dict:
#             """Generate a SQL Query according to the user query"""
#             schema = state.get("schema_of_table", "")
#             human_query = state.get("query", "")
#             tables = state.get("tables_list", "")
            
#             print(f"Generating query for: {human_query}")
            
#             generate_query_system_prompt = """You are a SQL expert that generates precise SQL queries based on user questions.
            
#             You will be provided with:
#             - User's question
#             - Available tables
#             - Complete schema information
            
#             Generate a SQL query that:
#             - Uses correct column names from schema
#             - Properly joins tables if needed
#             - Includes appropriate WHERE clauses
#             - Uses proper aggregation functions when needed
            
#             Respond ONLY with the SQL query. Do not explain."""
            
#             combined_input = f"""
#             User Question: {human_query}
#             Tables: {tables}
#             Schema: {schema}
#             """
            
#             generate_query_prompt = ChatPromptTemplate.from_messages([
#                 ("system", generate_query_system_prompt),
#                 ("human", "{input}")
#             ])
            
#             try:
#                 formatted_prompt = generate_query_prompt.invoke({"input": combined_input})
#                 generate_query_llm = self.llm.with_structured_output(DBQuery)
#                 result = generate_query_llm.invoke(formatted_prompt)
                
#                 print(f"βœ… Query generated: {result.query}")
#                 return {
#                     "messages": [AIMessage(content=f"Query generated: {result.query}")],
#                     "query_gen": result.query,
#                     "next_tool": "sql_agent"
#                 }
#             except Exception as e:
#                 print(f"❌ Failed to generate query: {e}")
#                 return {
#                     "messages": [AIMessage(content="⚠️ Failed to generate SQL query.")],
#                     "query_gen": "",
#                     "next_tool": "sql_agent"
#                 }
            
#     def check_query(self,state: SQLAgentState) -> Dict:
#             """Check if the query is correct"""
#             query = state.get("query_gen", "")
#             print(f"Checking query: {query}")
            
#             if not query:
#                 return {
#                     "messages": [AIMessage(content="No query to check")],
#                     "check_query": "",
#                     "next_tool": "sql_agent"
#                 }
            
#             try:
#                 checked_query = self.query_checker_tool.invoke(query)
#                 ## if checked query contains ``` anywhere remove it 
#                 if "```" in checked_query:
#                     checked_query = checked_query.replace("```", "")
#                 print(f"Query checked: {checked_query}")
#                 return {
#                     "messages": [AIMessage(content=f"Query checked: {checked_query}")],
#                     "check_query": checked_query if checked_query else query,
#                     "next_tool": "sql_agent"
#                 }
#             except Exception as e:
#                 print(f"Error checking query: {e}")
#                 return {
#                     "messages": [AIMessage(content="Query check failed, using original query")],
#                     "check_query": query,
#                     "next_tool": "sql_agent"
#                 }
            
#     def execute_query(self,state: SQLAgentState) -> Dict:
#             """Execute the SQL query"""
#             query = state.get("check_query", "") or state.get("query_gen", "")
#             print(f"Executing query: {query}")
            
#             if not query:
#                 return {
#                     "messages": [AIMessage(content="No query to execute")],
#                     "execute_query": "",
#                     "next_tool": "sql_agent"
#                 }
            
#             try:
#                 results = self.query_tool.invoke(query)
#                 print(f"Query results: {results}")
#                 return {
#                     "messages": [AIMessage(content=f"Query executed successfully: {results}")],
#                     "execute_query": results,
#                     "next_tool": "sql_agent"
#                 }
#             except Exception as e:
#                 print(f"Error executing query: {e}")
#                 return {
#                     "messages": [AIMessage(content=f"Query execution failed: {e}")],
#                     "execute_query": "",
#                     "next_tool": "sql_agent"
#                 }
#     def create_response(self,state: SQLAgentState) -> Dict:
#             """Create a final response for the user"""
#             print("Creating final response...")
            
#             query = state.get("check_query", "") or state.get("query_gen", "")
#             result = state.get("execute_query", "")
#             human_query = state.get("query", "")
            
#             response_prompt = f"""Create a clear, concise response for the user based on:
            
#             User Question: {human_query}
#             SQL Query: {query}
#             Query Result: {result}
            
#             Provide a natural language answer that directly addresses the user's question. Make sure to provide only answer to human question, no any internal process results and explaination, just answer related to the human query."""
            
#             try:
#                 response = self.llm.invoke([HumanMessage(content=response_prompt)])
#                 print(f"Response created: {response.content}")
                
#                 return {
#                     "messages": [response],
#                     "response_to_user": response.content,
#                     "next_tool": "sql_agent",
#                     "task_complete": True
#                 }
#             except Exception as e:
#                 print(f"Error creating response: {e}")
#                 return {
#                     "messages": [AIMessage(content="Failed to create response")],
#                     "response_to_user": "",
#                     "next_tool": "sql_agent",
#                     "task_complete": True
#                 }


## creating database tools 
from langchain_core.tools import tool
from app.schemas.agent_state import SQLAgentState
from typing import Dict
from langchain_core.messages import AIMessage
from langchain_community.agent_toolkits import SQLDatabaseToolkit
from app.schemas.agent_state import DBQuery
from langchain_core.prompts import ChatPromptTemplate

class DatabaseTools:
    def __init__(self,db = None, llm = None):
        self.db = db 
        self.llm = llm
        # self._create_query_tool = self._create_query_tool()
        self.tools = self.get_all_tools()
        try:
                # Initialize toolkit and tools
                self.toolkit = SQLDatabaseToolkit(db=self.db, llm=self.llm)
                self.tools = self.toolkit.get_tools()
                for tool in self.tools:
                    print(f"Initialized tool: {tool.name}")

                # Create instances of the tools
                self.list_tables_tool = next((tool for tool in self.tools if tool.name == "sql_db_list_tables"), None)
                self.query_tool = next((tool for tool in self.tools if tool.name == "sql_db_query"), None)
                self.get_schema_tool = next((tool for tool in self.tools if tool.name == "sql_db_schema"), None)
                self.query_checker_tool = next((tool for tool in self.tools if tool.name == "sql_db_query_checker"), None)
                if not all([self.list_tables_tool, self.query_tool, self.get_schema_tool, self.query_checker_tool]):
                    raise ValueError("Failed to initialize one or more required database tools")

                # # Initialize workflow and compile it into an app
                # self.initialize_workflow()
                
        except Exception as e:
            print(f"Error initializing tools and workflow: {str(e)}")
            raise ValueError(f"Failed to initialize database tools: {str(e)}")
    # @tool
    # def _create_query_tool(self):
    #         """Create the query tool bound to this instance"""
    #         print("creating _create_query_tool")
    #         @tool
    #         def query_to_database(query: str) -> str:
    #             """
    #             Execute a SQL query against the database and return the result.
    #             If the query is invalid or returns no result, an error message will be returned.
    #             In case of an error, the user is advised to rewrite the query and try again.
    #             """
    #             if self.db is None:
    #                 return "Error: Database connection not established. Please set up the connection first."
    #             result = self.db.run_no_throw(query)
    #             if not result:
    #                 return "Error: Query failed. Please rewrite your query and try again."
    #             return result
            
    #         return query_to_database
    def list_tables(self) -> Dict:
            """List all the tables"""
            tables_list = self.list_tables_tool.invoke("")
            print(f"Tables found: {tables_list}")
            return tables_list
    
    def get_schema(self, table_name: list[str]) -> Dict:
            """Get the schema of required tables"""
            print("πŸ“˜ Getting schema...")
            tables_list = self.list_tables_tool.invoke("")
            if any(table not in tables_list for table in table_name):
                 return "Table not exits in database"
            
            tables = [table.strip() for table in tables_list.split(",")]
            required_schema = ""
            
            for table in tables:
                try:
                    schema = self.get_schema_tool.invoke(table)
                    required_schema += f"\nTable: {table}\n{schema}\n"
                except Exception as e:
                    print(f"Error getting schema for {table}: {e}")
            
            return required_schema
    

    def generate_query(self, state: SQLAgentState) -> Dict:
            """Generate a SQL Query according to the user query"""
            schema = state.get("schema_of_table", "")
            human_query = state.get("query", "")
            tables = state.get("tables_list", "")
            
            print(f"Generating query for: {human_query}")
            
            generate_query_system_prompt = """You are a SQL expert that generates precise SQL queries based on user questions.
            
            You will be provided with:
            - User's question
            - Available tables
            - Complete schema information
            
            Generate a SQL query that:
            - Uses correct column names from schema
            - Properly joins tables if needed
            - Includes appropriate WHERE clauses
            - Uses proper aggregation functions when needed
            
            Respond ONLY with the SQL query. Do not explain."""
            
            combined_input = f"""
            User Question: {human_query}
            Tables: {tables}
            Schema: {schema}
            """
            
            generate_query_prompt = ChatPromptTemplate.from_messages([
                ("system", generate_query_system_prompt),
                ("human", "{input}")
            ])
            
            try:
                formatted_prompt = generate_query_prompt.invoke({"input": combined_input})
                generate_query_llm = self.llm.with_structured_output(DBQuery)
                result = generate_query_llm.invoke(formatted_prompt)
                
                print(f"βœ… Query generated: {result.query}")
                return {
                    "messages": [AIMessage(content=f"Query generated: {result.query}")],
                    "query_gen": result.query,
                    "next_tool": "sql_agent"
                }
            except Exception as e:
                print(f"❌ Failed to generate query: {e}")
                return {
                    "messages": [AIMessage(content="⚠️ Failed to generate SQL query.")],
                    "query_gen": "",
                    "next_tool": "sql_agent"
                }
            
    
    def execute_query(self,query: str) -> Dict:
            """Execute the SQL query
            
            Arguments:
            query -- The SQL query to execute

            returns:
            execution results
            """
            
            try:
                results = self.query_tool.invoke(query)
                print(f"Query results: {results}")
                return results
            except Exception as e:
                print(f"Error executing query: {e}")
                return "Query execution failed."
            
    def get_all_tools(self):
         return [self.list_tables, self.get_schema, self.execute_query]