Files changed (1) hide show
  1. app.py +142 -201
app.py CHANGED
@@ -3,308 +3,249 @@ import os
3
  import sys
4
  import io
5
  import re
6
- import uuid
7
  import pandas as pd
8
- import numpy as np
9
- import joblib
10
- import matplotlib.pyplot as plt
11
- import seaborn as sns
12
  from typing import Annotated, TypedDict, Literal
13
- from langgraph.graph import StateGraph, END
14
  from langgraph.graph.message import add_messages
15
  from langgraph.checkpoint.memory import MemorySaver
16
  from langgraph.types import interrupt, Command
17
  from langchain_google_genai import ChatGoogleGenerativeAI
18
  from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, SystemMessage
 
19
 
20
  # --- 1. SETUP & CONFIGURATION ---
21
  st.set_page_config(page_title="Autonomous Data Scientist", layout="wide")
22
  st.title("🤖 Autonomous Data Scientist Agent")
23
 
24
- # Sidebar for API Key
25
- with st.sidebar:
26
- st.header("Configuration")
27
- api_key = st.text_input("Gemini API Key", type="password")
28
- if api_key:
29
- os.environ["GOOGLE_API_KEY"] = api_key
30
-
31
- uploaded_file = st.file_uploader("Upload Dataset (CSV)", type=["csv"])
32
- if uploaded_file is not None:
33
- # Save file locally so the agent can access it via path
34
- save_path = f"/content/{uploaded_file.name}"
35
- with open(save_path, "wb") as f:
36
- f.write(uploaded_file.getbuffer())
37
- st.success(f"File saved to: {save_path}")
38
- st.session_state["dataset_path"] = save_path
39
-
40
- # --- 2. DATABASE FUNCTIONS (Supabase) ---
41
- from supabase import create_client, Client
42
-
43
- # Initialize Supabase
44
- # We use st.cache_resource so we don't reconnect every time the app reloads
45
  @st.cache_resource
46
  def init_supabase():
47
  url = os.environ.get("SUPABASE_URL")
48
  key = os.environ.get("SUPABASE_KEY")
 
 
49
  return create_client(url, key)
50
 
51
  supabase = init_supabase()
52
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  def save_message(session_id, role, content):
54
- """Save a message to Supabase Cloud."""
55
  try:
56
- data = {
57
- "session_id": session_id,
58
- "role": role,
59
- "content": content
60
- }
61
  supabase.table("chat_history").insert(data).execute()
62
  except Exception as e:
63
- st.error(f"Database Error: {e}")
64
 
65
  def load_history(session_id):
66
- """Load history from Supabase Cloud."""
67
  try:
68
- response = supabase.table("chat_history")\
69
  .select("role, content")\
70
  .eq("session_id", session_id)\
71
  .order("created_at", desc=False)\
72
  .execute()
73
- return response.data # Returns a list of dicts: [{'role': 'user', 'content': 'hi'}]
74
  except Exception:
75
  return []
76
 
77
- # No need to call init_db() anymore, Supabase is always on.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
 
79
- # --- 2. CORE AGENT LOGIC ---
 
 
 
 
 
 
 
 
 
 
 
 
80
 
 
81
  def local_python_executor(code: str):
82
- """Executes Python code in the global scope and captures stdout."""
83
  old_stdout = sys.stdout
84
  new_stdout = io.StringIO()
85
  sys.stdout = new_stdout
86
  try:
87
- # We use a shared global dictionary to persist variables (df, model, etc.)
88
- if "agent_globals" not in st.session_state:
89
- st.session_state["agent_globals"] = globals().copy()
90
-
91
  exec(code, st.session_state["agent_globals"])
92
  output = new_stdout.getvalue()
93
- except Exception as e:
94
- output = f"❌ Error: {str(e)}"
95
- finally:
96
- sys.stdout = old_stdout
97
- return output if output.strip() else "✅ Code executed successfully (No text output)."
98
 
99
- class AgentState(TypedDict):
100
- messages: Annotated[list[BaseMessage], add_messages]
101
 
102
  def data_science_node(state: AgentState):
103
  messages = state["messages"]
104
- unique_id = st.session_state["session_id"]
105
-
106
- # Initialize LLM only if API key is present
107
  if "GOOGLE_API_KEY" not in os.environ:
108
- return {"messages": [AIMessage(content="Please provide a Google Gemini API Key in the sidebar.")]}
109
 
110
  llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
 
111
 
112
- sys_msg = SystemMessage(content="""You are an Autonomous Data Scientist.
113
  1. Run code by outputting markdown: ```python ... ```
114
- 2. Suggest models but DO NOT train without asking.
115
- 3. Ask "Do I have permission?" before training.
116
- 4. IMPORTANT: Always save the final model to exactly: '/tmp/model_{unique_id}.joblib' using joblib.
117
  """)
118
 
119
  response = llm.invoke([sys_msg] + messages)
120
 
121
- # --- CODE DETECTION & INTERCEPTOR ---
122
  if "```python" in response.content:
123
  code_match = re.search(r"```python\n(.*?)```", response.content, re.DOTALL)
124
  if code_match:
125
  code = code_match.group(1)
126
-
127
- # 🛡️ SECURITY INTERCEPTOR
128
- dangerous_keywords = [".fit(", "joblib.dump", "GradientBoosting", "RandomForest", "LogisticRegression"]
129
- if any(k in code for k in dangerous_keywords):
130
- # Interrupt and ask user
131
- decision = interrupt({
132
- "type": "security_check",
133
- "question": "The agent wants to run training code. Approve?",
134
- "code": code
135
- })
136
-
137
- # Check user decision from the Resume Command
138
  if str(decision).lower() not in ["yes", "y", "approve"]:
139
- return {"messages": [response, HumanMessage(content=f"User BLOCKED execution.")]}
140
-
141
- # Execution
142
  result = local_python_executor(code)
143
- return {"messages": [response, HumanMessage(content=f"Code Output: {result}")]}
144
 
145
- # --- PERMISSION CHECK ---
146
  if "permission" in response.content.lower():
147
- decision = interrupt({
148
- "type": "permission_request",
149
- "question": response.content,
150
- "code": None
151
- })
152
- return {"messages": [response, HumanMessage(content=f"User Decision: {decision}")]}
153
 
154
  return {"messages": [response]}
155
 
156
- def should_continue(state: AgentState) -> Literal["analyst", "__end__"]:
157
  last_msg = state["messages"][-1]
158
- if isinstance(last_msg, HumanMessage):
159
- return "analyst"
160
- return "__end__"
161
-
162
-
163
- # 1. Check if a session ID is already in the URL
164
- if "session_id" in st.query_params:
165
- st.session_state["session_id"] = st.query_params["session_id"]
166
 
167
- # 2. If not in URL and not in State, generate a new one
168
- elif "session_id" not in st.session_state:
169
- new_id = str(uuid.uuid4())[:8]
170
- st.session_state["session_id"] = new_id
171
- # Save it to the URL so it persists after refresh
172
- st.query_params["session_id"] = new_id
173
-
174
- # 3. Always ensure the URL matches the current session
175
- if st.query_params.get("session_id") != st.session_state["session_id"]:
176
- st.query_params["session_id"] = st.session_state["session_id"]
177
-
178
- # Display the ID so you can verify it stays the same
179
- st.sidebar.caption(f"🆔 Session ID: {st.session_state['session_id']}")
180
- # generate random uid for each file so saving dont mix with other
181
- if "session_id" not in st.session_state:
182
- st.session_state["session_id"] = str(uuid.uuid4())[:8] # Generates a random ID like 'a1b2c3d4'
183
-
184
- # --- 3. GRAPH BUILDER (Singleton) ---
185
  if "app_graph" not in st.session_state:
186
  workflow = StateGraph(AgentState)
187
  workflow.add_node("analyst", data_science_node)
188
  workflow.set_entry_point("analyst")
189
  workflow.add_conditional_edges("analyst", should_continue)
190
- memory = MemorySaver()
191
- st.session_state["app_graph"] = workflow.compile(checkpointer=memory)
192
- st.session_state["thread_config"] = {"configurable": {"thread_id": "streamlit_session_1"}}
193
-
194
- # --- 4. UI INTERACTION ---
195
-
196
- # Initialize Chat History
197
- if "messages" not in st.session_state:
198
- st.session_state.messages = []
199
-
200
- # Display Chat History
201
- for msg in st.session_state.messages:
202
- if msg["role"] == "user":
203
- st.chat_message("user").write(msg["content"])
204
- elif msg["role"] == "assistant":
205
- st.chat_message("assistant").write(msg["content"])
206
- if "code" in msg:
207
- with st.expander("View Code"):
208
- st.code(msg["code"], language="python")
209
-
210
- # Handle User Input
211
- user_input = st.chat_input("Ask me to analyze your data...")
212
-
213
  if user_input:
214
- # 1. Add user message to UI
215
- st.session_state.messages.append({"role": "user", "content": user_input})
216
  st.chat_message("user").write(user_input)
217
 
218
- # 2. Run Graph
219
  app = st.session_state["app_graph"]
220
- config = st.session_state["thread_config"]
221
 
222
- # We use a container to stream updates
223
  with st.spinner("Thinking..."):
224
  try:
225
- # Standard Run (Streaming)
226
- # Note: We pass None as input if we are resuming from an interrupt,
227
- # but here we assume a fresh message.
228
- # (Resuming logic is handled in the "Resume" button block below)
 
 
 
 
 
 
 
 
 
229
 
230
  for event in app.stream({"messages": [HumanMessage(content=user_input)]}, config=config):
231
  if "analyst" in event:
232
  last_msg = event["analyst"]["messages"][-1]
233
-
234
- # If code was executed (HumanMessage inside the loop)
235
- if isinstance(last_msg, HumanMessage) and "Code Output" in last_msg.content:
236
- with st.expander("⚙️ Code Output", expanded=False):
237
- st.text(last_msg.content)
238
-
239
- # If AI Responded
240
- elif isinstance(last_msg, AIMessage):
241
- st.session_state.messages.append({"role": "assistant", "content": last_msg.content})
242
  st.chat_message("assistant").write(last_msg.content)
243
-
244
- # Save if there was code in this turn (parsing it out for display)
245
- if "```python" in last_msg.content:
246
- code = re.search(r"```python\n(.*?)```", last_msg.content, re.DOTALL).group(1)
247
- st.session_state.messages[-1]["code"] = code
248
-
249
- except Exception as e:
250
- # This block catches the "GraphInterrupt" exception used by LangGraph
251
- # We don't print an error; we check the state snapshot.
252
- pass
253
 
254
- # --- 5. HANDLING INTERRUPTS (HITL) ---
255
- # We check the current state of the graph to see if it's paused.
256
- app = st.session_state["app_graph"]
257
- config = st.session_state["thread_config"]
258
- snapshot = app.get_state(config)
259
 
 
 
 
 
260
  if snapshot.next:
261
- # If the graph is paused, retrieve the interrupt details
262
- # Note: snapshot.tasks[0].interrupts is a tuple, we get the first one
263
  if snapshot.tasks and snapshot.tasks[0].interrupts:
264
  interrupt_value = snapshot.tasks[0].interrupts[0].value
265
-
266
  st.warning("⚠️ **APPROVAL REQUIRED**")
267
  st.write(interrupt_value.get("question", "Permission needed"))
268
-
269
  if interrupt_value.get("code"):
270
  st.code(interrupt_value["code"], language="python")
271
 
272
  col1, col2 = st.columns(2)
273
  with col1:
274
- if st.button("✅ Approve / Yes"):
275
- # Resume the graph with "yes"
276
  with st.spinner("Resuming..."):
277
- for event in app.stream(Command(resume="yes"), config=config):
278
  if "analyst" in event:
279
  last_msg = event["analyst"]["messages"][-1]
280
  if isinstance(last_msg, AIMessage):
281
- st.session_state.messages.append({"role": "assistant", "content": last_msg.content})
282
- st.chat_message("assistant").write(last_msg.content)
283
- elif isinstance(last_msg, HumanMessage):
284
- with st.expander("⚙️ Code Output"):
285
- st.text(last_msg.content)
286
- st.rerun() # Refresh to clear the buttons
287
-
288
- with col2:
289
- if st.button("❌ Reject / No"):
290
- with st.spinner("Rejecting..."):
291
- for event in app.stream(Command(resume="no"), config=config):
292
- if "analyst" in event:
293
- last_msg = event["analyst"]["messages"][-1]
294
- if isinstance(last_msg, AIMessage):
295
- st.session_state.messages.append({"role": "assistant", "content": last_msg.content})
296
  st.chat_message("assistant").write(last_msg.content)
