Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -39,8 +39,6 @@ load_dotenv()
|
|
39 |
UPLOAD_FOLDER = os.path.join(os.getcwd(), "uploads")
|
40 |
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
41 |
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
|
42 |
-
DATABASE_URI = f"sqlite:///{os.path.join(BASE_DIR, 'data', 'mydb.db')}"
|
43 |
-
print("DATABASE URI:", DATABASE_URI)
|
44 |
|
45 |
# API Keys from .env file
|
46 |
os.environ["GROQ_API_KEY"] = os.getenv("GROQ_API_KEY")
|
@@ -130,12 +128,9 @@ def create_agent_app(db_path: str):
|
|
130 |
query_gen = query_gen_prompt | llm.bind_tools([SubmitFinalAnswer])
|
131 |
|
132 |
# -------------------------------------------------------------------------
|
133 |
-
#
|
134 |
# -------------------------------------------------------------------------
|
135 |
-
|
136 |
-
global DATABASE_URI
|
137 |
-
DATABASE_URI = abs_db_path_local
|
138 |
-
db_uri = f"sqlite:///{abs_db_path_local}"
|
139 |
print("db_uri", db_uri)
|
140 |
|
141 |
try:
|
@@ -248,16 +243,33 @@ def create_app():
|
|
248 |
try:
|
249 |
if agent_app is None:
|
250 |
socketio.emit("log", {"message": "[INFO]: Initializing agent for the first time..."})
|
251 |
-
|
252 |
-
|
253 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
254 |
query = {"messages": [("user", prompt)]}
|
255 |
result = agent_app.invoke(query)
|
256 |
try:
|
257 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
258 |
except Exception as e:
|
259 |
-
result = "
|
260 |
-
flash("
|
|
|
261 |
print("final_answer------>", result)
|
262 |
socketio.emit("final", {"message": result})
|
263 |
except Exception as e:
|
@@ -289,6 +301,14 @@ def create_app():
|
|
289 |
flash(error_message, "error")
|
290 |
return "ERROR", 500
|
291 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
292 |
@flask_app.route("/upload", methods=["GET", "POST"])
|
293 |
def upload():
|
294 |
global abs_file_path, agent_app, db_path
|
@@ -303,12 +323,20 @@ def create_app():
|
|
303 |
db_path = os.path.join(flask_app.config['UPLOAD_FOLDER'], "uploaded.db")
|
304 |
print("Saving file to:", db_path)
|
305 |
file.save(db_path)
|
|
|
|
|
|
|
|
|
|
|
306 |
abs_file_path = os.path.abspath(db_path)
|
307 |
-
agent_app = None # Reset the agent to be lazily reinitialized on next query.
|
308 |
print(f"[INFO]: File '{filename}' uploaded. Agent will be initialized on first query.")
|
309 |
socketio.emit("log", {"message": f"[INFO]: Database file '{filename}' uploaded."})
|
310 |
flash(f"Database file '{filename}' uploaded successfully.", "info")
|
|
|
311 |
return redirect(url_for("index"))
|
|
|
|
|
|
|
312 |
return render_template("upload.html")
|
313 |
except Exception as e:
|
314 |
error_message = f"[ERROR]: {str(e)}"
|
|
|
39 |
UPLOAD_FOLDER = os.path.join(os.getcwd(), "uploads")
|
40 |
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
41 |
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
|
|
|
|
|
42 |
|
43 |
# API Keys from .env file
|
44 |
os.environ["GROQ_API_KEY"] = os.getenv("GROQ_API_KEY")
|
|
|
128 |
query_gen = query_gen_prompt | llm.bind_tools([SubmitFinalAnswer])
|
129 |
|
130 |
# -------------------------------------------------------------------------
|
131 |
+
# Create SQLDatabase connection.
|
132 |
# -------------------------------------------------------------------------
|
133 |
+
db_uri = f"sqlite:///{os.path.abspath(db_path)}"
|
|
|
|
|
|
|
134 |
print("db_uri", db_uri)
|
135 |
|
136 |
try:
|
|
|
243 |
try:
|
244 |
if agent_app is None:
|
245 |
socketio.emit("log", {"message": "[INFO]: Initializing agent for the first time..."})
|
246 |
+
try:
|
247 |
+
agent_app = create_agent_app(abs_file_path)
|
248 |
+
socketio.emit("log", {"message": "[INFO]: Agent initialized."})
|
249 |
+
flash("Agent initialized.", "info")
|
250 |
+
except Exception as e:
|
251 |
+
error_message = f"Agent initialization failed: {str(e)}"
|
252 |
+
socketio.emit("log", {"message": f"[ERROR]: {error_message}"})
|
253 |
+
socketio.emit("final", {"message": "Agent initialization failed."})
|
254 |
+
flash(error_message, "error")
|
255 |
+
return
|
256 |
+
|
257 |
query = {"messages": [("user", prompt)]}
|
258 |
result = agent_app.invoke(query)
|
259 |
try:
|
260 |
+
# Attempt to extract the final answer from the tool call arguments
|
261 |
+
if result and result["messages"] and len(result["messages"]) > 0 and result["messages"][-1].tool_calls and len(result["messages"][-1].tool_calls) > 0:
|
262 |
+
result = result["messages"][-1].tool_calls[0]["args"]["final_answer"]
|
263 |
+
else:
|
264 |
+
result = "Query execution did not return a valid final answer."
|
265 |
+
flash("Query execution did not return a valid final answer.", "warning")
|
266 |
+
except KeyError:
|
267 |
+
result = "The agent's response did not contain the expected 'final_answer' key."
|
268 |
+
flash("Unexpected agent response format.", "warning")
|
269 |
except Exception as e:
|
270 |
+
result = f"An error occurred while processing the agent's response: {str(e)}"
|
271 |
+
flash("Error processing agent response.", "error")
|
272 |
+
|
273 |
print("final_answer------>", result)
|
274 |
socketio.emit("final", {"message": result})
|
275 |
except Exception as e:
|
|
|
301 |
flash(error_message, "error")
|
302 |
return "ERROR", 500
|
303 |
|
304 |
+
def is_sqlite_db(file_path):
|
305 |
+
try:
|
306 |
+
with open(file_path, 'rb') as f:
|
307 |
+
header = f.read(16)
|
308 |
+
return header[:16] == b'SQLite format 3\x00'
|
309 |
+
except Exception:
|
310 |
+
return False
|
311 |
+
|
312 |
@flask_app.route("/upload", methods=["GET", "POST"])
|
313 |
def upload():
|
314 |
global abs_file_path, agent_app, db_path
|
|
|
323 |
db_path = os.path.join(flask_app.config['UPLOAD_FOLDER'], "uploaded.db")
|
324 |
print("Saving file to:", db_path)
|
325 |
file.save(db_path)
|
326 |
+
if not is_sqlite_db(db_path):
|
327 |
+
os.remove(db_path)
|
328 |
+
flash("Uploaded file is not a valid SQLite database.", "error")
|
329 |
+
socketio.emit("log", {"message": "[ERROR]: Invalid database file uploaded."})
|
330 |
+
return render_template("upload.html")
|
331 |
abs_file_path = os.path.abspath(db_path)
|
|
|
332 |
print(f"[INFO]: File '{filename}' uploaded. Agent will be initialized on first query.")
|
333 |
socketio.emit("log", {"message": f"[INFO]: Database file '{filename}' uploaded."})
|
334 |
flash(f"Database file '{filename}' uploaded successfully.", "info")
|
335 |
+
agent_app = None # Reset the agent to be lazily reinitialized on next query.
|
336 |
return redirect(url_for("index"))
|
337 |
+
else:
|
338 |
+
flash("Invalid file format. Please upload a .db file.", "error")
|
339 |
+
return render_template("upload.html")
|
340 |
return render_template("upload.html")
|
341 |
except Exception as e:
|
342 |
error_message = f"[ERROR]: {str(e)}"
|