Erfan97 commited on
Commit
81cd6fc
·
verified ·
1 Parent(s): e80e5fd

Update Gradio_UI.py

Browse files
Files changed (1) hide show
  1. Gradio_UI.py +82 -76
Gradio_UI.py CHANGED
@@ -13,10 +13,12 @@
13
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
  # See the License for the specific language governing permissions and
15
  # limitations under the License.
 
16
  import mimetypes
17
  import os
18
  import re
19
  import shutil
 
20
  from typing import Optional
21
 
22
  from smolagents.agent_types import AgentAudio, AgentImage, AgentText, handle_agent_output_types
@@ -25,36 +27,27 @@ from smolagents.memory import MemoryStep
25
  from smolagents.utils import _is_package_available
26
 
27
 
28
- def pull_messages_from_step(
29
- step_log: MemoryStep,
30
- ):
31
  """Extract ChatMessage objects from agent steps with proper nesting"""
32
  import gradio as gr
33
 
34
  if isinstance(step_log, ActionStep):
35
- # Output the step number
36
  step_number = f"Step {step_log.step_number}" if step_log.step_number is not None else ""
37
  yield gr.ChatMessage(role="assistant", content=f"**{step_number}**")
38
 
39
- # First yield the thought/reasoning from the LLM
40
  if hasattr(step_log, "model_output") and step_log.model_output is not None:
41
- # Clean up the LLM output
42
  model_output = step_log.model_output.strip()
43
- # Remove any trailing <end_code> and extra backticks, handling multiple possible formats
44
- model_output = re.sub(r"```\s*<end_code>", "```", model_output) # handles ```<end_code>
45
- model_output = re.sub(r"<end_code>\s*```", "```", model_output) # handles <end_code>```
46
- model_output = re.sub(r"```\s*\n\s*<end_code>", "```", model_output) # handles ```\n<end_code>
47
  model_output = model_output.strip()
48
  yield gr.ChatMessage(role="assistant", content=model_output)
49
 
50
- # For tool calls, create a parent message
51
  if hasattr(step_log, "tool_calls") and step_log.tool_calls is not None:
52
  first_tool_call = step_log.tool_calls[0]
53
  used_code = first_tool_call.name == "python_interpreter"
54
  parent_id = f"call_{len(step_log.tool_calls)}"
55
 
56
- # Tool call becomes the parent message with timing info
57
- # First we will handle arguments based on type
58
  args = first_tool_call.arguments
59
  if isinstance(args, dict):
60
  content = str(args.get("answer", str(args)))
