mohammedelfeky-ai commited on
Commit
3e2ff2f
·
verified ·
1 Parent(s): 9a2a3bc

Update Gradio_UI.py

Browse files
Files changed (1) hide show
  1. Gradio_UI.py +119 -108
Gradio_UI.py CHANGED
@@ -36,14 +36,13 @@ def pull_messages_from_step_dict(step_log: MemoryStep):
36
 
37
  if hasattr(step_log, "model_output") and step_log.model_output is not None:
38
  model_output = step_log.model_output.strip()
39
- # More robust cleaning for <end_code> potentially wrapped in backticks or with newlines
40
  model_output = re.sub(r"```\s*<end_code>[\s\S]*|[\s\S]*<end_code>\s*```", "```", model_output, flags=re.DOTALL)
41
- model_output = re.sub(r"<end_code>", "", model_output) # Remove standalone tag
42
  model_output = model_output.strip()
43
  yield {"role": "assistant", "content": model_output}
44
 
45
  if hasattr(step_log, "tool_calls") and step_log.tool_calls:
46
- tc = step_log.tool_calls[0] # Process first tool call for simplicity in this format
47
  tool_info_md = f"🛠️ **Tool Used: {tc.name}**\n"
48
 
49
  args = tc.arguments
@@ -54,7 +53,6 @@ def pull_messages_from_step_dict(step_log: MemoryStep):
54
 
55
  if tc.name == "python_interpreter":
56
  code_content = args_str
57
- # Clean up common wrapping issues
58
  code_content = re.sub(r"^```python\s*\n?", "", code_content)
59
  code_content = re.sub(r"\n?```\s*$", "", code_content)
60
  code_content = re.sub(r"^\s*<end_code>\s*", "", code_content)
@@ -66,34 +64,32 @@ def pull_messages_from_step_dict(step_log: MemoryStep):
66
 
67
  if hasattr(step_log, "observations") and step_log.observations and step_log.observations.strip():
68
  obs_content = step_log.observations.strip()
69
- # Remove "Execution logs:" prefix if present for cleaner display
70
  obs_content = re.sub(r"^Execution logs:\s*", "", obs_content).strip()
71
- if obs_content: # Only show if there's something after stripping
72
- tool_info_md += f"📝 **Tool Output/Logs:**\n```\n{obs_content}\n```\n"
73
 
74
  if hasattr(step_log, "error") and step_log.error:
75
  tool_info_md += f"💥 **Error:** {str(step_log.error)}\n"
76
 
77
  yield {"role": "assistant", "content": tool_info_md.strip()}
78
 
79
- elif hasattr(step_log, "error") and step_log.error: # Standalone error not from a tool call
80
  yield {"role": "assistant", "content": f"💥 **Error:** {str(step_log.error)}"}
81
 
82
- # --- Minimal footnote for type="messages" ---
83
  footnote_parts = []
84
  if step_log.step_number is not None:
85
  footnote_parts.append(f"Step {step_log.step_number}")
86
  if hasattr(step_log, "duration") and step_log.duration is not None:
87
  footnote_parts.append(f"Duration: {round(float(step_log.duration), 2)}s")
88
- if hasattr(step_log, "input_token_count") and step_log.input_token_count is not None: # Check for None
89
  footnote_parts.append(f"InTokens: {step_log.input_token_count:,}")
90
- if hasattr(step_log, "output_token_count") and step_log.output_token_count is not None: # Check for None
91
  footnote_parts.append(f"OutTokens: {step_log.output_token_count:,}")
92
 
93
  if footnote_parts:
94
  footnote_text = " | ".join(footnote_parts)
95
  yield {"role": "assistant", "content": f"""<p style="color: #999; font-size: 0.8em; margin-top:0; margin-bottom:0;">{footnote_text}</p>"""}
96
- yield {"role": "assistant", "content": "---"} # Separator
97
 
98
 
99
  def stream_to_gradio(
@@ -102,34 +98,41 @@ def stream_to_gradio(
102
  reset_agent_memory: bool = False,
103
  additional_args: Optional[dict] = None,
104
  ):
105
- """Runs an agent, yields message dicts for Gradio type='messages' Chatbot."""
106
  if not _is_package_available("gradio"):
107
  raise ModuleNotFoundError("Install 'gradio': `pip install 'smolagents[gradio]'`")
108
 
109
- if hasattr(agent, 'interaction_logs'): # Clear logs for this new agent run
110
  agent.interaction_logs.clear()
111
  print("DEBUG Gradio: Cleared agent interaction_logs for new run.")
112
 
 
 
113
  for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):
 
