WebashalarForML commited on
Commit
f69d96d
·
verified ·
1 Parent(s): 2a25020

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -89
app.py CHANGED
@@ -51,24 +51,6 @@ toolkit = SQLDatabaseToolkit(db=db, llm=llm)
51
  tools = toolkit.get_tools()
52
 
53
 
54
- def create_agent_app(db_path: str):
55
- # Construct the SQLite URI from the given file path.
56
- db_uri = f"sqlite:///{db_path}"
57
- # Create new SQLDatabase connection using the constructed URI.
58
- from langchain_community.utilities import SQLDatabase
59
- db_instance = SQLDatabase.from_uri(db_uri)
60
-
61
- # Create SQL toolkit and get the tools.
62
- from langchain_community.agent_toolkits import SQLDatabaseToolkit
63
- toolkit_instance = SQLDatabaseToolkit(db=db_instance, llm=llm)
64
- tools_instance = toolkit_instance.get_tools()
65
-
66
- # ... (rest of the logic remains unchanged)
67
- # [Define custom query tool, prompt templates, workflow nodes, etc.]
68
-
69
- # Compile and return the agent application workflow.
70
- return workflow.compile()
71
- # Define a custom query tool for executing SQL queries
72
 
73
  # Define a custom query tool for executing SQL queries
74
  @tool
@@ -137,78 +119,94 @@ DO NOT make any DML statements (INSERT, UPDATE, DELETE, DROP etc.) to the databa
137
  query_gen_prompt = ChatPromptTemplate.from_messages([("system", query_gen_system), ("placeholder", "{messages}")])
138
  query_gen = query_gen_prompt | llm.bind_tools([SubmitFinalAnswer])
139
 