@@ -62,9 +55,8 @@ def pull_messages_from_step(
62
  content = str(args).strip()
63
 
64
  if used_code:
65
- # Clean up the content by removing any end code tags
66
- content = re.sub(r"```.*?\n", "", content) # Remove existing code blocks
67
- content = re.sub(r"\s*<end_code>\s*", "", content) # Remove end_code tags
68
  content = content.strip()
69
  if not content.startswith("```python"):
70
  content = f"```python\n{content}\n```"
@@ -80,10 +72,9 @@ def pull_messages_from_step(
80
  )
81
  yield parent_message_tool
82
 
83
- # Nesting execution logs under the tool call if they exist
84
  if hasattr(step_log, "observations") and (
85
  step_log.observations is not None and step_log.observations.strip()
86
- ): # Only yield execution logs if there's actual content
87
  log_content = step_log.observations.strip()
88
  if log_content:
89
  log_content = re.sub(r"^Execution logs:\s*", "", log_content)
@@ -93,7 +84,6 @@ def pull_messages_from_step(
93
  metadata={"title": "📝 Execution Logs", "parent_id": parent_id, "status": "done"},
94
  )
95
 
96
- # Nesting any errors under the tool call
97
  if hasattr(step_log, "error") and step_log.error is not None:
98
  yield gr.ChatMessage(
99
  role="assistant",
@@ -101,14 +91,11 @@ def pull_messages_from_step(
101
  metadata={"title": "💥 Error", "parent_id": parent_id, "status": "done"},
102
  )
103
 
104
- # Update parent message metadata to done status without yielding a new message
105
  parent_message_tool.metadata["status"] = "done"
106
 
107
- # Handle standalone errors but not from tool calls
108
  elif hasattr(step_log, "error") and step_log.error is not None:
109
  yield gr.ChatMessage(role="assistant", content=str(step_log.error), metadata={"title": "💥 Error"})
110
 
111
- # Calculate duration and token information
112
  step_footnote = f"{step_number}"
113
  if hasattr(step_log, "input_token_count") and hasattr(step_log, "output_token_count"):
114
  token_str = (
@@ -118,17 +105,68 @@ def pull_messages_from_step(
118
  if hasattr(step_log, "duration"):
119
  step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else None
120
  step_footnote += step_duration
 
121
  step_footnote = f"""<span style="color: #bbbbc2; font-size: 12px;">{step_footnote}</span> """
122
  yield gr.ChatMessage(role="assistant", content=f"{step_footnote}")
123
  yield gr.ChatMessage(role="assistant", content="-----")
124
 
125
 
126
- def stream_to_gradio(
127
- agent,
128
- task: str,
129
- reset_agent_memory: bool = False,
130
- additional_args: Optional[dict] = None,
131
- ):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  """Runs an agent with the given task and streams the messages from the agent as gradio ChatMessages."""
133
  if not _is_package_available("gradio"):
134
  raise ModuleNotFoundError(
@@ -140,7 +178,6 @@ def stream_to_gradio(
140
  total_output_tokens = 0
141
 
142
  for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):
143
- # Track tokens if model provides them
144
  if hasattr(agent.model, "last_input_token_count"):
145
  total_input_tokens += agent.model.last_input_token_count
146
  total_output_tokens += agent.model.last_output_token_count
@@ -148,44 +185,22 @@ def stream_to_gradio(
148
  step_log.input_token_count = agent.model.last_input_token_count
149
  step_log.output_token_count = agent.model.last_output_token_count
150
 
151
- for message in pull_messages_from_step(
152
- step_log,
153
- ):
154
  yield message
155
 
156
- final_answer = step_log # Last log is the run's final_answer
157
  final_answer = handle_agent_output_types(final_answer)
158
 
159
  if isinstance(final_answer, AgentText):
160
- yield gr.ChatMessage(
161
- role="assistant",
162
- content=f"**Final answer:**\n{final_answer.to_string()}\n",
163
- )
164
  elif isinstance(final_answer, AgentImage):
165
- img_path = final_answer.to_string()
166
-
167
- # If the returned string isn't a valid file path, save the image ourselves
168
- if not isinstance(img_path, str) or not os.path.exists(img_path):
169
- os.makedirs("generated_images", exist_ok=True)
170
- img_path = os.path.join("generated_images", "generated_image.png")
171
-
172
- # Try to save AgentImage.value (usually PIL image)
173
- try:
174
- final_answer.value.save(img_path)
175
- except Exception:
176
- # Fallback for raw bytes
177
- with open(img_path, "wb") as f:
178
- f.write(final_answer.value)
179
-
180
- yield gr.ChatMessage(
181
- role="assistant",
182
- content={"path": img_path, "mime_type": "image/png"},
183
- )
184
  elif isinstance(final_answer, AgentAudio):
185
- yield gr.ChatMessage(
186
- role="assistant",
187
- content={"path": final_answer.to_string(), "mime_type": "audio/wav"},
188
- )
189
  else:
190
  yield gr.ChatMessage(role="assistant", content=f"**Final answer:** {str(final_answer)}")
191
 
@@ -206,7 +221,6 @@ class GradioUI:
206
 
207
  def interact_with_agent(self, prompt, messages):
208
  import gradio as gr
209
-
210
  messages.append(gr.ChatMessage(role="user", content=prompt))
211
  yield messages
212
  for msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):
@@ -224,9 +238,7 @@ class GradioUI:
224
  "text/plain",
225
  ],
226
  ):
227
- """
228
- Handle file uploads, default allowed types are .pdf, .docx, and .txt
229
- """
230
  import gradio as gr
231
 
232
  if file is None:
@@ -240,23 +252,18 @@ class GradioUI:
240
  if mime_type not in allowed_file_types:
241
  return gr.Textbox("File type disallowed", visible=True), file_uploads_log
242
 
243
- # Sanitize file name
244
  original_name = os.path.basename(file.name)
245
- sanitized_name = re.sub(
246
- r"[^\w\-.]", "_", original_name
247
- ) # Replace any non-alphanumeric, non-dash, or non-dot characters with underscores
248
 
249
  type_to_ext = {}
250
  for ext, t in mimetypes.types_map.items():
251
  if t not in type_to_ext:
252
  type_to_ext[t] = ext
253
 
254
- # Ensure the extension correlates to the mime type
255
  sanitized_name = sanitized_name.split(".")[:-1]
256
  sanitized_name.append("" + type_to_ext[mime_type])
257
  sanitized_name = "".join(sanitized_name)
258
 
259
- # Save the uploaded file to the specified folder
260
  file_path = os.path.join(self.file_upload_folder, os.path.basename(sanitized_name))
261
  shutil.copy(file.name, file_path)
262
 
@@ -275,7 +282,7 @@ class GradioUI:
275
 
276
  def launch(self, **kwargs):
277
  import gradio as gr
278
-
279
  with gr.Blocks(fill_height=True) as demo:
280
  stored_messages = gr.State([])
281
  file_uploads_log = gr.State([])
@@ -289,7 +296,7 @@ class GradioUI:
289
  resizable=True,
290
  scale=1,
291
  )
292
-
293
  if self.file_upload_folder is not None:
294
  upload_file = gr.File(label="Upload a file")
295
  upload_status = gr.Textbox(label="Upload Status", interactive=False, visible=False)
@@ -298,18 +305,17 @@ class GradioUI:
298
  [upload_file, file_uploads_log],
299
  [upload_status, file_uploads_log],
300
  )
301
-
302
  text_input = gr.Textbox(lines=1, label="Chat Message")
303
  text_input.submit(
304
  self.log_user_message,
305
  [text_input, file_uploads_log],
306
  [stored_messages, text_input],
307
  ).then(self.interact_with_agent, [stored_messages, chatbot], [chatbot])
308
-
309
  # Disable share on Spaces automatically
310
  is_spaces = os.environ.get("SPACE_ID") is not None
311
  demo.launch(debug=True, share=not is_spaces, **kwargs)
312
 
313
 
314
-
315
- __all__ = ["stream_to_gradio", "GradioUI"]
 
13
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
  # See the License for the specific language governing permissions and
15
  # limitations under the License.
16
+
17
  import mimetypes
18
  import os
19
  import re
20
  import shutil
21
+ import uuid
22
  from typing import Optional
23
 
24
  from smolagents.agent_types import AgentAudio, AgentImage, AgentText, handle_agent_output_types
 
27
  from smolagents.utils import _is_package_available
28
 
29
 
30
+ def pull_messages_from_step(step_log: MemoryStep):
 
 
31
  """Extract ChatMessage objects from agent steps with proper nesting"""
32
  import gradio as gr
33
 
34
  if isinstance(step_log, ActionStep):
 
35
  step_number = f"Step {step_log.step_number}" if step_log.step_number is not None else ""
36
  yield gr.ChatMessage(role="assistant", content=f"**{step_number}**")
37
 
 
38
  if hasattr(step_log, "model_output") and step_log.model_output is not None:
 
39
  model_output = step_log.model_output.strip()
40
+ model_output = re.sub(r"```\s*<end_code>", "```", model_output)
41
+ model_output = re.sub(r"<end_code>\s*```", "```", model_output)
42
+ model_output = re.sub(r"```\s*\n\s*<end_code>", "```", model_output)
 
43
  model_output = model_output.strip()
44
  yield gr.ChatMessage(role="assistant", content=model_output)
45
 
 
46
  if hasattr(step_log, "tool_calls") and step_log.tool_calls is not None:
47
  first_tool_call = step_log.tool_calls[0]
48
  used_code = first_tool_call.name == "python_interpreter"
49
  parent_id = f"call_{len(step_log.tool_calls)}"
50
 
 
 
51
  args = first_tool_call.arguments
52
  if isinstance(args, dict):
53
  content = str(args.get("answer", str(args)))
 
55
  content = str(args).strip()
56
 
57
  if used_code:
58
+ content = re.sub(r"```.*?\n", "", content)
59
+ content = re.sub(r"\s*<end_code>\s*", "", content)
 
60
  content = content.strip()
61
  if not content.startswith("```python"):
62
  content = f"```python\n{content}\n```"
 
72
  )
