jcleee commited on
Commit
4bd057d
·
verified ·
1 Parent(s): c90dd56

Update Gradio_UI.py

Browse files
Files changed (1) hide show
  1. Gradio_UI.py +56 -118
Gradio_UI.py CHANGED
@@ -24,47 +24,32 @@ from smolagents.agents import ActionStep, MultiStepAgent
24
  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)))
61
- else:
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```"
@@ -72,28 +57,18 @@ def pull_messages_from_step(
72
  parent_message_tool = gr.ChatMessage(
73
  role="assistant",
74
  content=content,
75
- metadata={
76
- "title": f"🛠️ Used tool {first_tool_call.name}",
77
- "id": parent_id,
78
- "status": "pending",
79
- },
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)
90
- yield gr.ChatMessage(
91
- role="assistant",
92
- content=f"{log_content}",
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,46 +76,31 @@ 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 = (
115
- f" | Input-tokens:{step_log.input_token_count:,} | Output-tokens:{step_log.output_token_count:,}"
116
- )
117
  step_footnote += token_str
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(
135
- "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
136
- )
137
- import gradio as gr
138
 
 
139
  total_input_tokens = 0
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,18 +108,14 @@ 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
  from smolagents.agents import FinalAnswerStep
157
 
158
- # Safely extract the final output from the last step
159
  if isinstance(step_log, FinalAnswerStep):
160
  final_output = step_log.final_answer
161
  else:
162
- # If not a FinalAnswerStep, fallback to tool_output or tool_calls
163
  final_output = getattr(step_log, "tool_output", None)
164
  if not final_output and hasattr(step_log, "tool_calls"):
165
  for call in step_log.tool_calls:
@@ -167,47 +123,28 @@ def stream_to_gradio(
167
  final_output = call.arguments.get("answer")
168
  break
169
 
170
-
171
  final_output = handle_agent_output_types(final_output)
172
 
173
  if isinstance(final_output, AgentText):
174
- yield gr.ChatMessage(
175
- role="assistant",
176
- content=final_output.to_string().strip(),
177
- )
178
  elif isinstance(final_output, AgentImage):
179
- yield gr.ChatMessage(
180
- role="assistant",
181
- content={"path": final_output.to_string(), "mime_type": "image/png"},
182
- )
183
  elif isinstance(final_output, AgentAudio):
184
- yield gr.ChatMessage(
185
- role="assistant",
186
- content={"path": final_output.to_string(), "mime_type": "audio/wav"},
187
- )
188
  else:
189
  yield gr.ChatMessage(role="assistant", content=str(final_output).strip())
190
 
191
-
192
-
193
-
194
  class GradioUI:
195
- """A one-line interface to launch your agent in Gradio"""
196
-
197
  def __init__(self, agent: MultiStepAgent, file_upload_folder: str | None = None):
198
  if not _is_package_available("gradio"):
199
- raise ModuleNotFoundError(
200
- "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
201
- )
202
  self.agent = agent
203
  self.file_upload_folder = file_upload_folder
204
- if self.file_upload_folder is not None:
205
- if not os.path.exists(file_upload_folder):
206
- os.mkdir(file_upload_folder)
207
 
208
  def interact_with_agent(self, prompt, messages):
209
  import gradio as gr
210
-
211
  messages.append(gr.ChatMessage(role="user", content=prompt))
212
  yield messages
213
  for msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):
@@ -215,21 +152,14 @@ class GradioUI:
215
  yield messages
216
  yield messages
217
 
218
- def upload_file(
219
- self,
220
- file,
221
- file_uploads_log,
222
- allowed_file_types=[
223
- "application/pdf",
224
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
225
- "text/plain",
226
- ],
227
- ):
228
- """
229
- Handle file uploads, default allowed types are .pdf, .docx, and .txt
230
- """
231
  import gradio as gr
232
-
 
 
 
 
 
233
  if file is None:
234
  return gr.Textbox("No file uploaded", visible=True), file_uploads_log
235
 
@@ -241,23 +171,18 @@ class GradioUI:
241
  if mime_type not in allowed_file_types:
242
  return gr.Textbox("File type disallowed", visible=True), file_uploads_log
243
 
244
- # Sanitize file name
245
  original_name = os.path.basename(file.name)
246
- sanitized_name = re.sub(
247
- r"[^\w\-.]", "_", original_name
248
- ) # Replace any non-alphanumeric, non-dash, or non-dot characters with underscores
249
 
250
  type_to_ext = {}
251
  for ext, t in mimetypes.types_map.items():
252
  if t not in type_to_ext:
253
  type_to_ext[t] = ext
254
 
255
- # Ensure the extension correlates to the mime type
256
  sanitized_name = sanitized_name.split(".")[:-1]
257
  sanitized_name.append("" + type_to_ext[mime_type])
258
  sanitized_name = "".join(sanitized_name)
259
 
260
- # Save the uploaded file to the specified folder
261
  file_path = os.path.join(self.file_upload_folder, os.path.basename(sanitized_name))
262
  shutil.copy(file.name, file_path)
263
 
@@ -265,17 +190,16 @@ class GradioUI:
265
 
266
  def log_user_message(self, text_input, file_uploads_log):
267
  return (
268
- text_input
269
- + (
270
  f"\nYou have been provided with these files, which might be helpful or not: {file_uploads_log}"
271
- if len(file_uploads_log) > 0
272
- else ""
273
  ),
274
  "",
275
  )
276
 
277
  def launch(self, **kwargs):
278
  import gradio as gr
 
279
 
280
  with gr.Blocks(fill_height=True) as demo:
281
  stored_messages = gr.State([])
@@ -290,7 +214,7 @@ class GradioUI:
290
  resizeable=True,
291
  scale=1,
292
  )
293
- # If an upload folder is provided, enable the upload feature
294
  if self.file_upload_folder is not None:
295
  upload_file = gr.File(label="Upload a file")
296
  upload_status = gr.Textbox(label="Upload Status", interactive=False, visible=False)
@@ -299,6 +223,7 @@ class GradioUI:
299
  [upload_file, file_uploads_log],
300
  [upload_status, file_uploads_log],
301
  )
 
302
  text_input = gr.Textbox(lines=1, label="Chat Message")
303
  text_input.submit(
304
  self.log_user_message,
@@ -306,7 +231,20 @@ class GradioUI:
306
  [stored_messages, text_input],
307
  ).then(self.interact_with_agent, [stored_messages, chatbot], [chatbot])
308
 
309
- demo.launch(debug=True, share=True, show_error=True, **kwargs)
 
 
 
 
 
 
310
 
 
 
 
 
 
 
 
311
 
312
- __all__ = ["stream_to_gradio", "GradioUI"]
 
24
  from smolagents.memory import MemoryStep
25
  from smolagents.utils import _is_package_available
26
 
27
+ def pull_messages_from_step(step_log: MemoryStep):
 
 
 
 
28
  import gradio as gr
29
 
30
  if isinstance(step_log, ActionStep):
 
31
  step_number = f"Step {step_log.step_number}" if step_log.step_number is not None else ""
32
  yield gr.ChatMessage(role="assistant", content=f"**{step_number}**")
33
 
 
34
  if hasattr(step_log, "model_output") and step_log.model_output is not None:
 
35
  model_output = step_log.model_output.strip()
36
+ model_output = re.sub(r"```\s*<end_code>", "```", model_output)
37
+ model_output = re.sub(r"<end_code>\s*```", "```", model_output)
38
+ model_output = re.sub(r"```\s*\n\s*<end_code>", "```", model_output)
 
39
  model_output = model_output.strip()
40
  yield gr.ChatMessage(role="assistant", content=model_output)
41
 
 
42
  if hasattr(step_log, "tool_calls") and step_log.tool_calls is not None:
43
  first_tool_call = step_log.tool_calls[0]
44
  used_code = first_tool_call.name == "python_interpreter"
45
  parent_id = f"call_{len(step_log.tool_calls)}"
46
 
 
 
47
  args = first_tool_call.arguments
48
+ content = str(args.get("answer", str(args))) if isinstance(args, dict) else str(args).strip()
 
 
 
49
 
50
  if used_code:
51
+ content = re.sub(r"```.*?\n", "", content)
52
+ content = re.sub(r"\s*<end_code>\s*", "", content)
 
