jbisal commited on
Commit
6b2b0d0
·
1 Parent(s): 6369537

Reverted UI and app

Browse files
Files changed (2) hide show
  1. Gradio_UI.py +247 -73
  2. app.py +2 -2
Gradio_UI.py CHANGED
@@ -22,17 +22,175 @@ from smolagents.agent_types import AgentAudio, AgentImage, AgentText, handle_age
22
  from smolagents.agents import ActionStep, MultiStepAgent
23
  from smolagents.memory import MemoryStep
24
  from smolagents.utils import _is_package_available
25
- import gradio as gr
26
- from gradio.components import Markdown
27
- from gradio.components import Chatbot, Textbox, State, Button
28
 
29
- class EnhancedGradioUI:
30
- """Enhanced Gradio UI with markdown introduction and quick prompt buttons"""
31
 
32
- def __init__(self, agent):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  self.agent = agent
 
 
 
 
34
 
35
  def interact_with_agent(self, prompt, messages):
 
 
36
  messages.append(gr.ChatMessage(role="user", content=prompt))
37
  yield messages
38
  for msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):
@@ -40,46 +198,73 @@ class EnhancedGradioUI:
40
  yield messages
41
  yield messages
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  def launch(self, **kwargs):
44
- with gr.Blocks(theme="base") as demo:
45
- # State to store chat messages
46
- stored_messages = State([])
47
-
48
- # Markdown Introduction
49
- gr.Markdown("""
50
- # NBAi - NBA Stats Chatbot 🤖🏀
51
-
52
- Welcome to **NBAi**, your personal NBA statistics assistant! This app fetches and presents NBA box scores from last night's games, giving you insights on player performance, team stats, and more.
53
-
54
- ## Features
55
- - Get real-time NBA box scores and player statistics.
56
- - Ask questions like:
57
- - Who had the most points last night?
58
- - Who grabbed the most rebounds?
59
- - Who had the highest assist-to-turnover ratio?
60
-
61
- ## Tools Used 🔧
62
- - **smolagents** for building multi-step agents.
63
- - **Gradio** for the user interface.
64
- - **BeautifulSoup** and **Pandas** for web scraping and data processing.
65
- - **DuckDuckGoSearchTool** and **VisitWebpageTool** for enhanced web interactions.
66
-
67
- ## How to Use 🚀
68
- - Click one of the quick prompt buttons below or type your own question.
69
- - The chatbot will respond with detailed NBA statistics from last night's games.
70
-
71
- ---
72
- """)
73
-
74
- # Quick Prompt Buttons
75
- with gr.Row():
76
- btn_points = Button(value="🏀 Most Points", variant="primary")
77
- btn_rebounds = Button(value="💪 Most Rebounds", variant="primary")
78
- btn_assist_to_turnover = Button(value="🎯 Best Assist-to-Turnover Ratio", variant="primary")
79
-
80
- # Chatbot Interface
81
- chatbot = Chatbot(
82
- label="NBAi Chatbot",
83
  type="messages",
84
  avatar_images=(
85
  None,
@@ -88,34 +273,23 @@ class EnhancedGradioUI:
88
  resizeable=True,
89
  scale=1,
90
  )
91
-
92
- # Textbox for Custom User Input
93
- text_input = Textbox(lines=1, label="Your Question")
94
-
95
- # Bindings for Buttons
96
- btn_points.click(
97
- self.interact_with_agent,
98
- ["Who had the most points in last night's NBA games?", stored_messages],
99
- chatbot
100
- )
101
-
102
- btn_rebounds.click(
103
- self.interact_with_agent,
104
- ["Who had the most rebounds in last night's NBA games?", stored_messages],
105
- chatbot
106
- )
107
-
108
- btn_assist_to_turnover.click(
109
- self.interact_with_agent,
110
- ["Who had the highest ratio of assists to turnovers in last night's NBA games?", stored_messages],
111
- chatbot
112
- )
113
-
114
- # Custom Input Submission
115
  text_input.submit(
116
- self.interact_with_agent,
117
- [text_input, stored_messages],
118
- chatbot
119
- )
120
 
121
  demo.launch(debug=True, share=True, **kwargs)
 
 
 
 
22
  from smolagents.agents import ActionStep, MultiStepAgent
23
  from smolagents.memory import MemoryStep
24
  from smolagents.utils import _is_package_available
 
 
 
25
 
 
 
26
 
27
+ def pull_messages_from_step(
28
+ step_log: MemoryStep,
29
+ ):
30
+ """Extract ChatMessage objects from agent steps with proper nesting"""
31
+ import gradio as gr
32
+
33
+ if isinstance(step_log, ActionStep):
34
+ # Output the step number
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
+ # First yield the thought/reasoning from the LLM
39
+ if hasattr(step_log, "model_output") and step_log.model_output is not None:
40
+ # Clean up the LLM output
41
+ model_output = step_log.model_output.strip()
42
+ # Remove any trailing <end_code> and extra backticks, handling multiple possible formats
43
+ model_output = re.sub(r"```\s*<end_code>", "```", model_output) # handles ```<end_code>
44
+ model_output = re.sub(r"<end_code>\s*```", "```", model_output) # handles <end_code>```
45
+ model_output = re.sub(r"```\s*\n\s*<end_code>", "```", model_output) # handles ```\n<end_code>
46
+ model_output = model_output.strip()
47
+ yield gr.ChatMessage(role="assistant", content=model_output)
48
+
49
+ # For tool calls, create a parent message
50
+ if hasattr(step_log, "tool_calls") and step_log.tool_calls is not None:
51
+ first_tool_call = step_log.tool_calls[0]
52
+ used_code = first_tool_call.name == "python_interpreter"
53
+ parent_id = f"call_{len(step_log.tool_calls)}"
54
+
55
+ # Tool call becomes the parent message with timing info
56
+ # First we will handle arguments based on type
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
+ # Clean up the content by removing any end code tags
65
+ content = re.sub(r"```.*?\n", "", content) # Remove existing code blocks
66
+ content = re.sub(r"\s*<end_code>\s*", "", content) # Remove end_code tags
67
+ content = content.strip()
68
+ if not content.startswith("```python"):
69
+ content = f"```python\n{content}\n```"
70
+
71
+ parent_message_tool = gr.ChatMessage(
72
+ role="assistant",
73
+ content=content,
74
+ metadata={
75
+ "title": f"🛠️ Used tool {first_tool_call.name}",
76
+ "id": parent_id,
77
+ "status": "pending",
78
+ },
79
+ )
80
+ yield parent_message_tool
81
+
82
+ # Nesting execution logs under the tool call if they exist
83
+ if hasattr(step_log, "observations") and (
84
+ step_log.observations is not None and step_log.observations.strip()
85
+ ): # Only yield execution logs if there's actual content
86
+ log_content = step_log.observations.strip()
87
+ if log_content:
88
+ log_content = re.sub(r"^Execution logs:\s*", "", log_content)
89
+ yield gr.ChatMessage(
90
+ role="assistant",
91
+ content=f"{log_content}",
92
+ metadata={"title": "📝 Execution Logs", "parent_id": parent_id, "status": "done"},
93
+ )
94
+
95
+ # Nesting any errors under the tool call
96
+ if hasattr(step_log, "error") and step_log.error is not None:
97
+ yield gr.ChatMessage(
98
+ role="assistant",
99
+ content=str(step_log.error),
100
+ metadata={"title": "💥 Error", "parent_id": parent_id, "status": "done"},
101
+ )
102
+
103
+ # Update parent message metadata to done status without yielding a new message
104
+ parent_message_tool.metadata["status"] = "done"
105
+
106
+ # Handle standalone errors but not from tool calls
107
+ elif hasattr(step_log, "error") and step_log.error is not None:
108
+ yield gr.ChatMessage(role="assistant", content=str(step_log.error), metadata={"title": "💥 Error"})
109
+
110
+ # Calculate duration and token information
111
+ step_footnote = f"{step_number}"
112
+ if hasattr(step_log, "input_token_count") and hasattr(step_log, "output_token_count"):
113
+ token_str = (
114
+ f" | Input-tokens:{step_log.input_token_count:,} | Output-tokens:{step_log.output_token_count:,}"
115
+ )
116
+ step_footnote += token_str
117
+ if hasattr(step_log, "duration"):
118
+ step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else None
119
+ step_footnote += step_duration
120
+ step_footnote = f"""<span style="color: #bbbbc2; font-size: 12px;">{step_footnote}</span> """
121
+ yield gr.ChatMessage(role="assistant", content=f"{step_footnote}")
122
+ yield gr.ChatMessage(role="assistant", content="-----")
123
+
124
+
125
+ def stream_to_gradio(
126
+ agent,
127
+ task: str,
128
+ reset_agent_memory: bool = False,
129
+ additional_args: Optional[dict] = None,
130
+ ):
131
+ """Runs an agent with the given task and streams the messages from the agent as gradio ChatMessages."""
132
+ if not _is_package_available("gradio"):
133
+ raise ModuleNotFoundError(
134
+ "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
135
+ )
136
+ import gradio as gr
137
+
138
+ total_input_tokens = 0
139
+ total_output_tokens = 0
140
+
141
+ for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):
142
+ # Track tokens if model provides them
143
+ if hasattr(agent.model, "last_input_token_count"):
144
+ total_input_tokens += agent.model.last_input_token_count
145
+ total_output_tokens += agent.model.last_output_token_count
146
+ if isinstance(step_log, ActionStep):
147
+ step_log.input_token_count = agent.model.last_input_token_count
148
+ step_log.output_token_count = agent.model.last_output_token_count
149
+
150
+ for message in pull_messages_from_step(
151
+ step_log,
152
+ ):
153
+ yield message
154
+
155
+ final_answer = step_log # Last log is the run's final_answer
156
+ final_answer = handle_agent_output_types(final_answer)
157
+
158
+ if isinstance(final_answer, AgentText):
159
+ yield gr.ChatMessage(
160
+ role="assistant",
161
+ content=f"**Final answer:**\n{final_answer.to_string()}\n",
162
+ )
163
+ elif isinstance(final_answer, AgentImage):
164
+ yield gr.ChatMessage(
165
+ role="assistant",
166
+ content={"path": final_answer.to_string(), "mime_type": "image/png"},
167
+ )
168
+ elif isinstance(final_answer, AgentAudio):
169
+ yield gr.ChatMessage(
170
+ role="assistant",
171
+ content={"path": final_answer.to_string(), "mime_type": "audio/wav"},
172
+ )
173
+ else:
174
+ yield gr.ChatMessage(role="assistant", content=f"**Final answer:** {str(final_answer)}")
175
+
176
+
177
+ class GradioUI:
178
+ """A one-line interface to launch your agent in Gradio"""
179
+
180
+ def __init__(self, agent: MultiStepAgent, file_upload_folder: str | None = None):
181
+ if not _is_package_available("gradio"):
182
+ raise ModuleNotFoundError(
183
+ "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
184
+ )
185
  self.agent = agent
