Tbaberca commited on
Commit
719280c
·
verified ·
1 Parent(s): 2c8a37c

Update Gradio_UI.py

Browse files
Files changed (1) hide show
  1. Gradio_UI.py +1 -172
Gradio_UI.py CHANGED
@@ -129,175 +129,4 @@ def stream_to_gradio(
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
147
- if isinstance(step_log, ActionStep):
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
- yield gr.ChatMessage(
166
- role="assistant",
167
- content={"path": final_answer.to_string(), "mime_type": "image/png"},
168
- )
169
- elif isinstance(final_answer, AgentAudio):
170
- yield gr.ChatMessage(
171
- role="assistant",
172
- content={"path": final_answer.to_string(), "mime_type": "audio/wav"},
173
- )
174
- else:
175
- yield gr.ChatMessage(role="assistant", content=f"**Final answer:** {str(final_answer)}")
176
-
177
-
178
- class GradioUI:
179
- def __init__(self, agent):
180
- self.agent = agent
181
-
182
- def launch(self, share=False, **kwargs):
183
- import gradio as gr
184
-
185
- # Your interface setup here
186
- with gr.Blocks() as demo:
187
- gr.Markdown("### Welcome to the AI Agent UI")
188
- inp = gr.Textbox(label="Input")
189
- out = gr.Textbox(label="Output")
190
-
191
- def respond(message):
192
- return self.agent.run(message)
193
-
194
- btn = gr.Button("Submit")
195
- btn.click(fn=respond, inputs=inp, outputs=out)
196
-
197
- demo.launch(debug=True, share=share, **kwargs)
198
-
199
- def interact_with_agent(self, prompt, messages):
200
- import gradio as gr
201
-
202
- messages.append(gr.ChatMessage(role="user", content=prompt))
203
- yield messages
204
- for msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):
205
- messages.append(msg)
206
- yield messages
207
- yield messages
208
-
209
- def upload_file(
210
- self,
211
- file,
212
- file_uploads_log,
213
- allowed_file_types=[
214
- "application/pdf",
215
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
216
- "text/plain",
217
- ],
218
- ):
219
- """
220
- Handle file uploads, default allowed types are .pdf, .docx, and .txt
221
- """
222
- import gradio as gr
223
-
224
- if file is None:
225
- return gr.Textbox("No file uploaded", visible=True), file_uploads_log
226
-
227
- try:
228
- mime_type, _ = mimetypes.guess_type(file.name)
229
- except Exception as e:
230
- return gr.Textbox(f"Error: {e}", visible=True), file_uploads_log
231
-
232
- if mime_type not in allowed_file_types:
233
- return gr.Textbox("File type disallowed", visible=True), file_uploads_log
234
-
235
- # Sanitize file name
236
- original_name = os.path.basename(file.name)
237
- sanitized_name = re.sub(
238
- r"[^\w\-.]", "_", original_name
239
- ) # Replace any non-alphanumeric, non-dash, or non-dot characters with underscores
240
-
241
- type_to_ext = {}
242
- for ext, t in mimetypes.types_map.items():
243
- if t not in type_to_ext:
244
- type_to_ext[t] = ext
245
-
246
- # Ensure the extension correlates to the mime type
247
- sanitized_name = sanitized_name.split(".")[:-1]
248
- sanitized_name.append("" + type_to_ext[mime_type])
249
- sanitized_name = "".join(sanitized_name)
250
-
251
- # Save the uploaded file to the specified folder
252
- file_path = os.path.join(self.file_upload_folder, os.path.basename(sanitized_name))
253
- shutil.copy(file.name, file_path)
254
-
255
- return gr.Textbox(f"File uploaded: {file_path}", visible=True), file_uploads_log + [file_path]
256
-
257
- def log_user_message(self, text_input, file_uploads_log):
258
- return (
259
- text_input
260
- + (
261
- f"\nYou have been provided with these files, which might be helpful or not: {file_uploads_log}"
262
- if len(file_uploads_log) > 0
263
- else ""
264
- ),
265
- "",
266
- )
267
-
268
- def launch(self, **kwargs):
269
- import gradio as gr
270
-
271
- with gr.Blocks(fill_height=True) as demo:
272
- stored_messages = gr.State([])
273
- file_uploads_log = gr.State([])
274
- chatbot = gr.Chatbot(
275
- label="Agent",
276
- type="messages",
277
- avatar_images=(
278
- None,
279
- "https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/Alfred.png",
280
- ),
281
- resizeable=True,
282
- scale=1,
283
- )
284
- # If an upload folder is provided, enable the upload feature
285
- if self.file_upload_folder is not None:
286
- upload_file = gr.File(label="Upload a file")
287
- upload_status = gr.Textbox(label="Upload Status", interactive=False, visible=False)
288
- upload_file.change(
289
- self.upload_file,
290
- [upload_file, file_uploads_log],
291
- [upload_status, file_uploads_log],
292
- )
293
- text_input = gr.Textbox(lines=1, label="Chat Message")
294
- text_input.submit(
295
- self.log_user_message,
296
- [text_input, file_uploads_log],
297
- [stored_messages, text_input],
298
- ).then(self.interact_with_agent, [stored_messages, chatbot], [chatbot])
299
-
300
- demo.launch(debug=True, share=True, **kwargs)
301
-
302
-
303
- __all__ = ["stream_to_gradio", "GradioUI"]
 
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 ChatMes