114
  if hasattr(agent.model, "last_input_token_count") and agent.model.last_input_token_count is not None:
115
  if isinstance(step_log, ActionStep):
116
  step_log.input_token_count = agent.model.last_input_token_count
117
  step_log.output_token_count = agent.model.last_output_token_count
118
 
119
- for msg_dict in pull_messages_from_step_dict(step_log): # Use new dict-yielding function
120
  yield msg_dict
 
 
 
 
 
121
 
122
- final_answer_content = step_log # Last step_log is the final output/state
123
 
124
  # --- Handle final answer for type="messages" ---
125
  if isinstance(final_answer_content, PILImage.Image):
126
- print("DEBUG Gradio (stream_to_gradio): Final answer is raw PIL Image.")
127
  try:
 
128
  with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmp_file:
129
  final_answer_content.save(tmp_file, format="PNG")
130
  image_path_for_gradio = tmp_file.name
131
- print(f"DEBUG Gradio: Saved PIL image to temp path: {image_path_for_gradio}")
132
- # For Gradio type="messages", image content is just the path string
133
  yield {"role": "assistant", "content": image_path_for_gradio}
134
  return
135
  except Exception as e:
@@ -137,17 +140,43 @@ def stream_to_gradio(
137
  yield {"role": "assistant", "content": f"**Final Answer (Error displaying image):** {e}"}
138
  return
139
 
140
- final_answer_processed = handle_agent_output_types(final_answer_content)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
 
142
  if isinstance(final_answer_processed, AgentText):
143
  yield {"role": "assistant", "content": f"**Final Answer:**\n{final_answer_processed.to_string()}"}
144
  elif isinstance(final_answer_processed, AgentImage):
145
  image_path = final_answer_processed.to_string()
146
- print(f"DEBUG Gradio (stream_to_gradio): AgentImage path: {image_path}")
147
  if image_path and os.path.exists(image_path):
148
  yield {"role": "assistant", "content": image_path}
149
  else:
150
- err_msg = f"Error: Image path from AgentImage not found or invalid ('{image_path}')"
151
  print(f"DEBUG Gradio: {err_msg}")
152
  yield {"role": "assistant", "content": f"**Final Answer ({err_msg})**"}
153
  elif isinstance(final_answer_processed, AgentAudio):
@@ -156,16 +185,15 @@ def stream_to_gradio(
156
  if audio_path and os.path.exists(audio_path):
157
  yield {"role": "assistant", "content": audio_path}
158
  else:
159
- err_msg = f"Error: Audio path from AgentAudio not found ('{audio_path}')"
160
  print(f"DEBUG Gradio: {err_msg}")
161
  yield {"role": "assistant", "content": f"**Final Answer ({err_msg})**"}
162
  else:
 
163
  yield {"role": "assistant", "content": f"**Final Answer:**\n{str(final_answer_processed)}"}
164
 
165
 
166
  class GradioUI:
167
- """A one-line interface to launch your agent in Gradio"""
168
-
169
  def __init__(self, agent: MultiStepAgent, file_upload_folder: str | None = None):
170
  if not _is_package_available("gradio"):
171
  raise ModuleNotFoundError("Install 'gradio': `pip install 'smolagents[gradio]'`")
@@ -180,82 +208,65 @@ class GradioUI:
180
  self._latest_file_path_for_download = None
181
  if hasattr(self.agent, 'interaction_logs') and self.agent.interaction_logs:
182
  print(f"DEBUG Gradio UI: Checking {len(self.agent.interaction_logs)} interaction log entries for created files.")
183
- for log_entry in reversed(self.agent.interaction_logs): # Check recent logs first
184
- if isinstance(log_entry, ActionStep) and hasattr(log_entry, 'tool_calls') and log_entry.tool_calls:
185
- for tool_call in log_entry.tool_calls:
186
- if tool_call.name == "create_document":
187
- tool_output_value = getattr(log_entry, 'observations', None)
188
- print(f"DEBUG Gradio UI: Log for 'create_document' call, observed output: {tool_output_value}")
189
- if tool_output_value and isinstance(tool_output_value, str):
190
- # Try to extract path if it's wrapped, e.g. by "Execution logs:"
191
- cleaned_output = re.sub(r"^Execution logs:\s*", "", tool_output_value).strip()
192
- path_match = re.search(r"(/tmp/[a-zA-Z0-9_]+/generated_document\.(?:docx|pdf|txt))", cleaned_output)
193
- extracted_path = path_match.group(1) if path_match else cleaned_output
194
-
195
- if not extracted_path.lower().startswith("error:"):
196
- normalized_path = os.path.normpath(extracted_path)
197
- if os.path.exists(normalized_path):
198
- self._latest_file_path_for_download = normalized_path
199
- print(f"DEBUG Gradio UI: File path for download set: {self._latest_file_path_for_download}")
200
- return True
201
- else:
202
- print(f"DEBUG Gradio UI: Path from 'create_document' log ('{normalized_path}') does not exist.")
203
- else:
204
- print(f"DEBUG Gradio UI: 'create_document' tool reported error in observations: {extracted_path}")
205
- print("DEBUG Gradio UI: No valid 'create_document' output found for download.")
206
  return False
207
 
208
- def interact_with_agent(self, prompt_text: str, current_chat_tuples: list):
209
- # current_chat_tuples is the history from the chatbot (list of lists/tuples)
210
- # Convert to 'messages' format if needed, or adapt stream_to_gradio if chatbot is not type="messages"
211
- # For type="messages", current_chat_tuples is already list of dicts.
212
-
213
  print(f"DEBUG Gradio: interact_with_agent called with prompt: '{prompt_text}'")
214
- print(f"DEBUG Gradio: Current chat history (input): {current_chat_tuples}")
215
 
216
- # Add user's new message to the chat history list
217
- current_chat_messages = current_chat_tuples + [{"role": "user", "content": prompt_text}]
218
 
219
- # Initial yield to show user message immediately and hide download items
220
- yield current_chat_messages, gr.update(visible=False), gr.update(value=None, visible=False)
221
 
222
- # Stream agent messages
223
  agent_responses_for_history = []
224
  for msg_dict in stream_to_gradio(self.agent, task=prompt_text, reset_agent_memory=False):
225
  agent_responses_for_history.append(msg_dict)
226
- # Yield progressively: current user message + all agent messages so far
227
- yield current_chat_messages + agent_responses_for_history, gr.update(visible=False), gr.update(value=None, visible=False)
228
 
229
- # After streaming all agent messages, check for created file
230
  file_found = self._check_for_created_file()
231
 
232
- # Final state for UI components
233
- final_chat_display = current_chat_messages + agent_responses_for_history
234
- print(f"DEBUG Gradio: Final chat history for display: {final_chat_display}")
235
  yield final_chat_display, gr.update(visible=file_found), gr.update(value=None, visible=False)
236
 
237
-
238
  def upload_file(self, file, file_uploads_log_state):
239
- if file is None: # No file selected
240
  return gr.update(value="No file uploaded.", visible=True), file_uploads_log_state
241
 
242
- # Ensure file_upload_folder exists (it should from __init__)
243
  if not self.file_upload_folder or not os.path.exists(self.file_upload_folder):
244
- os.makedirs(self.file_upload_folder, exist_ok=True) # Defensive check
245
 
246
  allowed_file_types = [
247
  "application/pdf",
248
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
249
- "text/plain",
250
- "image/jpeg", "image/png", # Added image types
251
  ]
252
 
253
- # Gradio File object has 'name' (temp path) and 'orig_name'
254
- original_name = file.orig_name if hasattr(file, 'orig_name') else os.path.basename(file.name)
255
 
256
- # Try to guess mime type from temp file name first, then from original name if needed
257
  mime_type, _ = mimetypes.guess_type(file.name)
258
- if mime_type is None: # Fallback
259
  mime_type, _ = mimetypes.guess_type(original_name)
260
 
261
  if mime_type not in allowed_file_types:
@@ -264,13 +275,13 @@ class GradioUI:
264
  sanitized_name = re.sub(r"[^\w\-.]", "_", original_name)
265
  base_name, current_ext = os.path.splitext(sanitized_name)
266
 
267
- type_to_ext_map = {v: k for k, v_list in mimetypes. প্রেফারেন্সেস.items() for v in v_list} # More robust ext map
268
- type_to_ext_map.update({ # Manual overrides / common types
269
  "application/pdf": ".pdf",
270
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx",
271
  "text/plain": ".txt", "image/jpeg": ".jpg", "image/png": ".png"
272
- })
273
- expected_ext = type_to_ext_map.get(mime_type)
274
 
275
  if expected_ext and current_ext.lower() != expected_ext.lower():
276
  sanitized_name = base_name + expected_ext
@@ -278,22 +289,21 @@ class GradioUI:
278
  destination_path = os.path.join(self.file_upload_folder, sanitized_name)
279
 
280
  try:
281
- shutil.copy(file.name, destination_path) # file.name is the temp path from Gradio
282
  print(f"DEBUG Gradio: File '{original_name}' copied to '{destination_path}'")
283
  updated_log = file_uploads_log_state + [destination_path]
284
- return gr.update(value=f"Uploaded: {original_name} (as {sanitized_name})", visible=True), updated_log
285
  except Exception as e:
286
  print(f"DEBUG Gradio: Error copying uploaded file: {e}")
287
  return gr.update(value=f"Error uploading {original_name}: {e}", visible=True), file_uploads_log_state
288
 
289
-
290
  def log_user_message(self, text_input_value: str, current_file_uploads: list):
291
  full_prompt = text_input_value
292
  if current_file_uploads:
293
  files_str = ", ".join([os.path.basename(f) for f in current_file_uploads])
294
  full_prompt += f"\n\n[Uploaded files for context: {files_str}]"
295
- print(f"DEBUG Gradio: Prepared prompt for agent: {full_prompt}")
296
- return full_prompt, "" # Clears the text input box
297
 
298
  def prepare_and_show_download_file(self):
299
  if self._latest_file_path_for_download and os.path.exists(self._latest_file_path_for_download):
@@ -303,56 +313,57 @@ class GradioUI:
303
  visible=True)
304
  else:
305
  print("DEBUG Gradio UI: No valid file path to prepare for download component.")
306
- gr.Warning("No file available for download or path is invalid.")
307
- return gr.File.update(visible=False)
308
 
309
  def launch(self, **kwargs):
310
  with gr.Blocks(fill_height=True, theme=gr.themes.Soft(primary_hue=gr.themes.colors.blue)) as demo:
311
  file_uploads_log_state = gr.State([])
312
  prepared_prompt_for_agent = gr.State("")
313
 
314
- gr.Markdown("# agente inteligente")
315
 
316
- with gr.Row():
317
  with gr.Column(scale=3):
318
  chatbot_display = gr.Chatbot(
319
  label="Agent Interaction",
320
  type="messages",
321
  avatar_images=(None, "https://huggingface.co/datasets/huggingface/brand-assets/resolve/main/hf-logo-round.png"),
322
- height=600,
323
  show_copy_button=True,
324
- bubble_full_width=False
 
325
  )
326
  text_message_input = gr.Textbox(
327
  lines=1,
328
  label="Your Message to the Agent",
329
- placeholder="Type your message and press Enter, or Shift+Enter for new line..."
 
330
  )
331
 
332
  with gr.Column(scale=1):
333
  if self.file_upload_folder is not None:
334
- gr.Markdown("### File Upload")
335
- file_uploader = gr.File(label="Upload a supporting file (PDF, DOCX, TXT, JPG, PNG)")
336
- upload_status_text = gr.Textbox(label="Upload Status", interactive=False, lines=2, max_lines=4)
337
- file_uploader.upload(
338
- self.upload_file,
339
- [file_uploader, file_uploads_log_state],
340
- [upload_status_text, file_uploads_log_state],
341
- )
342
 
343
- gr.Markdown("### Generated File")
344
- download_action_button = gr.Button("Download Generated File", visible=False)
345
- file_download_display_component = gr.File(label="Downloadable Document", visible=False, interactive=False)
346
 
347
- # Event Handling Chain for Text Submission
348
  text_message_input.submit(
349
- self.log_user_message, # Step 1: Prepare prompt, clear input
350
  [text_message_input, file_uploads_log_state],
351
  [prepared_prompt_for_agent, text_message_input]
352
  ).then(
353
- self.interact_with_agent, # Step 2: Run agent, stream to chatbot, update download button
354
- [prepared_prompt_for_agent, chatbot_display],
355
- [chatbot_display, download_action_button, file_download_display_component]
356
  )
357
 
358
  download_action_button.click(
@@ -360,7 +371,7 @@ class GradioUI:
360
  [],
361
  [file_download_display_component]
362
  )
363
-
364
  demo.launch(debug=True, share=kwargs.get("share", False), **kwargs)
365
 
366
  __all__ = ["stream_to_gradio", "GradioUI"]
 
36
 
37
  if hasattr(step_log, "model_output") and step_log.model_output is not None:
38
  model_output = step_log.model_output.strip()
 
39
  model_output = re.sub(r"```\s*<end_code>[\s\S]*|[\s\S]*<end_code>\s*```", "```", model_output, flags=re.DOTALL)
40
+ model_output = re.sub(r"<end_code>", "", model_output)
41
  model_output = model_output.strip()
42
  yield {"role": "assistant", "content": model_output}
43
 
44
  if hasattr(step_log, "tool_calls") and step_log.tool_calls:
45
+ tc = step_log.tool_calls[0]
46
  tool_info_md = f"🛠️ **Tool Used: {tc.name}**\n"
47
 
48
  args = tc.arguments
 
53
 
54
  if tc.name == "python_interpreter":
55
  code_content = args_str
 
56
  code_content = re.sub(r"^```python\s*\n?", "", code_content)
57
  code_content = re.sub(r"\n?```\s*$", "", code_content)
58
  code_content = re.sub(r"^\s*<end_code>\s*", "", code_content)
 
64
 
65
  if hasattr(step_log, "observations") and step_log.observations and step_log.observations.strip():
66
  obs_content = step_log.observations.strip()
 
67
  obs_content = re.sub(r"^Execution logs:\s*", "", obs_content).strip()
68
+ if obs_content:
69
+ tool_info_md += f"📝 **Tool Output/Logs:**\n```text\n{obs_content}\n```\n" # Use text for generic logs
70
 
71
  if hasattr(step_log, "error") and step_log.error:
72
  tool_info_md += f"💥 **Error:** {str(step_log.error)}\n"
73
 
74
  yield {"role": "assistant", "content": tool_info_md.strip()}
75
 
76
+ elif hasattr(step_log, "error") and step_log.error:
77
  yield {"role": "assistant", "content": f"💥 **Error:** {str(step_log.error)}"}
78
 
 
79
  footnote_parts = []
80
  if step_log.step_number is not None:
81
  footnote_parts.append(f"Step {step_log.step_number}")
82
  if hasattr(step_log, "duration") and step_log.duration is not None:
83
  footnote_parts.append(f"Duration: {round(float(step_log.duration), 2)}s")
84
+ if hasattr(step_log, "input_token_count") and step_log.input_token_count is not None:
85
  footnote_parts.append(f"InTokens: {step_log.input_token_count:,}")
86
+ if hasattr(step_log, "output_token_count") and step_log.output_token_count is not None:
87
  footnote_parts.append(f"OutTokens: {step_log.output_token_count:,}")
88
 
89
  if footnote_parts:
90
  footnote_text = " | ".join(footnote_parts)
91
  yield {"role": "assistant", "content": f"""<p style="color: #999; font-size: 0.8em; margin-top:0; margin-bottom:0;">{footnote_text}</p>"""}
92
+ yield {"role": "assistant", "content": "---"}
93
 
94
 
95
  def stream_to_gradio(
 
98
  reset_agent_memory: bool = False,
99
  additional_args: Optional[dict] = None,
100
  ):
 
101
  if not _is_package_available("gradio"):
102
  raise ModuleNotFoundError("Install 'gradio': `pip install 'smolagents[gradio]'`")
103
 
104
+ if hasattr(agent, 'interaction_logs'):
105
  agent.interaction_logs.clear()
106
  print("DEBUG Gradio: Cleared agent interaction_logs for new run.")
107
 
108
+ # This will collect all step_log objects from the agent run
109
+ all_step_logs = []
110
  for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):