186
+ self.file_upload_folder = file_upload_folder
187
+ if self.file_upload_folder is not None:
188
+ if not os.path.exists(file_upload_folder):
189
+ os.mkdir(file_upload_folder)
190
 
191
  def interact_with_agent(self, prompt, messages):
192
+ import gradio as gr
193
+
194
  messages.append(gr.ChatMessage(role="user", content=prompt))
195
  yield messages
196
  for msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):
 
198
  yield messages
199
  yield messages
200
 
201
+ def upload_file(
202
+ self,
203
+ file,
204
+ file_uploads_log,
205
+ allowed_file_types=[
206
+ "application/pdf",
207
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
208
+ "text/plain",
209
+ ],
210
+ ):
211
+ """
212
+ Handle file uploads, default allowed types are .pdf, .docx, and .txt
213
+ """
214
+ import gradio as gr
215
+
216
+ if file is None:
217
+ return gr.Textbox("No file uploaded", visible=True), file_uploads_log
218
+
219
+ try:
220
+ mime_type, _ = mimetypes.guess_type(file.name)
221
+ except Exception as e:
222
+ return gr.Textbox(f"Error: {e}", visible=True), file_uploads_log
223
+
224
+ if mime_type not in allowed_file_types:
225
+ return gr.Textbox("File type disallowed", visible=True), file_uploads_log
226
+
227
+ # Sanitize file name
228
+ original_name = os.path.basename(file.name)
229
+ sanitized_name = re.sub(
230
+ r"[^\w\-.]", "_", original_name
231
+ ) # Replace any non-alphanumeric, non-dash, or non-dot characters with underscores
232
+
233
+ type_to_ext = {}
234
+ for ext, t in mimetypes.types_map.items():
235
+ if t not in type_to_ext:
236
+ type_to_ext[t] = ext
237
+
238
+ # Ensure the extension correlates to the mime type
239
+ sanitized_name = sanitized_name.split(".")[:-1]
240
+ sanitized_name.append("" + type_to_ext[mime_type])
241
+ sanitized_name = "".join(sanitized_name)
242
+
243
+ # Save the uploaded file to the specified folder
244
+ file_path = os.path.join(self.file_upload_folder, os.path.basename(sanitized_name))
245
+ shutil.copy(file.name, file_path)
246
+
247
+ return gr.Textbox(f"File uploaded: {file_path}", visible=True), file_uploads_log + [file_path]
248
+
249
+ def log_user_message(self, text_input, file_uploads_log):
250
+ return (
251
+ text_input
252
+ + (
253
+ f"\nYou have been provided with these files, which might be helpful or not: {file_uploads_log}"
254
+ if len(file_uploads_log) > 0
255
+ else ""
256
+ ),
257
+ "",
258
+ )
259
+
260
  def launch(self, **kwargs):