297
  st.rerun()
298
- # Check if the final model exists and offer download
299
- # --- 6. EXPORT / DOWNLOAD SECTION ---
300
- unique_id = st.session_state["session_id"]
301
- model_file_path = f"/tmp/model_{unique_id}.joblib"
302
-
303
- if os.path.exists(model_file_path):
304
- with open(model_file_path, "rb") as file:
305
- st.download_button(
306
- label="⬇️ Download Your Model",
307
- data=file,
308
- file_name=f"model_{unique_id}.joblib",
309
- mime="application/octet-stream"
310
- )
 
3
  import sys
4
  import io
5
  import re
 
6
  import pandas as pd
7
+ import uuid
 
 
 
8
  from typing import Annotated, TypedDict, Literal
9
+ from langgraph.graph import StateGraph
10
  from langgraph.graph.message import add_messages
11
  from langgraph.checkpoint.memory import MemorySaver
12
  from langgraph.types import interrupt, Command
13
  from langchain_google_genai import ChatGoogleGenerativeAI
14
  from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, SystemMessage
15
+ from supabase import create_client
16
 
17
  # --- 1. SETUP & CONFIGURATION ---
18
  st.set_page_config(page_title="Autonomous Data Scientist", layout="wide")
19
  st.title("🤖 Autonomous Data Scientist Agent")
20
 
21
+ # --- 2. SUPABASE CONNECTION ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  @st.cache_resource
23
  def init_supabase():
24
  url = os.environ.get("SUPABASE_URL")
25
  key = os.environ.get("SUPABASE_KEY")
26
+ if not url or not key:
27
+ return None
28
  return create_client(url, key)
29
 
30
  supabase = init_supabase()
31
 
32
+ def get_all_sessions():
33
+ """Fetch all unique session IDs from the database to list in the sidebar."""
34
+ if not supabase: return []
35
+ try:
36
+ # Fetch all session_ids (inefficient for millions of rows, but fine for now)
37
+ res = supabase.table("chat_history").select("session_id").execute()
38
+ # Get unique IDs and reverse them (so newest might appear first if sorted)
39
+ unique_ids = list(set([row['session_id'] for row in res.data]))
40
+ return sorted(unique_ids, reverse=True)
41
+ except Exception:
42
+ return []
43
+
44
  def save_message(session_id, role, content):
45
+ if not supabase: return
46
  try:
47
+ data = {"session_id": session_id, "role": role, "content": content}
 
 
 
 
48
  supabase.table("chat_history").insert(data).execute()
49
  except Exception as e:
50
+ st.error(f"DB Error: {e}")
51
 
52
  def load_history(session_id):
53
+ if not supabase: return []
54
  try:
55
+ res = supabase.table("chat_history")\
56
  .select("role, content")\
57
  .eq("session_id", session_id)\
58
  .order("created_at", desc=False)\
59
  .execute()
60
+ return res.data
61
  except Exception:
62
  return []
63
 
64
+ # --- 3. SIDEBAR: SESSION SELECTOR ---
65
+ with st.sidebar:
66
+ st.header("🗄️ Chat History")
67
+
68
+ # 1. Button to start a fresh chat
69
+ if st.button("➕ New Chat"):
70
+ new_id = str(uuid.uuid4())[:8]
71
+ st.session_state["session_id"] = new_id
72
+ st.rerun()
73
+
74
+ # 2. Dropdown to select past chats
75
+ existing_sessions = get_all_sessions()
76
+
77
+ # If we have a session in state, make sure it's the default in the box
78
+ if "session_id" not in st.session_state:
79
+ st.session_state["session_id"] = existing_sessions[0] if existing_sessions else str(uuid.uuid4())[:8]
80
+
81
+ selected_session = st.selectbox(
82
+ "Load Past Conversation:",
83
+ options=existing_sessions,
84
+ index=existing_sessions.index(st.session_state["session_id"]) if st.session_state["session_id"] in existing_sessions else 0
85
+ )
86
+
87
+ # If user changed the dropdown, update the state
88
+ if selected_session != st.session_state["session_id"]:
89
+ st.session_state["session_id"] = selected_session
90
+ st.rerun()
91
 