73
  yield parent_message_tool
74
 
 
75
  if hasattr(step_log, "observations") and (
76
  step_log.observations is not None and step_log.observations.strip()
77
+ ):
78
  log_content = step_log.observations.strip()
79
  if log_content:
80
  log_content = re.sub(r"^Execution logs:\s*", "", log_content)
 
84
  metadata={"title": "📝 Execution Logs", "parent_id": parent_id, "status": "done"},
85
  )
86
 
 
87
  if hasattr(step_log, "error") and step_log.error is not None:
88
  yield gr.ChatMessage(
89
  role="assistant",
 
91
  metadata={"title": "💥 Error", "parent_id": parent_id, "status": "done"},
92
  )
93
 
 
94
  parent_message_tool.metadata["status"] = "done"
95
 
 
96
  elif hasattr(step_log, "error") and step_log.error is not None:
97
  yield gr.ChatMessage(role="assistant", content=str(step_log.error), metadata={"title": "💥 Error"})
98
 
 
99
  step_footnote = f"{step_number}"
100
  if hasattr(step_log, "input_token_count") and hasattr(step_log, "output_token_count"):
101
  token_str = (
 
105
  if hasattr(step_log, "duration"):
106
  step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else None
107
  step_footnote += step_duration
108
+
109
  step_footnote = f"""<span style="color: #bbbbc2; font-size: 12px;">{step_footnote}</span> """
110
  yield gr.ChatMessage(role="assistant", content=f"{step_footnote}")
111
  yield gr.ChatMessage(role="assistant", content="-----")
112
 
113
 
114
+ def _save_agent_image(final_answer: AgentImage) -> str:
115
+ """
116
+ Convert AgentImage into a real PNG path so Gradio can render it.
117
+ Works for:
118
+ - AgentImage.to_string() returning path
119
+ - PIL Images stored inside .value, .image, .data, .pil_image
120
+ - raw bytes stored inside .value/.data
121
+ """
122
+ os.makedirs("generated_images", exist_ok=True)
123
+
124
+ # If to_string() already points to a valid file, use it
125
+ img_str = final_answer.to_string()
126
+ if isinstance(img_str, str) and os.path.exists(img_str):
127
+ return img_str
128
+
129
+ # Otherwise save it ourselves
130
+ img_path = os.path.join("generated_images", f"image_{uuid.uuid4().hex[:8]}.png")
131
+
132
+ pil_img = None
133
+
134
+ # Try common fields
135
+ for attr in ["value", "image", "data", "pil_image"]:
136
+ if hasattr(final_answer, attr):
137
+ candidate = getattr(final_answer, attr)
138
+ if candidate is None:
139
+ continue
140
+ if hasattr(candidate, "save"): # PIL Image
141
+ pil_img = candidate
142
+ break
143
+
144
+ # Try method
145
+ if pil_img is None and hasattr(final_answer, "to_pil"):
146
+ try:
147
+ pil_img = final_answer.to_pil()
148
+ except Exception:
149
+ pil_img = None
150
+
151
+ if pil_img is not None:
152
+ pil_img.save(img_path)
153
+ return img_path
154
+
155
+ # Fallback: raw bytes
156
+ for attr in ["value", "image", "data"]:
157
+ if hasattr(final_answer, attr):
158
+ candidate = getattr(final_answer, attr)
159
+ if isinstance(candidate, (bytes, bytearray)):
160
+ with open(img_path, "wb") as f:
161
+ f.write(candidate)
162
+ return img_path
163
+
164
+ # If we couldn't save anything, return a placeholder path
165
+ # (Gradio will show broken image, but app won't crash)
166
+ return img_path
167
+
168
+
169
+ def stream_to_gradio(agent, task: str, reset_agent_memory: bool = False, additional_args: Optional[dict] = None):
170
  """Runs an agent with the given task and streams the messages from the agent as gradio ChatMessages."""
171
  if not _is_package_available("gradio"):
172
  raise ModuleNotFoundError(
 
178
  total_output_tokens = 0
179
 
180
  for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):
 
181
  if hasattr(agent.model, "last_input_token_count"):
182
  total_input_tokens += agent.model.last_input_token_count
183
  total_output_tokens += agent.model.last_output_token_count
 
185
  step_log.input_token_count = agent.model.last_input_token_count
186
  step_log.output_token_count = agent.model.last_output_token_count
187
 
188
+ for message in pull_messages_from_step(step_log):
 
 
189
  yield message
190
 
191
+ final_answer = step_log
192
  final_answer = handle_agent_output_types(final_answer)
193
 
194
  if isinstance(final_answer, AgentText):
195
+ yield gr.ChatMessage(role="assistant", content=f"**Final answer:**\n{final_answer.to_string()}\n")
196
+
 
 
197
  elif isinstance(final_answer, AgentImage):
198
+ img_path = _save_agent_image(final_answer)
199
+ yield gr.ChatMessage(role="assistant", content={"path": img_path, "mime_type": "image/png"})
200
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  elif isinstance(final_answer, AgentAudio):
202
+ yield gr.ChatMessage(role="assistant", content={"path": final_answer.to_string(), "mime_type": "audio/wav"})
203
+
 
 
204
  else:
205
  yield gr.ChatMessage(role="assistant", content=f"**Final answer:** {str(final_answer)}")
206
 
 
221
 
222
  def interact_with_agent(self, prompt, messages):
223
  import gradio as gr
 
224
  messages.append(gr.ChatMessage(role="user", content=prompt))
225
  yield messages
226
  for msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):
 