53
  content = content.strip()
54
  if not content.startswith("```python"):
55
  content = f"```python\n{content}\n```"
 
57
  parent_message_tool = gr.ChatMessage(
58
  role="assistant",
59
  content=content,
60
+ metadata={"title": f"🛠️ Used tool {first_tool_call.name}", "id": parent_id, "status": "pending"},
 
 
 
 
61
  )
62
  yield parent_message_tool
63
 
64
+ if hasattr(step_log, "observations") and step_log.observations and step_log.observations.strip():
65
+ log_content = re.sub(r"^Execution logs:\s*", "", step_log.observations.strip())
66
+ yield gr.ChatMessage(
67
+ role="assistant",
68
+ content=log_content,
69
+ metadata={"title": "📝 Execution Logs", "parent_id": parent_id, "status": "done"},
70
+ )
71
+
 
 
 
 
 
 
72
  if hasattr(step_log, "error") and step_log.error is not None:
73
  yield gr.ChatMessage(
74
  role="assistant",
 
76
  metadata={"title": "💥 Error", "parent_id": parent_id, "status": "done"},
77
  )
78
 
 
79
  parent_message_tool.metadata["status"] = "done"
80
 
 
81
  elif hasattr(step_log, "error") and step_log.error is not None:
82
  yield gr.ChatMessage(role="assistant", content=str(step_log.error), metadata={"title": "💥 Error"})
