Firoj112 commited on
Commit
69dbdbd
·
verified ·
1 Parent(s): e6b4f96

Create GRADIO_UI.py

Browse files
Files changed (1) hide show
  1. GRADIO_UI.py +295 -0
GRADIO_UI.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
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
23
+ 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)
45
+ model_output = re.sub(r"<end_code>\s*```", "```", model_output)
46
+ model_output = re.sub(r"```\s*\n\s*<end_code>", "```", model_output)
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
+ args = first_tool_call.arguments
58
+ if isinstance(args, dict):
59
+ content = str(args.get("answer", str(args)))
60
+ else:
61
+ content = str(args).strip()
62
+
63
+ if used_code:
64
+ content = re.sub(r"```.*?\n", "", content)
65
+ content = re.sub(r"\s*<end_code>\s*", "", content)
66
+ content = content.strip()
67
+ if not content.startswith("```python"):
68
+ content = f"```python\n{content}\n```"
69
+
70
+ parent_message_tool = gr.ChatMessage(
71
+ role="assistant",
72
+ content=content,
73
+ metadata={
74
+ "title": f"🛠️ Used tool {first_tool_call.name}",
75
+ "id": parent_id,
76
+ "status": "pending",
77
+ },
78
+ )
79
+ yield parent_message_tool
80
+
81
+ # Nesting execution logs under the tool call if they exist
82
+ if hasattr(step_log, "observations") and (
83
+ step_log.observations is not None and step_log.observations.strip()
84
+ ):
85
+ log_content = step_log.observations.strip()
86
+ if log_content:
87
+ log_content = re.sub(r"^Execution logs:\s*", "", log_content)
88
+ yield gr.ChatMessage(
89
+ role="assistant",
90
+ content=f"{log_content}",
91
+ metadata={"title": "📝 Execution Logs", "parent_id": parent_id, "status": "done"},
92
+ )
93
+
94
+ # Nesting any errors under the tool call
95
+ if hasattr(step_log, "error") and step_log.error is not None:
96
+ yield gr.ChatMessage(
97
+ role="assistant",
98
+ content=str(step_log.error),
99
+ metadata={"title": "💥 Error", "parent_id": parent_id, "status": "done"},
100
+ )
101
+
102
+ # Update parent message metadata to done status without yielding a new message
103
+ parent_message_tool.metadata["status"] = "done"
104
+
105
+ # Handle standalone errors but not from tool calls
106
+ elif hasattr(step_log, "error") and step_log.error is not None:
107
+ yield gr.ChatMessage(role="assistant", content=str(step_log.error), metadata={"title": "💥 Error"})
108
+
109
+ # Calculate duration and token information
110
+ step_footnote = f"{step_number}"
111
+ if hasattr(step_log, "input_token_count") and hasattr(step_log, "output_token_count"):
112
+ token_str = (
113
+ f" | Input-tokens:{step_log.input_token_count:,} | Output-tokens:{step_log.output_token_count:,}"
114
+ )
115
+ step_footnote += token_str
116
+ if hasattr(step_log, "duration"):
117
+ step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else None
118
+ step_footnote += step_duration
119
+ step_footnote = f"""<span style="color: #bbbbc2; font-size: 12px;">{step_footnote}</span> """
120
+ yield gr.ChatMessage(role="assistant", content=f"{step_footnote}")
121
+ yield gr.ChatMessage(role="assistant", content="-----")
122
+
123
+ # Handle screenshot if present in observations
124
+ if hasattr(step_log, "observations") and step_log.observations:
125
+ for line in step_log.observations.split("\n"):
126
+ if line.startswith("Screenshot saved at:"):
127
+ screenshot_path = line.replace("Screenshot saved at: ", "").strip()
128
+ yield gr.ChatMessage(
129
+ role="assistant",
130
+ content={"path": screenshot_path, "mime_type": "image/png"},
131
+ metadata={"title": "📸 Screenshot"}
132
+ )
133
+
134
+
135
+ def stream_to_gradio(
136
+ agent,
137
+ task: str,
138
+ reset_agent_memory: bool = False,
139
+ additional_args: Optional[dict] = None,
140
+ ):
141
+ """Runs an agent with the given task and streams the messages from the agent as gradio ChatMessages."""
142
+ if not _is_package_available("gradio"):
143
+ raise ModuleNotFoundError(
144
+ "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
145
+ )
146
+ import gradio as gr
147
+
148
+ total_input_tokens = 0
149
+ total_output_tokens = 0
150
+
151
+ for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):
152
+ if hasattr(agent.model, "last_input_token_count"):
153
+ total_input_tokens += agent.model.last_input_token_count
154
+ total_output_tokens += agent.model.last_output_token_count
155
+ if isinstance(step_log, ActionStep):
156
+ step_log.input_token_count = agent.model.last_input_token_count
157
+ step_log.output_token_count = agent.model.last_output_token_count
158
+
159
+ for message in pull_messages_from_step(
160
+ step_log,
161
+ ):
162
+ yield message
163
+
164
+ final_answer = step_log
165
+ final_answer = handle_agent_output_types(final_answer)
166
+
167
+ if isinstance(final_answer, AgentText):
168
+ yield gr.ChatMessage(
169
+ role="assistant",
170
+ content=f"**Final answer:**\n{final_answer.to_string()}\n",
171
+ )
172
+ elif isinstance(final_answer, AgentImage):
173
+ yield gr.ChatMessage(
174
+ role="assistant",
175
+ content={"path": final_answer.to_string(), "mime_type": "image/png"},
176
+ )
177
+ elif isinstance(final_answer, AgentAudio):
178
+ yield gr.ChatMessage(
179
+ role="assistant",
180
+ content={"path": final_answer.to_string(), "mime_type": "audio/wav"},
181
+ )
182
+ else:
183
+ yield gr.ChatMessage(role="assistant", content=f"**Final answer:** {str(final_answer)}")
184
+
185
+
186
+ class GradioUI:
187
+ """A one-line interface to launch your agent in Gradio"""
188
+
189
+ def __init__(self, agent: MultiStepAgent, file_upload_folder: str | None = None):
190
+ if not _is_package_available("gradio"):
191
+ raise ModuleNotFoundError(
192
+ "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
193
+ )
194
+ self.agent = agent
195
+ self.file_upload_folder = file_upload_folder
196
+ if self.file_upload_folder is not None:
197
+ if not os.path.exists(file_upload_folder):
198
+ os.mkdir(file_upload_folder)
199
+
200
+ def interact_with_agent(self, prompt, messages):
201
+ import gradio as gr
202
+
203
+ messages.append(gr.ChatMessage(role="user", content=prompt))
204
+ yield messages
205
+ for msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):
206
+ messages.append(msg)
207
+ yield messages
208
+ yield messages
209
+
210
+ def upload_file(
211
+ self,
212
+ file,
213
+ file_uploads_log,
214
+ allowed_file_types=[
215
+ "application/pdf",
216
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
217
+ "text/plain",
218
+ ],
219
+ ):
220
+ import gradio as gr
221
+
222
+ if file is None:
223
+ return gr.Textbox("No file uploaded", visible=True), file_uploads_log
224
+
225
+ try:
226
+ mime_type, _ = mimetypes.guess_type(file.name)
227
+ except Exception as e:
228
+ return gr.Textbox(f"Error: {e}", visible=True), file_uploads_log
229
+
230
+ if mime_type not in allowed_file_types:
231
+ return gr.Textbox("File type disallowed", visible=True), file_uploads_log
232
+
233
+ original_name = os.path.basename(file.name)
234
+ sanitized_name = re.sub(r"[^\w\-.]", "_", original_name)
235
+
236
+ type_to_ext = {}
237
+ for ext, t in mimetypes.types_map.items():
238
+ if t not in type_to_ext:
239
+ type_to_ext[t] = ext
240
+
241
+ sanitized_name = sanitized_name.split(".")[:-1]
242
+ sanitized_name.append("" + type_to_ext[mime_type])
243
+ sanitized_name = "".join(sanitized_name)
244
+
245
+ file_path = os.path.join(self.file_upload_folder, os.path.basename(sanitized_name))
246
+ shutil.copy(file.name, file_path)
247
+
248
+ return gr.Textbox(f"File uploaded: {file_path}", visible=True), file_uploads_log + [file_path]
249
+
250
+ def log_user_message(self, text_input, file_uploads_log):
251
+ return (
252
+ text_input
253
+ + (
254
+ f"\nYou have been provided with these files, which might be helpful or not: {file_uploads_log}"
255
+ if len(file_uploads_log) > 0
256
+ else ""
257
+ ),
258
+ "",
259
+ )
260
+
261
+ def launch(self, **kwargs):
262
+ import gradio as gr
263
+
264
+ with gr.Blocks(fill_height=True) as demo:
265
+ stored_messages = gr.State([])
266
+ file_uploads_log = gr.State([])
267
+ chatbot = gr.Chatbot(
268
+ label="Web Navigation Agent",
269
+ type="messages",
270
+ avatar_images=(
271
+ None,
272
+ "https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/Alfred.png",
273
+ ),
274
+ resizeable=True,
275
+ scale=1,
276
+ )
277
+ if self.file_upload_folder is not None:
278
+ upload_file = gr.File(label="Upload a file")
279
+ upload_status = gr.Textbox(label="Upload Status", interactive=False, visible=False)
280
+ upload_file.change(
281
+ self.upload_file,
282
+ [upload_file, file_uploads_log],
283
+ [upload_status, file_uploads_log],
284
+ )
285
+ text_input = gr.Textbox(lines=1, label="Enter URL and request (e.g., https://github.com Click on Developers)")
286
+ text_input.submit(
287
+ self.log_user_message,
288
+ [text_input, file_uploads_log],
289
+ [stored_messages, text_input],
290
+ ).then(self.interact_with_agent, [stored_messages, chatbot], [chatbot])
291
+
292
+ demo.launch(debug=True, **kwargs)
293
+
294
+
295
+ __all__ = ["stream_to_gradio", "GradioUI"]