111
+ all_step_logs.append(step_log) # Store the log
112
  if hasattr(agent.model, "last_input_token_count") and agent.model.last_input_token_count is not None:
113
  if isinstance(step_log, ActionStep):
114
  step_log.input_token_count = agent.model.last_input_token_count
115
  step_log.output_token_count = agent.model.last_output_token_count
116
 
117
+ for msg_dict in pull_messages_from_step_dict(step_log):
118
  yield msg_dict
119
+
120
+ # After the loop, the last item in all_step_logs is the final output/state from agent.run
121
+ if not all_step_logs: # Should not happen if agent.run yields at least one thing
122
+ yield {"role": "assistant", "content": "Agent did not produce any output."}
123
+ return
124
 
125
+ final_answer_content = all_step_logs[-1] # This is what final_answer tool returns or the last ActionStep.final_answer
126
 
127
  # --- Handle final answer for type="messages" ---
128
  if isinstance(final_answer_content, PILImage.Image):
129
+ print("DEBUG Gradio (stream_to_gradio): Final answer content IS a raw PIL Image.")
130
  try:
131
+ # delete=False is crucial for Gradio to access the file before it's cleaned up
132
  with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmp_file:
133
  final_answer_content.save(tmp_file, format="PNG")
134
  image_path_for_gradio = tmp_file.name
