yetessam commited on
Commit
4e6dea6
·
verified ·
1 Parent(s): dcd74f0

Delete ui/gradioui.py

Browse files
Files changed (1) hide show
  1. ui/gradioui.py +0 -383
ui/gradioui.py DELETED
@@ -1,383 +0,0 @@
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
-
18
- import os
19
- import re
20
- import shutil
21
- from typing import Optional
22
-
23
- from smolagents.agent_types import AgentAudio, AgentImage, AgentText, handle_agent_output_types
24
- from smolagents.agents import ActionStep, MultiStepAgent
25
- from smolagents.memory import MemoryStep
26
- from smolagents.utils import _is_package_available
27
-
28
-
29
- agent_header = """
30
- # Content Agent
31
-
32
-
33
- Use content agent to determine whether language is polite by passing it text strings.
34
-
35
-
36
- * Checks text and classify whether or not it is polite, somewhat polite, neutral, and impolite.
37
- * Uses Intel's Polite Guard NLP library
38
-
39
-
40
-
41
- """
42
- # * Returns the current time if provided with a timezone.
43
-
44
- section_header = "Section Overview"
45
-
46
-
47
- agent_footer = """
48
- Thanks for trying it out!
49
- """
50
-
51
- def get_examples():
52
-
53
- example_root = os.path.join(os.path.dirname(__file__), "examples")
54
- # Get list of all example text paths
55
- example_files = [os.path.join(example_root, _) for _ in os.listdir(example_root) if _.endswith("txt")]
56
-
57
-
58
- # Read the content of each file (assuming they're text-based PDFs or plain text files)
59
- examples = []
60
-
61
- for file_path in example_files:
62
- example_content = ""
63
- with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
64
- example_content = f.read()
65
-
66
- examples.append(example_content) # Read the content and append it to the list
67
-
68
-
69
- return examples
70
-
71
- def pull_messages_from_step(
72
- step_log: MemoryStep,
73
- ):
74
- """Extract ChatMessage objects from agent steps with proper nesting"""
75
- import gradio as gr
76
-
77
- if isinstance(step_log, ActionStep):
78
- # Output the step number
79
- step_number = f"Step {step_log.step_number}" if step_log.step_number is not None else ""
80
- yield gr.ChatMessage(role="assistant", content=f"**{step_number}**")
81
-
82
- # First yield the thought/reasoning from the LLM
83
- if hasattr(step_log, "model_output") and step_log.model_output is not None:
84
- # Clean up the LLM output
85
- model_output = step_log.model_output.strip()
86
- # Remove any trailing <end_code> and extra backticks, handling multiple possible formats
87
- model_output = re.sub(r"```\s*<end_code>", "```", model_output) # handles ```<end_code>
88
- model_output = re.sub(r"<end_code>\s*```", "```", model_output) # handles <end_code>```
89
- model_output = re.sub(r"```\s*\n\s*<end_code>", "```", model_output) # handles ```\n<end_code>
90
- model_output = model_output.strip()
91
- yield gr.ChatMessage(role="assistant", content=model_output)
92
-
93
- # For tool calls, create a parent message
94
- if hasattr(step_log, "tool_calls") and step_log.tool_calls is not None:
95
- first_tool_call = step_log.tool_calls[0]
96
- used_code = first_tool_call.name == "python_interpreter"
97
- parent_id = f"call_{len(step_log.tool_calls)}"
98
-
99
- # Tool call becomes the parent message with timing info
100
- # First we will handle arguments based on type
101
- args = first_tool_call.arguments
102
- if isinstance(args, dict):
103
- content = str(args.get("answer", str(args)))
104
- else:
105
- content = str(args).strip()
106
-
107
- if used_code:
108
- # Clean up the content by removing any end code tags
109
- content = re.sub(r"```.*?\n", "", content) # Remove existing code blocks
110
- content = re.sub(r"\s*<end_code>\s*", "", content) # Remove end_code tags
111
- content = content.strip()
112
- if not content.startswith("```python"):
113
- content = f"```python\n{content}\n```"
114
-
115
- parent_message_tool = gr.ChatMessage(
116
- role="assistant",
117
- content=content,
118
- metadata={
119
- "title": f"🛠️ Used tool {first_tool_call.name}",
120
- "id": parent_id,
121
- "status": "pending",
122
- },
123
- )
124
- yield parent_message_tool
125
-
126
- # Nesting execution logs under the tool call if they exist
127
- if hasattr(step_log, "observations") and (
128
- step_log.observations is not None and step_log.observations.strip()
129
- ): # Only yield execution logs if there's actual content
130
- log_content = step_log.observations.strip()
131
- if log_content:
132
- log_content = re.sub(r"^Execution logs:\s*", "", log_content)
133
- yield gr.ChatMessage(
134
- role="assistant",
135
- content=f"{log_content}",
136
- metadata={"title": "📝 Execution Logs", "parent_id": parent_id, "status": "done"},
137
- )
138
-
139
- # Nesting any errors under the tool call
140
- if hasattr(step_log, "error") and step_log.error is not None:
141
- yield gr.ChatMessage(
142
- role="assistant",
143
- content=str(step_log.error),
144
- metadata={"title": "💥 Error", "parent_id": parent_id, "status": "done"},
145
- )
146
-
147
- # Update parent message metadata to done status without yielding a new message
148
- parent_message_tool.metadata["status"] = "done"
149
-
150
- # Handle standalone errors but not from tool calls
151
- elif hasattr(step_log, "error") and step_log.error is not None:
152
- yield gr.ChatMessage(role="assistant", content=str(step_log.error), metadata={"title": "💥 Error"})
153
-
154
- # Calculate duration and token information
155
- step_footnote = f"{step_number}"
156
- if hasattr(step_log, "input_token_count") and hasattr(step_log, "output_token_count"):
157
- token_str = (
158
- f" | Input-tokens:{step_log.input_token_count:,} | Output-tokens:{step_log.output_token_count:,}"
159
- )
160
- step_footnote += token_str
161
- if hasattr(step_log, "duration"):
162
- step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else None
163
- step_footnote += step_duration
164
- step_footnote = f"""<span style="color: #bbbbc2; font-size: 12px;">{step_footnote}</span> """
165
- yield gr.ChatMessage(role="assistant", content=f"{step_footnote}")
166
- yield gr.ChatMessage(role="assistant", content="-----")
167
-
168
-
169
- def stream_to_gradio(
170
- agent,
171
- task: str,
172
- reset_agent_memory: bool = False,
173
- additional_args: Optional[dict] = None,
174
- ):
175
- """Runs an agent with the given task and streams the messages from the agent as gradio ChatMessages."""
176
- if not _is_package_available("gradio"):
177
- raise ModuleNotFoundError(
178
- "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
179
- )
180
- import gradio as gr
181
-
182
- total_input_tokens = 0
183
- total_output_tokens = 0
184
-
185
- for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):
186
- # Track tokens if model provides them
187
- if hasattr(agent.model, "last_input_token_count"):
188
- total_input_tokens += agent.model.last_input_token_count
189
- total_output_tokens += agent.model.last_output_token_count
190
- if isinstance(step_log, ActionStep):
191
- step_log.input_token_count = agent.model.last_input_token_count
192
- step_log.output_token_count = agent.model.last_output_token_count
193
-
194
- for message in pull_messages_from_step(
195
- step_log,
196
- ):
197
- yield message
198
-
199
- final_answer = step_log # Last log is the run's final_answer
200
- final_answer = handle_agent_output_types(final_answer)
201
-
202
- if isinstance(final_answer, AgentText):
203
- yield gr.ChatMessage(
204
- role="assistant",
205
- content=f"**Final answer:**\n{final_answer.to_string()}\n",
206
- )
207
- elif isinstance(final_answer, AgentImage):
208
- yield gr.ChatMessage(
209
- role="assistant",
210
- content={"path": final_answer.to_string(), "mime_type": "image/png"},
211
- )
212
- elif isinstance(final_answer, AgentAudio):
213
- yield gr.ChatMessage(
214
- role="assistant",
215
- content={"path": final_answer.to_string(), "mime_type": "audio/wav"},
216
- )
217
- else:
218
- yield gr.ChatMessage(role="assistant", content=f"**Final answer:** {str(final_answer)}")
219
-
220
-
221
-
222
- class GradioUI:
223
- """A one-line interface to launch your agent in Gradio"""
224
-
225
- def __init__(self, agent: MultiStepAgent, file_upload_folder: str | None = None):
226
- if not _is_package_available("gradio"):
227
- raise ModuleNotFoundError(
228
- "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
229
- )
230
- self.agent = agent
231
- self.file_upload_folder = file_upload_folder
232
- if self.file_upload_folder is not None:
233
- if not os.path.exists(file_upload_folder):
234
- os.mkdir(file_upload_folder)
235
-
236
-
237
-
238
- def interact_with_agent(self, prompt, messages):
239
- import gradio as gr
240
-
241
- messages.append(gr.ChatMessage(role="user", content=prompt))
242
- yield messages
243
- for msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):
244
- messages.append(msg)
245
- yield messages
246
- yield messages
247
-
248
- def upload_file(
249
- self,
250
- file,
251
- file_uploads_log,
252
- allowed_file_types=[
253
- "application/pdf",
254
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
255
- "text/plain",
256
- ],
257
- ):
258
- """
259
- Handle file uploads, default allowed types are .pdf, .docx, and .txt
260
- """
261
- import gradio as gr
262
-
263
- if file is None:
264
- return gr.Textbox("No file uploaded", visible=True), file_uploads_log
265
-
266
- try:
267
- mime_type, _ = mimetypes.guess_type(file.name)
268
- except Exception as e:
269
- return gr.Textbox(f"Error: {e}", visible=True), file_uploads_log
270
-
271
- if mime_type not in allowed_file_types:
272
- return gr.Textbox("File type disallowed", visible=True), file_uploads_log
273
-
274
- # Sanitize file name
275
- original_name = os.path.basename(file.name)
276
- sanitized_name = re.sub(
277
- r"[^\w\-.]", "_", original_name
278
- ) # Replace any non-alphanumeric, non-dash, or non-dot characters with underscores
279
-
280
- type_to_ext = {}
281
- for ext, t in mimetypes.types_map.items():
282
- if t not in type_to_ext:
283
- type_to_ext[t] = ext
284
-
285
- # Ensure the extension correlates to the mime type
286
- sanitized_name = sanitized_name.split(".")[:-1]
287
- sanitized_name.append("" + type_to_ext[mime_type])
288
- sanitized_name = "".join(sanitized_name)
289
-
290
- # Save the uploaded file to the specified folder
291
- file_path = os.path.join(self.file_upload_folder, os.path.basename(sanitized_name))
292
- shutil.copy(file.name, file_path)
293
-
294
- return gr.Textbox(f"File uploaded: {file_path}", visible=True), file_uploads_log + [file_path]
295
-
296
- def log_user_message(self, text_input, file_uploads_log):
297
- return (
298
- text_input
299
- + (
300
- f"\nYou have been provided with these files, which might be helpful or not: {file_uploads_log}"
301
- if len(file_uploads_log) > 0
302
- else ""
303
- ),
304
- "",
305
- )
306
-
307
-
308
-
309
- def launch(self, **kwargs):
310
-
311
- import gradio as gr
312
-
313
- # Function for handling input change after selecting an example
314
- def on_example_click(example_text):
315
- return example_text + " yay!!"
316
-
317
- with gr.Blocks(
318
- title="Content Classifier",
319
- fill_height=True,
320
- css="""
321
- .loading-message {
322
- animation: pulse 2s cubic-bezier(.4,0,.6,1) infinite;
323
- }
324
- @keyframes pulse {
325
- 0%, 100% { opacity: 1; }
326
- 50% { opacity: 0.5; }
327
- }
328
- """
329
- ) as demo:
330
- gr.Markdown(agent_header)
331
- stored_messages = gr.State([])
332
- file_uploads_log = gr.State([])
333
- chatbot = gr.Chatbot(
334
- label="Agent",
335
- type="messages",
336
- avatar_images=(
337
- None,
338
- "https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/Alfred.png",
339
- ),
340
- resizeable=True,
341
- scale=1,
342
- )
343
- # If an upload folder is provided, enable the upload feature
344
- if self.file_upload_folder is not None:
345
- upload_file = gr.File(label="Upload a file")
346
- upload_status = gr.Textbox(label="Upload Status", interactive=False, visible=False)
347
- upload_file.change(
348
- self.upload_file,
349
- [upload_file, file_uploads_log],
350
- [upload_status, file_uploads_log],
351
- )
352
- text_input = gr.Textbox(lines=1, label="Chat Message")
353
-
354
- text_input.submit(
355
- self.log_user_message,
356
-
357
- [text_input, file_uploads_log],
358
- # outputs
359
- [stored_messages, text_input],
360
- ).then(self.interact_with_agent, [stored_messages, chatbot], [chatbot])
361
-
362
- gr.Examples(
363
- examples=get_examples(),
364
- inputs=text_input,
365
- label="Example Input Text"
366
- )
367
- # Example texts (you can replace these with your own examples)
368
- example_texts = ["Example 1: Hello!", "Example 2: How are you?", "Example 3: What's your name?"]
369
-
370
- # Set up the examples, with the on_example_click to update text_input
371
- gr.Examples(
372
- examples=example_texts,
373
- inputs=text_input,
374
- label="Demoing Text",
375
- fn=on_example_click # Update text_input with the selected example
376
- )
377
-
378
- gr.Markdown( agent_footer )
379
-
380
- demo.launch(debug=True, share=True, **kwargs)
381
-
382
-
383
- __all__ = ["stream_to_gradio", "GradioUI"]