Kshitijk20 commited on
Commit
34a5262
·
1 Parent(s): b7755d4

added modular code

Browse files
app/agents/__inti__.py ADDED
File without changes
app/agents/sql_agent.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from langchain_community.utilities import SQLDatabase
3
+ from langchain_groq import ChatGroq
4
+ from langgraph.graph import StateGraph, END, START
5
+ from langchain_core.messages import AIMessage, ToolMessage, AnyMessage, HumanMessage
6
+ from langgraph.graph.message import AnyMessage, add_messages
7
+ from langchain_core.tools import tool
8
+ from typing import Annotated, Literal, TypedDict, Any
9
+ from pydantic import BaseModel, Field
10
+ from langchain_core.runnables import RunnableLambda, RunnableWithFallbacks
11
+ from langgraph.prebuilt import ToolNode
12
+ from langchain_core.prompts import ChatPromptTemplate
13
+ from langchain_community.agent_toolkits import SQLDatabaseToolkit
14
+ from dotenv import load_dotenv
15
+ import os
16
+ from IPython.display import display
17
+ import PIL
18
+ from langgraph.errors import GraphRecursionError
19
+ import os
20
+ import io
21
+ from typing import Annotated, Any, TypedDict
22
+ from langgraph.graph import StateGraph, END, MessagesState
23
+
24
+ from IPython.display import Image, display
25
+ from langchain_core.runnables.graph import MermaidDrawMethod
26
+ from typing import Optional, Dict
27
+
28
+ from langchain_community.utilities import SQLDatabase
29
+ from langchain_community.agent_toolkits import SQLDatabaseToolkit
30
+ from langchain_groq import ChatGroq
31
+ from langchain_core.messages import HumanMessage, AIMessage
32
+ from langchain_core.prompts import ChatPromptTemplate
33
+ # from langchain_core.pydantic_v1 import BaseModel, Field
34
+ from langgraph.graph import StateGraph, END, MessagesState
35
+ from typing import TypedDict, Annotated, List, Literal, Dict, Any
36
+ from langchain_google_genai import ChatGoogleGenerativeAI
37
+ from app.schemas.agent_state import DBQuery, SQLAgentState
38
+ from app.tools.database_tools import DatabaseTools
39
+ from app.utils.database_connection import DatabaseConnection
40
+ from dotenv import load_dotenv
41
+ load_dotenv()
42
+ import os
43
+ os.environ["GROQ_API_KEY"]=os.getenv("GROQ_API_KEY")
44
+ os.environ["GEMINI_API_KEY"]=os.getenv("GEMINI_API_KEY")
45
+
46
+
47
+ class SQLAgent:
48
+ def __init__(self):
49
+
50
+ # Initialize instance variables
51
+ self.db = None
52
+ self.toolkit = None
53
+ self.tools = None
54
+ self.list_tables_tool = None
55
+ self.sql_db_query = None
56
+ self.get_schema_tool = None
57
+ self.app = None
58
+
59
+ # Setting up LLM
60
+ # self.llm = ChatGroq(model=model,api_key = os.getenv("GROQ_API_KEY"))
61
+ self.llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash-lite", google_api_key=os.environ["GEMINI_API_KEY"])
62
+ # Register the tool method
63
+ # self.query_to_database = self._create_query_tool()
64
+
65
+
66
+
67
+ def setup_database_connection(self, connection_string: str):
68
+ """Set up database connection and initialize tools"""
69
+ try:
70
+ # Initialize database connection
71
+ # self.db = SQLDatabase.from_uri(connection_string)
72
+ # print("Database connection successful!")
73
+ self.db = DatabaseConnection(connection_string).db
74
+ print("Database connection successful!")
75
+ # Initialize toolkit and tools class
76
+ self.db_tools = DatabaseTools(db=self.db, llm=self.llm)
77
+
78
+ try:
79
+ self.initialize_workflow()
80
+
81
+ return self.db
82
+
83
+ except Exception as e:
84
+ print(f"Error initializing tools and workflow: {str(e)}")
85
+ raise ValueError(f"Failed to initialize database tools: {str(e)}")
86
+
87
+ except ImportError as e:
88
+ print(f"Database driver import error: {str(e)}")
89
+ raise ValueError(f"Missing database driver or invalid database type: {str(e)}")
90
+ except ValueError as e:
91
+ print(f"Invalid connection string or configuration: {str(e)}")
92
+ raise
93
+ except Exception as e:
94
+ print(f"Unexpected error during database connection: {str(e)}")
95
+ raise ValueError(f"Failed to establish database connection: {str(e)}")
96
+
97
+ def initialize_workflow(self):
98
+ """Initialize the workflow graph"""
99
+
100
+ print("Intializing Workflow....")
101
+
102
+ def creating_sql_agent_chain():
103
+ """Creating a sql agent chain"""
104
+
105
+ print("Creating a sql agent chain")
106
+ sql_agent_prompt = ChatPromptTemplate.from_messages([
107
+ ("system", """You are a supervisor SQL agent managing tools to get the answer to the user's query.
108
+
109
+ Based on the current state, decide which tool should be called next:
110
+ 1. list_table_tools - List all tables from the database
111
+ 2. get_schema - Get the schema of required tables
112
+ 3. generate_query - Generate a SQL query
113
+ 4. check_query - Check if the query is correct
114
+ 5. execute_query - Execute the query
115
+ 6. response - Create response for the user
116
+
117
+ Current state:
118
+ - Tables listed: {tables_list}
119
+ - Schema retrieved: {schema_of_table}
120
+ - Query generated: {query_gen}
121
+ - Query checked: {check_query}
122
+ - Query executed: {execute_query}
123
+ - Response created: {response_to_user}
124
+
125
+ If no tables are listed, respond with 'list_table_tools'.
126
+ If tables are listed but no schema, respond with 'get_schema'.
127
+ If schema exists but no query generated, respond with 'generate_query'.
128
+ If query generated but not checked, respond with 'check_query'.
129
+ If query checked but not executed, respond with 'execute_query'.
130
+ If query executed but no response, respond with 'response'.
131
+ If everything is complete, respond with 'DONE'.
132
+
133
+ Respond with ONLY the tool name or 'DONE'.
134
+ """),
135
+ ("human", "{task}")
136
+ ])
137
+ return sql_agent_prompt | self.llm
138
+
139
+ def sql_agent(state: SQLAgentState) -> Dict:
140
+ """Agent decides which tool to call next"""
141
+ messages = state["messages"]
142
+ task = messages[-1].content if messages else "No task"
143
+
144
+ # Store the original query in state if not already stored
145
+ if not state.get("query"):
146
+ state["query"] = task
147
+
148
+ # Check what's been completed (convert to boolean properly)
149
+ tables_list = bool(state.get("tables_list", "").strip())
150
+ schema_of_table = bool(state.get("schema_of_table", "").strip())
151
+ query_gen = bool(state.get("query_gen", "").strip())
152
+ check_query = bool(state.get("check_query", "").strip())
153
+ execute_query = bool(state.get("execute_query", "").strip())
154
+ response_to_user = bool(state.get("response_to_user", "").strip())
155
+
156
+ print(f"State check - Tables: {tables_list}, Schema: {schema_of_table}, Query: {query_gen}, Check: {check_query}, Execute: {execute_query}, Response: {response_to_user}")
157
+
158
+ chain = creating_sql_agent_chain()
159
+ decision = chain.invoke({
160
+ "task": task,
161
+ "tables_list": tables_list,
162
+ "schema_of_table": schema_of_table,
163
+ "query_gen": query_gen,
164
+ "check_query": check_query,
165
+ "execute_query": execute_query,
166
+ "response_to_user": response_to_user
167
+ })
168
+ decision_text = decision.content.strip().lower()
169
+ print(f"Agent decision: {decision_text}")
170
+
171
+ if "done" in decision_text:
172
+ next_tool = "end"
173
+ agent_msg = "✅ SQL Agent: All tasks complete!"
174
+ elif "list_table_tools" in decision_text:
175
+ next_tool = "list_table_tools"
176
+ agent_msg = "📋 SQL Agent: Listing all tables in database."
177
+ elif "get_schema" in decision_text:
178
+ next_tool = "get_schema"
179
+ agent_msg = "📋 SQL Agent: Getting schema of tables."
180
+ elif "generate_query" in decision_text:
181
+ next_tool = "generate_query"
182
+ agent_msg = "📋 SQL Agent: Generating SQL query."
183
+ elif "check_query" in decision_text:
184
+ next_tool = "check_query"
185
+ agent_msg = "📋 SQL Agent: Checking SQL query."
186
+ elif "execute_query" in decision_text:
187
+ next_tool = "execute_query"
188
+ agent_msg = "📋 SQL Agent: Executing query."
189
+ elif "response" in decision_text:
190
+ next_tool = "response"
191
+ agent_msg = "📋 SQL Agent: Creating response."
192
+ else:
193
+ next_tool = "end"
194
+ agent_msg = "✅ SQL Agent: Task complete."
195
+
196
+ return {
197
+ "messages": [AIMessage(content=agent_msg)],
198
+ "next_tool": next_tool,
199
+ "current_task": task
200
+ }
201
+
202
+ def router(state: SQLAgentState):
203
+ """Route to the next node"""
204
+ print("🔁 Entering router...")
205
+ next_tool = state.get("next_tool", "")
206
+ print(f"➡️ Next tool: {next_tool}")
207
+
208
+ if next_tool == "end" or state.get("task_complete", False):
209
+ return END
210
+
211
+ valid_tools = [
212
+ "sql_agent", "list_table_tools", "get_schema", "generate_query",
213
+ "check_query", "execute_query", "response"
214
+ ]
215
+
216
+ return next_tool if next_tool in valid_tools else "sql_agent"
217
+
218
+ # Create workflow
219
+ workflow = StateGraph(SQLAgentState)
220
+
221
+ # Add nodes
222
+ workflow.add_node("sql_agent", sql_agent)
223
+ workflow.add_node("list_table_tools", self.db_tools.list_table_tools)
224
+ workflow.add_node("get_schema", self.db_tools.get_schema)
225
+ workflow.add_node("generate_query", self.db_tools.generate_query)
226
+ workflow.add_node("check_query", self.db_tools.check_query)
227
+ workflow.add_node("execute_query", self.db_tools.execute_query)
228
+ workflow.add_node("response", self.db_tools.create_response)
229
+
230
+ # Set entry point
231
+ workflow.set_entry_point("sql_agent")
232
+
233
+ # Add routing
234
+ for node in ["sql_agent", "list_table_tools", "get_schema", "generate_query", "check_query", "execute_query", "response"]:
235
+ workflow.add_conditional_edges(
236
+ node,
237
+ router,
238
+ {
239
+ "sql_agent": "sql_agent",
240
+ "list_table_tools": "list_table_tools",
241
+ "get_schema": "get_schema",
242
+ "generate_query": "generate_query",
243
+ "check_query": "check_query",
244
+ "execute_query": "execute_query",
245
+ "response": "response",
246
+ END: END
247
+ }
248
+ )
249
+
250
+ # Compile the graph
251
+ self.app = workflow.compile()
252
+ # self.app.get_graph().draw_mermaid_png(output_file_path="sql_agent_workflow.png", draw_method=MermaidDrawMethod.API)
253
+
254
+
255
+
256
+ def is_query_relevant(self, query: str) -> bool:
257
+ """Check if the query is relevant to the database using the LLM."""
258
+
259
+ # Retrieve the schema of the relevant tables
260
+ if self.db_tools.list_tables_tool:
261
+ relevant_tables = self.db_tools.list_tables_tool.invoke("")
262
+ # print(relevant_tables)
263
+ table_list= relevant_tables.split(", ")
264
+ print(table_list)
265
+ # print(agent.get_schema_tool.invoke(table_list[0]))
266
+ schema = ""
267
+ for table in table_list:
268
+ schema+= self.db_tools.get_schema_tool.invoke(table)
269
+
270
+ print(schema)
271
+
272
+ # if self.get_schema_tool:
273
+ # schema_response = self.get_schema_tool.invoke({})
274
+ # table_schema = schema_response.content # Assuming this returns the schema as a string
275
+
276
+ relevance_check_prompt = (
277
+ """You are an expert SQL agent which takes user query in Natural language and find out it have releavnce with the given schema or not. Please determine if the following query is related to a database.Here is the schema of the tables present in database:\n{schema}\n\n. If the query related to given schema respond with 'yes'. Here is the query: {query}. Answer with only 'yes' or 'no'."""
278
+ ).format(schema=relevant_tables, query=query)
279
+
280
+ response = self.llm.invoke([{"role": "user", "content": relevance_check_prompt}])
281
+
282
+ # Assuming the LLM returns a simple 'yes' or 'no'
283
+ return response.content == "yes"
284
+
285
+ ## called from the fastapi endpoint
286
+ def execute_query(self, query: str):
287
+ """Execute a query through the workflow"""
288
+ if self.db is None:
289
+ raise ValueError("Database connection not established. Please set up the connection first.")
290
+ if self.app is None:
291
+ raise ValueError("Workflow not initialized. Please set up the connection first.")
292
+ # First, handle simple queries like "list tables" directly
293
+ query_lower = query.lower()
294
+ if any(phrase in query_lower for phrase in ["list all the tables", "show tables", "name of tables",
295
+ "which tables are present", "how many tables", "list all tables"]):
296
+ if self.db_tools.list_tables_tool:
297
+ tables = self.db_tools.list_tables_tool.invoke("")
298
+ return f"The tables in the database are: {tables}"
299
+ else:
300
+ return "Error: Unable to list tables. The list_tables_tool is not initialized."
301
+
302
+ # Check if the query is relevant to the database
303
+ if not self.is_query_relevant(query):
304
+ print("Not relevent to database.")
305
+ # If not relevant, let the LLM answer the question directly
306
+ non_relevant_prompt = (
307
+ """You are an expert SQL agent created by Kshitij Kumrawat. You can only assist with questions related to databases so repond the user with the following example resonse and Do not answer any questions that are not related to databases.:
308
+ Please ask a question that pertains to database operations, such as querying tables, retrieving data, or understanding the database schema. """
309
+ )
310
+
311
+ # Invoke the LLM with the non-relevant prompt
312
+ response = self.llm.invoke([{"role": "user", "content": non_relevant_prompt}])
313
+ # print(response.content)
314
+ return response.content
315
+
316
+ # If relevant, proceed with the SQL workflow
317
+ # response = self.app.invoke({"messages": [HumanMessage(content=query, role="user")]})
318
+ response = self.app.invoke({
319
+ "messages": [HumanMessage(content=query)],
320
+ "query": query
321
+ })
322
+
323
+ return response["messages"][-1].content
324
+
325
+ # # More robust final answer extraction
326
+ # if (
327
+ # response
328
+ # and response["messages"]
329
+ # and response["messages"][-1].tool_calls
330
+ # and len(response["messages"][-1].tool_calls) > 0
331
+ # and "args" in response["messages"][-1].tool_calls[0]
332
+ # and "final_answer" in response["messages"][-1].tool_calls[0]["args"]
333
+ # ):
334
+ # return response["messages"][-1].tool_calls[0]["args"]["final_answer"]
335
+ # else:
336
+ # return "Error: Could not extract final answer."
337
+
app/schemas/__init__.py ADDED
File without changes
app/schemas/agent_state.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel, Field
2
+ from langgraph.graph import MessagesState
3
+
4
+ class SQLAgentState(MessagesState):
5
+ """State for the agent"""
6
+ next_tool : str = ""
7
+ tables_list: str = ""
8
+ schema_of_table: str = ""
9
+ query_gen : str= ""
10
+ check_query: str = ""
11
+ execute_query : str = ""
12
+ task_complete: bool = False
13
+ response_to_user: str= ""
14
+ current_task: str = ""
15
+ query: str = "" ## query of the human stored in it
16
+
17
+ class DBQuery(BaseModel):
18
+ query: str = Field(..., description="The SQL query to execute")
app/services/sql_agent_instance.py CHANGED
@@ -3,7 +3,7 @@ SQLAgent singleton instance module.
3
  This creates and maintains a single instance of the SQLAgent class