92
+ st.caption(f"Current Thread ID: {st.session_state['session_id']}")
93
+
94
+ # --- API KEY & FILE UPLOAD ---
95
+ st.divider()
96
+ api_key = st.text_input("Gemini API Key", type="password")
97
+ if api_key: os.environ["GOOGLE_API_KEY"] = api_key
98
+
99
+ uploaded_file = st.file_uploader("Upload Dataset (CSV)", type=["csv"])
100
+ if uploaded_file:
101
+ save_path = f"/tmp/{st.session_state['session_id']}_{uploaded_file.name}"
102
+ with open(save_path, "wb") as f: f.write(uploaded_file.getbuffer())
103
+ st.session_state["dataset_path"] = save_path
104
+ st.success("File Uploaded!")
105
 
106
+ # --- 4. CORE AGENT LOGIC (Standard) ---
107
  def local_python_executor(code: str):
 
108
  old_stdout = sys.stdout
109
  new_stdout = io.StringIO()
110
  sys.stdout = new_stdout
111
  try:
112
+ if "agent_globals" not in st.session_state: st.session_state["agent_globals"] = globals().copy()
 
 
 
113
  exec(code, st.session_state["agent_globals"])
114
  output = new_stdout.getvalue()
115
+ except Exception as e: output = f"❌ Error: {str(e)}"
116
+ finally: sys.stdout = old_stdout
117
+ return output if output.strip() else "✅ Done."
 
 
118
 
119
+ class AgentState(TypedDict): messages: Annotated[list[BaseMessage], add_messages]
 
120
 
121
  def data_science_node(state: AgentState):
122
  messages = state["messages"]
 
 
 
123
  if "GOOGLE_API_KEY" not in os.environ:
124
+ return {"messages": [AIMessage(content="Please provide a Gemini API Key.")]}
125
 
126
  llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
127
+ uid = st.session_state["session_id"]
128
 
129
+ sys_msg = SystemMessage(content=f"""You are an Autonomous Data Scientist.
130
  1. Run code by outputting markdown: ```python ... ```
131
+ 2. Ask "Do I have permission?" before training.
132
+ 3. IMPORTANT: Save models to exactly: '/tmp/model_{uid}.joblib'
133
+ 4. Dataset Path: '{st.session_state.get('dataset_path', 'No file')}'
134
  """)
135
 
136
  response = llm.invoke([sys_msg] + messages)
137
 
 
138
  if "```python" in response.content:
139
  code_match = re.search(r"```python\n(.*?)```", response.content, re.DOTALL)
140
  if code_match:
141
  code = code_match.group(1)
142
+ dangerous = [".fit(", "joblib.dump", "GradientBoosting", "RandomForest", "LogisticRegression"]
143
+ if any(k in code for k in dangerous):
144
+ decision = interrupt({"type": "security", "question": "Approve training?", "code": code})
 
 
 
 
 
 
 
 
 
145
  if str(decision).lower() not in ["yes", "y", "approve"]:
146
+ return {"messages": [response, HumanMessage(content="Blocked.")]}
 
 
147
  result = local_python_executor(code)
148
+ return {"messages": [response, HumanMessage(content=f"Output: {result}")]}
149
 
 
150
  if "permission" in response.content.lower():
151
+ decision = interrupt({"type": "perm", "question": response.content})
152
+ return {"messages": [response, HumanMessage(content=f"Decision: {decision}")]}
 
 
 
 
153
 
154
  return {"messages": [response]}
155
 
156
+ def should_continue(state):
157
  last_msg = state["messages"][-1]
158
+ return "analyst" if isinstance(last_msg, HumanMessage) else "__end__"
 
 
 
 
 
 
 
159
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  if "app_graph" not in st.session_state:
161
  workflow = StateGraph(AgentState)
162
  workflow.add_node("analyst", data_science_node)
163
  workflow.set_entry_point("analyst")
164
  workflow.add_conditional_edges("analyst", should_continue)
165
+ st.session_state["app_graph"] = workflow.compile(checkpointer=MemorySaver())
166
+
167
+ # --- 5. CHAT INTERFACE ---
168
+ # Load history for the SELECTED session
169
+ history_msgs = load_history(st.session_state["session_id"])
170
+
171
+ # Render Chat
172
+ for msg in history_msgs:
173
+ role = "user" if msg["role"] == "user" else "assistant"
174
+ st.chat_message(role).write(msg["content"])
175
+ if role == "assistant" and "```python" in msg["content"]:
176
+ code = re.search(r"```python\n(.*?)```", msg["content"], re.DOTALL)
177
+ if code: with st.expander("View Code"): st.code(code.group(1), language="python")
178
+
179
+ # Handle Input
180
+ user_input = st.chat_input("Ask a question...")
 
 
 
 
 
 
 