238
  "text/plain",
239
  ],
240
  ):
241
+ """Handle file uploads, default allowed types are .pdf, .docx, and .txt"""
 
 
242
  import gradio as gr
243
 
244
  if file is None:
 
252
  if mime_type not in allowed_file_types:
253
  return gr.Textbox("File type disallowed", visible=True), file_uploads_log
254
 
 
255
  original_name = os.path.basename(file.name)
256
+ sanitized_name = re.sub(r"[^\w\-.]", "_", original_name)
 
 
257
 
258
  type_to_ext = {}
259
  for ext, t in mimetypes.types_map.items():
260
  if t not in type_to_ext:
261
  type_to_ext[t] = ext
262
 
 
263
  sanitized_name = sanitized_name.split(".")[:-1]
264
  sanitized_name.append("" + type_to_ext[mime_type])
265
  sanitized_name = "".join(sanitized_name)
266
 
 
267
  file_path = os.path.join(self.file_upload_folder, os.path.basename(sanitized_name))
268
  shutil.copy(file.name, file_path)
269
 
 
282
 
283
  def launch(self, **kwargs):
284
  import gradio as gr
285
+
286
  with gr.Blocks(fill_height=True) as demo:
287
  stored_messages = gr.State([])
288
  file_uploads_log = gr.State([])
 
296
  resizable=True,
297
  scale=1,
298
  )
299
+
300
  if self.file_upload_folder is not None:
301
  upload_file = gr.File(label="Upload a file")
302
  upload_status = gr.Textbox(label="Upload Status", interactive=False, visible=False)
 
305
  [upload_file, file_uploads_log],
306
  [upload_status, file_uploads_log],
307
  )
308
+
309
  text_input = gr.Textbox(lines=1, label="Chat Message")
310
  text_input.submit(
311
  self.log_user_message,
312
  [text_input, file_uploads_log],
313
  [stored_messages, text_input],
314
  ).then(self.interact_with_agent, [stored_messages, chatbot], [chatbot])
315
+
316
  # Disable share on Spaces automatically
317
  is_spaces = os.environ.get("SPACE_ID") is not None
318
  demo.launch(debug=True, share=not is_spaces, **kwargs)
319
 
320
 
321
+ __all__ = ["stream_to_gradio", "GradioUI"]