83
 
 
84
  step_footnote = f"{step_number}"
85
  if hasattr(step_log, "input_token_count") and hasattr(step_log, "output_token_count"):
86
+ token_str = f" | Input-tokens:{step_log.input_token_count:,} | Output-tokens:{step_log.output_token_count:,}"
 
 
87
  step_footnote += token_str
88
  if hasattr(step_log, "duration"):
89
  step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else None
90
  step_footnote += step_duration
91
+ step_footnote = f'<span style="color: #bbbbc2; font-size: 12px;">{step_footnote}</span> '
92
  yield gr.ChatMessage(role="assistant", content=f"{step_footnote}")
93
  yield gr.ChatMessage(role="assistant", content="-----")
94
 
95
+ def stream_to_gradio(agent, task: str, reset_agent_memory: bool = False, additional_args: Optional[dict] = None):
 
 
 
 
 
 
 
96
  if not _is_package_available("gradio"):
97
+ raise ModuleNotFoundError("Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`")
 
 
 
98
 
99
+ import gradio as gr
100
  total_input_tokens = 0
101
  total_output_tokens = 0
102
 
103
  for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):
 
104
  if hasattr(agent.model, "last_input_token_count"):
105
  total_input_tokens += agent.model.last_input_token_count
106
  total_output_tokens += agent.model.last_output_token_count
 
108
  step_log.input_token_count = agent.model.last_input_token_count
109
  step_log.output_token_count = agent.model.last_output_token_count
110
 
111
+ for message in pull_messages_from_step(step_log):
 
 
112
  yield message
113
 
114
  from smolagents.agents import FinalAnswerStep
115
 
 
116
  if isinstance(step_log, FinalAnswerStep):
117
  final_output = step_log.final_answer
118
  else:
 
119
  final_output = getattr(step_log, "tool_output", None)
120
  if not final_output and hasattr(step_log, "tool_calls"):
121
  for call in step_log.tool_calls:
 
123
  final_output = call.arguments.get("answer")
124
  break
125
 
 
126
  final_output = handle_agent_output_types(final_output)
127
 
128
  if isinstance(final_output, AgentText):
129
+ yield gr.ChatMessage(role="assistant", content=final_output.to_string().strip())
 
 
 
130
  elif isinstance(final_output, AgentImage):
131
+ yield gr.ChatMessage(role="assistant", content={"path": final_output.to_string(), "mime_type": "image/png"})
 
 
 
132
  elif isinstance(final_output, AgentAudio):