181
  if user_input:
182
+ # Save & Show User Msg
183
+ save_message(st.session_state["session_id"], "user", user_input)
184
  st.chat_message("user").write(user_input)
185
 
186
+ # Run Agent
187
  app = st.session_state["app_graph"]
188
+ config = {"configurable": {"thread_id": st.session_state["session_id"]}}
189
 
 
190
  with st.spinner("Thinking..."):
191
  try:
192
+ # Note: We pass the FULL history from DB to the agent so it has context
193
+ # We reconstruct BaseMessages from the DB dictionaries
194
+ past_messages = []
195
+ for m in history_msgs:
196
+ if m["role"] == "user": past_messages.append(HumanMessage(content=m["content"]))
197
+ else: past_messages.append(AIMessage(content=m["content"]))
198
+
199
+ # Add new input
200
+ past_messages.append(HumanMessage(content=user_input))
201
+
202
+ # Since LangGraph memory handles state, we actually just invoke with the NEW message
203
+ # But to ensure it syncs with our DB history, we rely on LangGraph's internal memory
204
+ # The DB is primarily for UI display and persistence across reloads.
205
 
206
  for event in app.stream({"messages": [HumanMessage(content=user_input)]}, config=config):
207
  if "analyst" in event:
208
  last_msg = event["analyst"]["messages"][-1]
209
+ if isinstance(last_msg, AIMessage):
210
+ save_message(st.session_state["session_id"], "assistant", last_msg.content)
 
 
 
 
 
 
 
211
  st.chat_message("assistant").write(last_msg.content)
212
+ elif isinstance(last_msg, HumanMessage) and "Output" in last_msg.content:
213
+ with st.expander("Output"): st.text(last_msg.content)
 
 
 
 
 
 
 
 
214
 
215
+ except Exception: pass # Graph interrupt logic is same as before
 
 
 
 
216
 
217
+ # Interrupt UI Logic (Buttons) - Keep your previous button logic here
218
+ # (I omitted it for brevity, but copy the "HANDLING INTERRUPTS" block from the previous code)
219
+ # --- 6. HANDLING INTERRUPTS (HITL) ---
220
+ snapshot = app.get_state({"configurable": {"thread_id": st.session_state["session_id"]}})
221
  if snapshot.next:
 
 
222
  if snapshot.tasks and snapshot.tasks[0].interrupts:
223
  interrupt_value = snapshot.tasks[0].interrupts[0].value
 
224
  st.warning("⚠️ **APPROVAL REQUIRED**")
225
  st.write(interrupt_value.get("question", "Permission needed"))
 
226
  if interrupt_value.get("code"):
227
  st.code(interrupt_value["code"], language="python")
228
 
229
  col1, col2 = st.columns(2)
230
  with col1:
231
+ if st.button("✅ Approve"):
 
232
  with st.spinner("Resuming..."):
233
+ for event in app.stream(Command(resume="yes"), config={"configurable": {"thread_id": st.session_state["session_id"]}}):
234
  if "analyst" in event:
235
  last_msg = event["analyst"]["messages"][-1]
236
  if isinstance(last_msg, AIMessage):
237
+ save_message(st.session_state["session_id"], "assistant", last_msg.content)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
238
  st.chat_message("assistant").write(last_msg.content)
239
  st.rerun()
240
+ with col2:
241
+ if st.button("❌ Reject"):
242
+ for event in app.stream(Command(resume="no"), config={"configurable": {"thread_id": st.session_state["session_id"]}}): pass
243
+ st.rerun()
244
+
245
+ # Download Button Logic
246
+ uid = st.session_state["session_id"]
247
+ model_path = f"/tmp/model_{uid}.joblib"
248
+ if os.path.exists(model_path):
249
+ st.divider()
250
+ with open(model_path, "rb") as f:
251
+ st.download_button("⬇️ Download Trained Model", f, f"model_{uid}.joblib")