135
+ print(f"DEBUG Gradio: Saved PIL image to temp path for display: {image_path_for_gradio}")
 
136
  yield {"role": "assistant", "content": image_path_for_gradio}
137
  return
138
  except Exception as e:
 
140
  yield {"role": "assistant", "content": f"**Final Answer (Error displaying image):** {e}"}
141
  return
142
 
143
+ # If not a raw PIL Image, then try smolagents processing from handle_agent_output_types
144
+ # The 'final_answer_content' here could be a FinalAnswerStep object or similar
145
+ # We need to extract the actual content from it if it's a wrapper.
146
+ actual_content_for_handling = final_answer_content
147
+ if hasattr(final_answer_content, 'final_answer') and not isinstance(final_answer_content, (str, PILImage.Image)):
148
+ actual_content_for_handling = final_answer_content.final_answer
149
+ print(f"DEBUG Gradio: Extracted actual_content_for_handling from FinalAnswerStep: {type(actual_content_for_handling)}")
150
+
151
+
152
+ # Re-check if the extracted content is a PIL Image
153
+ if isinstance(actual_content_for_handling, PILImage.Image):
154
+ print("DEBUG Gradio (stream_to_gradio): Extracted content IS a raw PIL Image.")
155
+ try:
156
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmp_file:
157
+ actual_content_for_handling.save(tmp_file, format="PNG")
158
+ image_path_for_gradio = tmp_file.name
159
+ print(f"DEBUG Gradio: Saved extracted PIL image to temp path: {image_path_for_gradio}")
160
+ yield {"role": "assistant", "content": image_path_for_gradio}
161
+ return
162
+ except Exception as e:
163
+ print(f"DEBUG Gradio: Error saving extracted PIL image: {e}")
164
+ yield {"role": "assistant", "content": f"**Final Answer (Error displaying image from extracted content):** {e}"}
165
+ return
166
+
167
+ final_answer_processed = handle_agent_output_types(actual_content_for_handling)
168
+ print(f"DEBUG Gradio: final_answer_processed type after handle_agent_output_types: {type(final_answer_processed)}")
169
+
170
 