4
  that can be imported and used throughout the application.
5
  """
6
- from app.services.sql_agent import SQLAgent
7
-
8
  # Create a singleton instance
9
  sql_agent = SQLAgent()
 
3
  This creates and maintains a single instance of the SQLAgent class
4
  that can be imported and used throughout the application.
5
  """
6
+ # from app.services.sql_agent import SQLAgent
7
+ from app.agents.sql_agent import SQLAgent
8
  # Create a singleton instance
9
  sql_agent = SQLAgent()
app/services/{sql_agent.py → sql_agent_old.py} RENAMED
File without changes
app/tools/__init__.py ADDED
File without changes
app/tools/database_tools.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## creating database tools
2
+ from langchain_core.tools import tool
3
+ from app.schemas.agent_state import SQLAgentState
4
+ from typing import Dict
5
+ from langchain_core.messages import AIMessage, HumanMessage
6
+ from app.utils.database_connection import DatabaseConnection
7
+ from langchain_community.agent_toolkits import SQLDatabaseToolkit
8
+ from app.schemas.agent_state import DBQuery
9
+ from langchain_core.prompts import ChatPromptTemplate
10
+
11
+ class DatabaseTools:
12
+ def __init__(self,db = None, llm = None):
13
+ self.db = db
14
+ self.llm = llm
15
+ self._create_query_tool = self._create_query_tool()
16
+ try:
17
+ # Initialize toolkit and tools
18
+ self.toolkit = SQLDatabaseToolkit(db=self.db, llm=self.llm)
19
+ self.tools = self.toolkit.get_tools()
20
+ for tool in self.tools:
21
+ print(f"Initialized tool: {tool.name}")
22
+
23
+ # Create instances of the tools
24
+ self.list_tables_tool = next((tool for tool in self.tools if tool.name == "sql_db_list_tables"), None)
25
+ self.query_tool = next((tool for tool in self.tools if tool.name == "sql_db_query"), None)
26
+ self.get_schema_tool = next((tool for tool in self.tools if tool.name == "sql_db_schema"), None)
27
+ self.query_checker_tool = next((tool for tool in self.tools if tool.name == "sql_db_query_checker"), None)
28
+ if not all([self.list_tables_tool, self.query_tool, self.get_schema_tool, self.query_checker_tool]):
29
+ raise ValueError("Failed to initialize one or more required database tools")
30
+
31
+ # # Initialize workflow and compile it into an app
32
+ # self.initialize_workflow()
33
+
34
+ except Exception as e:
35
+ print(f"Error initializing tools and workflow: {str(e)}")
36
+ raise ValueError(f"Failed to initialize database tools: {str(e)}")
37
+
38
+ def _create_query_tool(self):
39
+ """Create the query tool bound to this instance"""
40
+ print("creating _create_query_tool")
41
+ @tool
42
+ def query_to_database(query: str) -> str:
43
+ """
44
+ Execute a SQL query against the database and return the result.
45
+ If the query is invalid or returns no result, an error message will be returned.
46
+ In case of an error, the user is advised to rewrite the query and try again.
47
+ """
48
+ if self.db is None:
49
+ return "Error: Database connection not established. Please set up the connection first."
50
+ result = self.db.run_no_throw(query)
51
+ if not result:
52
+ return "Error: Query failed. Please rewrite your query and try again."
53
+ return result
54
+
55
+ return query_to_database
56
+
57
+ def list_table_tools(self, state: SQLAgentState = None) -> Dict:
58
+ """List all the tables"""
59
+ tables_list = self.list_tables_tool.invoke("")
60
+ print(f"Tables found: {tables_list}")
61
+ return {
62
+ "messages": [AIMessage(content=f"Tables found: {tables_list}")],
63
+ "tables_list": tables_list,
64
+ "next_tool": "sql_agent"
65
+ }
66
+
67
+ def get_schema(self,state: SQLAgentState) -> Dict:
68
+ """Get the schema of required tables"""
69
+ print("📘 Getting schema...")
70
+ tables_list = state.get("tables_list", "")
71
+ if not tables_list:
72
+ tables_list = self.list_tables_tool.invoke("")
73
+
74
+ tables = [table.strip() for table in tables_list.split(",")]
75
+ full_schema = ""
76
+
77
+ for table in tables:
78
+ try:
79
+ schema = self.get_schema_tool.invoke(table)
80
+ full_schema += f"\nTable: {table}\n{schema}\n"
81
+ except Exception as e:
82
+ print(f"Error getting schema for {table}: {e}")
83
+
84
+ print(f"📘 Schema collected for tables: {tables}")
85
+ return {
86
+ "messages": [AIMessage(content=f"Schema retrieved: {full_schema}")],
87
+ "schema_of_table": full_schema,
88
+ "tables_list": tables_list,
89
+ "next_tool": "sql_agent"
90
+ }
91
+ def generate_query(self, state: SQLAgentState) -> Dict:
92
+ """Generate a SQL Query according to the user query"""
93
+ schema = state.get("schema_of_table", "")
94
+ human_query = state.get("query", "")
95
+ tables = state.get("tables_list", "")
96
+
97
+ print(f"Generating query for: {human_query}")
98
+
99
+ generate_query_system_prompt = """You are a SQL expert that generates precise SQL queries based on user questions.
100
+
101
+ You will be provided with:
102
+ - User's question
103
+ - Available tables
104
+ - Complete schema information
105
+
106
+ Generate a SQL query that:
107
+ - Uses correct column names from schema
108
+ - Properly joins tables if needed
109
+ - Includes appropriate WHERE clauses
110
+ - Uses proper aggregation functions when needed
111
+
112
+ Respond ONLY with the SQL query. Do not explain."""
113
+
114
+ combined_input = f"""
115
+ User Question: {human_query}
116
+ Tables: {tables}
117
+ Schema: {schema}
118
+ """
119
+
120
+ generate_query_prompt = ChatPromptTemplate.from_messages([
121
+ ("system", generate_query_system_prompt),
122
+ ("human", "{input}")
123
+ ])
124
+
125
+ try:
126
+ formatted_prompt = generate_query_prompt.invoke({"input": combined_input})
127
+ generate_query_llm = self.llm.with_structured_output(DBQuery)
128
+ result = generate_query_llm.invoke(formatted_prompt)
129
+
130
+ print(f"✅ Query generated: {result.query}")
131
+ return {
132
+ "messages": [AIMessage(content=f"Query generated: {result.query}")],
133
+ "query_gen": result.query,
134
+ "next_tool": "sql_agent"
135
+ }
136
+ except Exception as e:
137
+ print(f"❌ Failed to generate query: {e}")
138
+ return {
139
+ "messages": [AIMessage(content="⚠️ Failed to generate SQL query.")],
140
+ "query_gen": "",
141
+ "next_tool": "sql_agent"
142
+ }
143
+
144
+ def check_query(self,state: SQLAgentState) -> Dict:
145
+ """Check if the query is correct"""
146
+ query = state.get("query_gen", "")
147
+ print(f"Checking query: {query}")
148
+
149
+ if not query:
150
+ return {
151
+ "messages": [AIMessage(content="No query to check")],
152
+ "check_query": "",
153
+ "next_tool": "sql_agent"
154
+ }
155
+
156
+ try:
157
+ checked_query = self.query_checker_tool.invoke(query)
158
+ ## if checked query contains ``` anywhere remove it
159
+ if "```" in checked_query:
160
+ checked_query = checked_query.replace("```", "")
161
+ print(f"Query checked: {checked_query}")
162
+ return {
163
+ "messages": [AIMessage(content=f"Query checked: {checked_query}")],
164
+ "check_query": checked_query if checked_query else query,
165
+ "next_tool": "sql_agent"
166
+ }
167
+ except Exception as e:
168
+ print(f"Error checking query: {e}")
169
+ return {
170
+ "messages": [AIMessage(content="Query check failed, using original query")],
171
+ "check_query": query,
172
+ "next_tool": "sql_agent"
173
+ }
174
+
175
+ def execute_query(self,state: SQLAgentState) -> Dict:
176
+ """Execute the SQL query"""
177
+ query = state.get("check_query", "") or state.get("query_gen", "")
178
+ print(f"Executing query: {query}")
179
+
180
+ if not query:
181
+ return {
182
+ "messages": [AIMessage(content="No query to execute")],
183
+ "execute_query": "",
184
+ "next_tool": "sql_agent"
185
+ }
186
+
187
+ try:
188
+ results = self.query_tool.invoke(query)
189
+ print(f"Query results: {results}")
190
+ return {
191
+ "messages": [AIMessage(content=f"Query executed successfully: {results}")],
192
+ "execute_query": results,
193
+ "next_tool": "sql_agent"
194
+ }
195
+ except Exception as e:
196
+ print(f"Error executing query: {e}")
197
+ return {
198
+ "messages": [AIMessage(content=f"Query execution failed: {e}")],
199
+ "execute_query": "",
200
+ "next_tool": "sql_agent"
201
+ }
202
+ def create_response(self,state: SQLAgentState) -> Dict:
203
+ """Create a final response for the user"""
204
+ print("Creating final response...")
205
+
206
+ query = state.get("check_query", "") or state.get("query_gen", "")
207
+ result = state.get("execute_query", "")
208
+ human_query = state.get("query", "")
209
+
210
+ response_prompt = f"""Create a clear, concise response for the user based on:
211
+
212
+ User Question: {human_query}
213
+ SQL Query: {query}
214
+ Query Result: {result}
215
+
216
+ 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."""
217
+
218
+ try:
219
+ response = self.llm.invoke([HumanMessage(content=response_prompt)])
220
+ print(f"Response created: {response.content}")
221
+
222
+ return {
223
+ "messages": [response],
224
+ "response_to_user": response.content,
225
+ "next_tool": "sql_agent",
226
+ "task_complete": True
227
+ }
228
+ except Exception as e:
229
+ print(f"Error creating response: {e}")
230
+ return {
231
+ "messages": [AIMessage(content="Failed to create response")],
232
+ "response_to_user": "",
233
+ "next_tool": "sql_agent",
234
+ "task_complete": True
235
+ }
app/utils/__init__.py ADDED
File without changes
app/utils/database_connection.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_community.utilities import SQLDatabase
2
+ from langchain_community.agent_toolkits import SQLDatabaseToolkit
3
+
4
+
5
+ class DatabaseConnection:
6
+ def __init__(self,connection_string: str):
7
+ self.db = None
8
+ self.setup_database_connection(connection_string)
9
+
10
+ def setup_database_connection(self, connection_string: str):
11
+ """Set up database connection and initialize tools"""
12
+ try:
13
+ # Initialize database connection
14
+ self.db = SQLDatabase.from_uri(connection_string)
15
+ print("Database connection successful!")
16
+
17
+ return self.db
18
+
19
+ except ImportError as e:
20
+ print(f"Database driver import error: {str(e)}")
21
+ raise ValueError(f"Missing database driver or invalid database type: {str(e)}")
22
+ except ValueError as e:
23
+ print(f"Invalid connection string or configuration: {str(e)}")
24
+ raise
25
+ except Exception as e:
26
+ print(f"Unexpected error during database connection: {str(e)}")
27
+ raise ValueError(f"Failed to establish database connection: {str(e)}")