261
+ import gradio as gr
262
+
263
+ with gr.Blocks(fill_height=True) as demo:
264
+ stored_messages = gr.State([])
265
+ file_uploads_log = gr.State([])
266
+ chatbot = gr.Chatbot(
267
+ label="Agent",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
  type="messages",
269
  avatar_images=(
270
  None,
 
273
  resizeable=True,
274
  scale=1,
275
  )
276
+ # If an upload folder is provided, enable the upload feature
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="Chat Message")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, share=True, **kwargs)
293
+
294
+
295
+ __all__ = ["stream_to_gradio", "GradioUI"]
app.py CHANGED
@@ -10,7 +10,7 @@ import logging
10
  import inspect
11
  from bs4 import BeautifulSoup # Fixed Import
12
  from tools.final_answer import FinalAnswerTool
13
- from Gradio_UI import EnhancedGradioUI
14
 
15
  logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
16
 
@@ -170,4 +170,4 @@ agent = CodeAgent(
170
  )
171
 
172
  # Launch Gradio UI
173
- EnhancedGradioUI(agent).launch()
 
10
  import inspect
11
  from bs4 import BeautifulSoup # Fixed Import
12
  from tools.final_answer import FinalAnswerTool
13
+ from Gradio_UI import GradioUI
14
 
15
  logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
16
 
 
170
  )
171
 
172
  # Launch Gradio UI
173
+ GradioUI(agent).launch()