171
  if isinstance(final_answer_processed, AgentText):
172
  yield {"role": "assistant", "content": f"**Final Answer:**\n{final_answer_processed.to_string()}"}
173
  elif isinstance(final_answer_processed, AgentImage):
174
  image_path = final_answer_processed.to_string()
175
+ print(f"DEBUG Gradio (stream_to_gradio): final_answer_processed is AgentImage. Path: {image_path}")
176
  if image_path and os.path.exists(image_path):
177
  yield {"role": "assistant", "content": image_path}
178
  else:
179
+ err_msg = f"Error: Image path from AgentImage ('{image_path}') not found or invalid after smolagents processing."
180
  print(f"DEBUG Gradio: {err_msg}")
181
  yield {"role": "assistant", "content": f"**Final Answer ({err_msg})**"}
182
  elif isinstance(final_answer_processed, AgentAudio):
 
185
  if audio_path and os.path.exists(audio_path):
186
  yield {"role": "assistant", "content": audio_path}
187
  else:
188
+ err_msg = f"Error: Audio path from AgentAudio ('{audio_path}') not found"
189
  print(f"DEBUG Gradio: {err_msg}")
190
  yield {"role": "assistant", "content": f"**Final Answer ({err_msg})**"}
191
  else:
192
+ # This will display the string representation of FinalAnswerStep if not handled above
193
  yield {"role": "assistant", "content": f"**Final Answer:**\n{str(final_answer_processed)}"}