140
- # Define workflow nodes and fallback functions
141
- def first_tool_call(state: State) -> dict[str, list[AIMessage]]:
142
- return {"messages": [AIMessage(content="", tool_calls=[{"name": "sql_db_list_tables", "args": {}, "id": "tool_abcd123"}])]}
143
-
144
- def handle_tool_error(state: State) -> dict:
145
- error = state.get("error")
146
- tool_calls = state["messages"][-1].tool_calls
147
- return {
148
- "messages": [
149
- ToolMessage(content=f"Error: {repr(error)}\n please fix your mistakes.", tool_call_id=tc["id"])
150
- for tc in tool_calls
151
- ]
152
- }
153
-
154
- def create_tool_node_with_fallback(tools_list: list) -> RunnableWithFallbacks[Any, dict]:
155
- return ToolNode(tools_list).with_fallbacks([RunnableLambda(handle_tool_error)], exception_key="error")
156
-
157
- def query_gen_node(state: State):
158
- message = query_gen.invoke(state)
159
- # Check for incorrect tool calls
160
- tool_messages = []
161
- if message.tool_calls:
162
- for tc in message.tool_calls:
163
- if tc["name"] != "SubmitFinalAnswer":
164
- tool_messages.append(
165
- ToolMessage(
166
- content=f"Error: The wrong tool was called: {tc['name']}. Please fix your mistakes. Remember to only call SubmitFinalAnswer to submit the final answer. Generated queries should be outputted WITHOUT a tool call.",
167
- tool_call_id=tc["id"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  )
169
- )
170
- return {"messages": [message] + tool_messages}
171
-
172
- def should_continue(state: State) -> Literal[END, "correct_query", "query_gen"]:
173
- messages = state["messages"]
174
- last_message = messages[-1]
175
- if getattr(last_message, "tool_calls", None):
176
- return END
177
- if last_message.content.startswith("Error:"):
178
- return "query_gen"
179
- else:
180
- return "correct_query"
181
-
182
- def model_check_query(state: State) -> dict[str, list[AIMessage]]:
183
- """Double-check if the query is correct before executing it."""
184
- return {"messages": [query_check.invoke({"messages": [state["messages"][-1]]})]}
185
-
186
- # Get tools for listing tables and fetching schema
187
- list_tables_tool = next((tool for tool in tools_instance if tool.name == "sql_db_list_tables"), None)
188
- get_schema_tool = next((tool for tool in tools_instance if tool.name == "sql_db_schema"), None)
189
-
190
- # Define the workflow (state graph)
191
- workflow = StateGraph(State)
192
- workflow.add_node("first_tool_call", first_tool_call)
193
- workflow.add_node("list_tables_tool", create_tool_node_with_fallback([list_tables_tool]))
194
- workflow.add_node("get_schema_tool", create_tool_node_with_fallback([get_schema_tool]))
195
- model_get_schema = llm.bind_tools([get_schema_tool])
196
- workflow.add_node("model_get_schema", lambda state: {"messages": [model_get_schema.invoke(state["messages"])],})
197
- workflow.add_node("query_gen", query_gen_node)
198
- workflow.add_node("correct_query", model_check_query)
199
- workflow.add_node("execute_query", create_tool_node_with_fallback([db_query_tool]))
200
-
201
- workflow.add_edge(START, "first_tool_call")
202
- workflow.add_edge("first_tool_call", "list_tables_tool")
203
- workflow.add_edge("list_tables_tool", "model_get_schema")
204
- workflow.add_edge("model_get_schema", "get_schema_tool")
205
- workflow.add_edge("get_schema_tool", "query_gen")
206
- workflow.add_conditional_edges("query_gen", should_continue)
207
- workflow.add_edge("correct_query", "execute_query")
208
- workflow.add_edge("execute_query", "query_gen")
209
-
210
- # Compile and return the agent application workflow
211
- return workflow.compile()
212
 
213
  ###############################################################################
214
  # Application Factory: create_app()
 
51
  tools = toolkit.get_tools()
52
 
53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
  # Define a custom query tool for executing SQL queries
56
  @tool
 
119
  query_gen_prompt = ChatPromptTemplate.from_messages([("system", query_gen_system), ("placeholder", "{messages}")])
120
  query_gen = query_gen_prompt | llm.bind_tools([SubmitFinalAnswer])
121
 
122
+
123
+ def create_agent_app(db_path: str):
124
+ # Construct the SQLite URI from the given file path.
125
+ db_uri = f"sqlite:///{db_path}"
126
+ # Create new SQLDatabase connection using the constructed URI.
127
+ from langchain_community.utilities import SQLDatabase
128
+ db_instance = SQLDatabase.from_uri(db_uri)
129
+
130
+ # Create SQL toolkit and get the tools.
131
+ from langchain_community.agent_toolkits import SQLDatabaseToolkit
132
+ toolkit_instance = SQLDatabaseToolkit(db=db_instance, llm=llm)
133
+ tools_instance = toolkit_instance.get_tools()
134
+
135
+ # ... (rest of the logic remains unchanged)
136
+ # Define a custom query tool for executing SQL queries
137
+
138
+ # Define workflow nodes and fallback functions
139
+ def first_tool_call(state: State) -> dict[str, list[AIMessage]]:
140
+ return {"messages": [AIMessage(content="", tool_calls=[{"name": "sql_db_list_tables", "args": {}, "id": "tool_abcd123"}])]}
141
+
142
+ def handle_tool_error(state: State) -> dict:
143
+ error = state.get("error")
144
+ tool_calls = state["messages"][-1].tool_calls
145
+ return {
146
+ "messages": [
147
+ ToolMessage(content=f"Error: {repr(error)}\n please fix your mistakes.", tool_call_id=tc["id"])
148
+ for tc in tool_calls
149
+ ]
150
+ }
151
+
152
+ def create_tool_node_with_fallback(tools_list: list) -> RunnableWithFallbacks[Any, dict]:
153
+ return ToolNode(tools_list).with_fallbacks([RunnableLambda(handle_tool_error)], exception_key="error")
154
+
155
+ def query_gen_node(state: State):
156
+ message = query_gen.invoke(state)
157
+ # Check for incorrect tool calls
158
+ tool_messages = []
159
+ if message.tool_calls:
160
+ for tc in message.tool_calls:
161
+ if tc["name"] != "SubmitFinalAnswer":
162
+ tool_messages.append(
163
+ ToolMessage(
164
+ content=f"Error: The wrong tool was called: {tc['name']}. Please fix your mistakes. Remember to only call SubmitFinalAnswer to submit the final answer. Generated queries should be outputted WITHOUT a tool call.",
165
+ tool_call_id=tc["id"],
166
+ )
167
  )
168
+ return {"messages": [message] + tool_messages}
169
+
170
+ def should_continue(state: State) -> Literal[END, "correct_query", "query_gen"]:
171
+ messages = state["messages"]
172
+ last_message = messages[-1]
173
+ if getattr(last_message, "tool_calls", None):
174
+ return END
175
+ if last_message.content.startswith("Error:"):
176
+ return "query_gen"
177
+ else:
178
+ return "correct_query"
179
+
180
+ def model_check_query(state: State) -> dict[str, list[AIMessage]]:
181
+ """Double-check if the query is correct before executing it."""
182
+ return {"messages": [query_check.invoke({"messages": [state["messages"][-1]]})]}
183
+
184
+ # Get tools for listing tables and fetching schema
185
+ list_tables_tool = next((tool for tool in tools_instance if tool.name == "sql_db_list_tables"), None)
186
+ get_schema_tool = next((tool for tool in tools_instance if tool.name == "sql_db_schema"), None)
187
+
188
+ # Define the workflow (state graph)
189
+ workflow = StateGraph(State)
190
+ workflow.add_node("first_tool_call", first_tool_call)
191
+ workflow.add_node("list_tables_tool", create_tool_node_with_fallback([list_tables_tool]))
192
+ workflow.add_node("get_schema_tool", create_tool_node_with_fallback([get_schema_tool]))
193
+ model_get_schema = llm.bind_tools([get_schema_tool])
194
+ workflow.add_node("model_get_schema", lambda state: {"messages": [model_get_schema.invoke(state["messages"])],})
195
+ workflow.add_node("query_gen", query_gen_node)
196
+ workflow.add_node("correct_query", model_check_query)
197
+ workflow.add_node("execute_query", create_tool_node_with_fallback([db_query_tool]))
198
+
199
+ workflow.add_edge(START, "first_tool_call")
200
+ workflow.add_edge("first_tool_call", "list_tables_tool")
201
+ workflow.add_edge("list_tables_tool", "model_get_schema")
202
+ workflow.add_edge("model_get_schema", "get_schema_tool")
203
+ workflow.add_edge("get_schema_tool", "query_gen")
204
+ workflow.add_conditional_edges("query_gen", should_continue)
205
+ workflow.add_edge("correct_query", "execute_query")
206
+ workflow.add_edge("execute_query", "query_gen")
207
+
208
+ # Compile and return the agent application workflow.
209
+ return workflow.compile()
 
210
 
211
  ###############################################################################
212
  # Application Factory: create_app()