133
+ yield gr.ChatMessage(role="assistant", content={"path": final_output.to_string(), "mime_type": "audio/wav"})
 
 
 
134
  else:
135
  yield gr.ChatMessage(role="assistant", content=str(final_output).strip())
136
 
 
 
 
137
  class GradioUI:
 
 
138
  def __init__(self, agent: MultiStepAgent, file_upload_folder: str | None = None):
139
  if not _is_package_available("gradio"):
140
+ raise ModuleNotFoundError("Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`")
 
 
141
  self.agent = agent
142
  self.file_upload_folder = file_upload_folder
143
+ if self.file_upload_folder and not os.path.exists(file_upload_folder):
144
+ os.mkdir(file_upload_folder)
 
145
 
146
  def interact_with_agent(self, prompt, messages):
147
  import gradio as gr
 
148
  messages.append(gr.ChatMessage(role="user", content=prompt))
149
  yield messages
150
  for msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):
 
152
  yield messages
153
  yield messages
154
 
155
+ def upload_file(self, file, file_uploads_log, allowed_file_types=None):
 
 
 
 
 
 
 
 
 
 
 
 
156
  import gradio as gr
157
+ if allowed_file_types is None:
158
+ allowed_file_types = [
159
+ "application/pdf",
160
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
161
+ "text/plain",
162
+ ]
163
  if file is None:
164
  return gr.Textbox("No file uploaded", visible=True), file_uploads_log
165
 
 
171
  if mime_type not in allowed_file_types:
172
  return gr.Textbox("File type disallowed", visible=True), file_uploads_log
173
 
 
174
  original_name = os.path.basename(file.name)
175
+ sanitized_name = re.sub(r"[^\w\-.]", "_", original_name)
 
 
176
 
177
  type_to_ext = {}
178
  for ext, t in mimetypes.types_map.items():
179
  if t not in type_to_ext:
180
  type_to_ext[t] = ext
181
 
 
182
  sanitized_name = sanitized_name.split(".")[:-1]
183
  sanitized_name.append("" + type_to_ext[mime_type])
184
  sanitized_name = "".join(sanitized_name)
185
 
 
186
  file_path = os.path.join(self.file_upload_folder, os.path.basename(sanitized_name))
187
  shutil.copy(file.name, file_path)
188
 
 
190
 
191
  def log_user_message(self, text_input, file_uploads_log):
192
  return (
193
+ text_input + (
 
194
  f"\nYou have been provided with these files, which might be helpful or not: {file_uploads_log}"
195
+ if len(file_uploads_log) > 0 else ""
 
196
  ),
197
  "",
198
  )
199
 
200
  def launch(self, **kwargs):
201
  import gradio as gr
202
+ from submit import main as submit_answers
203
 
204
  with gr.Blocks(fill_height=True) as demo:
205
  stored_messages = gr.State([])
 
214
  resizeable=True,
215
  scale=1,
216
  )
217
+
218
  if self.file_upload_folder is not None:
219
  upload_file = gr.File(label="Upload a file")
220
  upload_status = gr.Textbox(label="Upload Status", interactive=False, visible=False)
 
223
  [upload_file, file_uploads_log],
224
  [upload_status, file_uploads_log],
225
  )
226
+
227
  text_input = gr.Textbox(lines=1, label="Chat Message")
228
  text_input.submit(
229
  self.log_user_message,
 
231
  [stored_messages, text_input],
232
  ).then(self.interact_with_agent, [stored_messages, chatbot], [chatbot])
233
 
234
+ with gr.Row():
235
+ submit_btn = gr.Button("📤 Submit All GAIA Answers")
236
+ submission_status = gr.Textbox(label="Submission Status", interactive=False)
237
+
238
+ def trigger_submission():
239
+ submit_answers()
240
+ return "✅ Submitted to GAIA scoring API"
241
 
242
+ submit_btn.click(
243
+ fn=trigger_submission,
244
+ inputs=[],
245
+ outputs=[submission_status]
246
+ )
247
+
248
+ demo.launch(debug=True, share=True, show_error=True, **kwargs)
249
 
250
+ __all__ = ["stream_to_gradio", "GradioUI"]