194
 
195
 
196
  class GradioUI:
 
 
197
  def __init__(self, agent: MultiStepAgent, file_upload_folder: str | None = None):
198
  if not _is_package_available("gradio"):
199
  raise ModuleNotFoundError("Install 'gradio': `pip install 'smolagents[gradio]'`")
 
208
  self._latest_file_path_for_download = None
209
  if hasattr(self.agent, 'interaction_logs') and self.agent.interaction_logs:
210
  print(f"DEBUG Gradio UI: Checking {len(self.agent.interaction_logs)} interaction log entries for created files.")
211
+ for log_entry in reversed(self.agent.interaction_logs):
212
+ if isinstance(log_entry, ActionStep):
213
+ observations = getattr(log_entry, 'observations', None)
214
+ tool_calls = getattr(log_entry, 'tool_calls', [])
215
+
216
+ # Check if python_interpreter was used AND its code involved create_document
217
+ # For simplicity, we'll primarily rely on parsing observations for the path pattern
218
+ if observations and isinstance(observations, str):
219
+ # This regex should match paths printed by your create_document tool
220
+ path_match = re.search(r"(/tmp/[a-zA-Z0-9_]+/generated_document\.(?:docx|pdf|txt))", observations)
221
+ if path_match:
222
+ extracted_path = path_match.group(1)
223
+ normalized_path = os.path.normpath(extracted_path)
224
+ if os.path.exists(normalized_path):
225
+ self._latest_file_path_for_download = normalized_path
226
+ print(f"DEBUG Gradio UI: File path for download set (from observations): {self._latest_file_path_for_download}")
227
+ return True
228
+ else:
229
+ print(f"DEBUG Gradio UI: Path from observations ('{normalized_path}') does not exist.")
230
+ print("DEBUG Gradio UI: No valid generated file path found in agent logs for download.")
 
 
 
231
  return False
232
 
233
+ def interact_with_agent(self, prompt_text: str, current_chat_history: list):
 
 
 
 
234
  print(f"DEBUG Gradio: interact_with_agent called with prompt: '{prompt_text}'")
235
+ print(f"DEBUG Gradio: Current chat history (input type {type(current_chat_history)}): {current_chat_history}")
236
 
237
+ # current_chat_history from gr.Chatbot(type="messages") is already a list of dicts
238
+ updated_chat_history = current_chat_history + [{"role": "user", "content": prompt_text}]
239
 
240
+ yield updated_chat_history, gr.update(visible=False), gr.update(value=None, visible=False)
 
241
 
 
242
  agent_responses_for_history = []
243
  for msg_dict in stream_to_gradio(self.agent, task=prompt_text, reset_agent_memory=False):
244
  agent_responses_for_history.append(msg_dict)
245
+ yield updated_chat_history + agent_responses_for_history, gr.update(visible=False), gr.update(value=None, visible=False)
 
246
 
 
247
  file_found = self._check_for_created_file()
248
 
249
+ final_chat_display = updated_chat_history + agent_responses_for_history
250
+ print(f"DEBUG Gradio: Final chat history for display: {len(final_chat_display)} messages.")
 
251
  yield final_chat_display, gr.update(visible=file_found), gr.update(value=None, visible=False)
252
 
 
253
  def upload_file(self, file, file_uploads_log_state):
254
+ if file is None:
255
  return gr.update(value="No file uploaded.", visible=True), file_uploads_log_state
256
 
 
257
  if not self.file_upload_folder or not os.path.exists(self.file_upload_folder):
258
+ os.makedirs(self.file_upload_folder, exist_ok=True)
259
 
260
  allowed_file_types = [
261
  "application/pdf",
262
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
263
+ "text/plain", "image/jpeg", "image/png",
 
264
  ]
265
 
266
+ original_name = file.orig_name if hasattr(file, 'orig_name') and file.orig_name else os.path.basename(file.name)
 
267
 
 
268
  mime_type, _ = mimetypes.guess_type(file.name)
269
+ if mime_type is None:
270
  mime_type, _ = mimetypes.guess_type(original_name)
271
 
272
  if mime_type not in allowed_file_types:
 
275
  sanitized_name = re.sub(r"[^\w\-.]", "_", original_name)
276
  base_name, current_ext = os.path.splitext(sanitized_name)
277
 
278
+ # Updated mimetypes to extension mapping
279
+ common_mime_to_ext = {
280
  "application/pdf": ".pdf",
281
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx",
282
  "text/plain": ".txt", "image/jpeg": ".jpg", "image/png": ".png"
283
+ }
284
+ expected_ext = common_mime_to_ext.get(mime_type)
285
 
286
  if expected_ext and current_ext.lower() != expected_ext.lower():
287
  sanitized_name = base_name + expected_ext
 
289
  destination_path = os.path.join(self.file_upload_folder, sanitized_name)
290
 
291
  try:
292
+ shutil.copy(file.name, destination_path)
293
  print(f"DEBUG Gradio: File '{original_name}' copied to '{destination_path}'")
294
  updated_log = file_uploads_log_state + [destination_path]
295
+ return gr.update(value=f"Uploaded: {original_name}", visible=True), updated_log
296
  except Exception as e:
297
  print(f"DEBUG Gradio: Error copying uploaded file: {e}")
298
  return gr.update(value=f"Error uploading {original_name}: {e}", visible=True), file_uploads_log_state
299
 
 
300
  def log_user_message(self, text_input_value: str, current_file_uploads: list):
301
  full_prompt = text_input_value
302
  if current_file_uploads:
303
  files_str = ", ".join([os.path.basename(f) for f in current_file_uploads])
304
  full_prompt += f"\n\n[Uploaded files for context: {files_str}]"
305
+ print(f"DEBUG Gradio: Prepared prompt for agent: {full_prompt[:300]}...") # Log snippet
306
+ return full_prompt, ""
307
 
308
  def prepare_and_show_download_file(self):
309
  if self._latest_file_path_for_download and os.path.exists(self._latest_file_path_for_download):
 
313
  visible=True)
314
  else:
315
  print("DEBUG Gradio UI: No valid file path to prepare for download component.")
316
+ # gr.Warning("No file available for download or path is invalid.") # Causes JS error if used as return
317
+ return gr.File.update(visible=False, value=None) # Ensure value is None if not visible
318
 
319
  def launch(self, **kwargs):
320
  with gr.Blocks(fill_height=True, theme=gr.themes.Soft(primary_hue=gr.themes.colors.blue)) as demo:
321
  file_uploads_log_state = gr.State([])
322
  prepared_prompt_for_agent = gr.State("")
323
 
324
+ gr.Markdown("## Smol Talk with your Agent") # Changed title slightly
325
 
326
+ with gr.Row(equal_height=False): # Allow columns to size independently
327
  with gr.Column(scale=3):
328
  chatbot_display = gr.Chatbot(
329
  label="Agent Interaction",
330
  type="messages",
331
  avatar_images=(None, "https://huggingface.co/datasets/huggingface/brand-assets/resolve/main/hf-logo-round.png"),
332
+ height=700, # Increased height
333
  show_copy_button=True,
334
+ bubble_full_width=False,
335
+ show_label=False # Hide the "Agent Interaction" label above chatbot
336
  )
337
  text_message_input = gr.Textbox(
338
  lines=1,
339
  label="Your Message to the Agent",
340
+ placeholder="Type your message and press Enter, or Shift+Enter for new line...",
341
+ show_label=False # Hide label for text input
342
  )
343
 
344
  with gr.Column(scale=1):
345
  if self.file_upload_folder is not None:
346
+ with gr.Accordion("File Upload", open=False): # Collapsible section
347
+ file_uploader = gr.File(label="Upload a supporting file (PDF, DOCX, TXT, JPG, PNG)")
348
+ upload_status_text = gr.Textbox(label="Upload Status", interactive=False, lines=1) # single line
349
+ file_uploader.upload( # Changed from .change to .upload for gr.File
350
+ self.upload_file,
351
+ [file_uploader, file_uploads_log_state],
352
+ [upload_status_text, file_uploads_log_state],
353
+ )
354
 
355
+ with gr.Accordion("Generated File", open=True): # Collapsible, open by default
356
+ download_action_button = gr.Button("Download Generated File", visible=False)
357
+ file_download_display_component = gr.File(label="Downloadable Document", visible=False, interactive=False)
358
 
 
359
  text_message_input.submit(
360
+ self.log_user_message,
361
  [text_message_input, file_uploads_log_state],
362
  [prepared_prompt_for_agent, text_message_input]
363
  ).then(
364
+ self.interact_with_agent,
365
+ [prepared_prompt_for_agent, chatbot_display], # chatbot_display is input here
366
+ [chatbot_display, download_action_button, file_download_display_component] # chatbot_display is output here
367
  )
368
 
369
  download_action_button.click(
 
371
  [],
372
  [file_download_display_component]
373
  )
374
+ # Default share=False, can be overridden by kwargs
375
  demo.launch(debug=True, share=kwargs.get("share", False), **kwargs)
376
 
377
  __all__ = ["stream_to_gradio", "GradioUI"]