Spaces:
Runtime error
Runtime error
Create Gradio_UI.py
Browse files- Gradio_UI.py +93 -285
Gradio_UI.py
CHANGED
|
@@ -1,296 +1,104 @@
|
|
| 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
|
| 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) # 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```"
|
| 71 |
-
|
| 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",
|
| 100 |
-
content=str(step_log.error),
|
| 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
|
| 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 |
-
"""
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
|
|
|
| 186 |
self.agent = agent
|
| 187 |
-
self.
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
def
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
]
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
sanitized_name.append("" + type_to_ext[mime_type])
|
| 242 |
-
sanitized_name = "".join(sanitized_name)
|
| 243 |
-
|
| 244 |
-
# Save the uploaded file to the specified folder
|
| 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 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
label="
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
)
|
| 274 |
-
|
| 275 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
)
|
| 277 |
-
# If an upload folder is provided, enable the upload feature
|
| 278 |
-
if self.file_upload_folder is not None:
|
| 279 |
-
upload_file = gr.File(label="Upload a file")
|
| 280 |
-
upload_status = gr.Textbox(label="Upload Status", interactive=False, visible=False)
|
| 281 |
-
upload_file.change(
|
| 282 |
-
self.upload_file,
|
| 283 |
-
[upload_file, file_uploads_log],
|
| 284 |
-
[upload_status, file_uploads_log],
|
| 285 |
-
)
|
| 286 |
-
text_input = gr.Textbox(lines=1, label="Chat Message")
|
| 287 |
-
text_input.submit(
|
| 288 |
-
self.log_user_message,
|
| 289 |
-
[text_input, file_uploads_log],
|
| 290 |
-
[stored_messages, text_input],
|
| 291 |
-
).then(self.interact_with_agent, [stored_messages, chatbot], [chatbot])
|
| 292 |
-
|
| 293 |
-
demo.launch(debug=True, share=True, **kwargs)
|
| 294 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
|
| 296 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import re
|
| 3 |
+
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
class GradioUI:
|
| 6 |
+
"""
|
| 7 |
+
Gradio UI for a smolagents agent:
|
| 8 |
+
- unwraps FinalAnswerStep to plain text,
|
| 9 |
+
- extracts 'IMAGE:<path>' lines and shows them in a gallery,
|
| 10 |
+
- keeps chat and gallery state across messages (Spaces safe).
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
def __init__(self, agent):
|
| 14 |
self.agent = agent
|
| 15 |
+
self.images_dir = os.path.abspath("generated_images")
|
| 16 |
+
os.makedirs(self.images_dir, exist_ok=True)
|
| 17 |
+
|
| 18 |
+
# --- helpers ------------------------------------------------------------
|
| 19 |
+
|
| 20 |
+
def _pretty_text(self, out):
|
| 21 |
+
# smolagents FinalAnswerTool result object
|
| 22 |
+
if hasattr(out, "final_answer"):
|
| 23 |
+
v = out.final_answer
|
| 24 |
+
return v if isinstance(v, str) else str(v)
|
| 25 |
+
# dict with "final_answer"
|
| 26 |
+
if isinstance(out, dict) and "final_answer" in out:
|
| 27 |
+
v = out["final_answer"]
|
| 28 |
+
return v if isinstance(v, str) else str(v)
|
| 29 |
+
# plain string or anything else
|
| 30 |
+
return out if isinstance(out, str) else str(out)
|
| 31 |
+
|
| 32 |
+
IMAGE_LINE_RE = re.compile(
|
| 33 |
+
r"^\s*(?:IMAGE|IMG_PATH)\s*:\s*(.+\.(?:png|jpg|jpeg|webp|bmp|gif))\s*$",
|
| 34 |
+
re.IGNORECASE | re.MULTILINE
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
def _extract_image_paths(self, text):
|
| 38 |
+
paths = []
|
| 39 |
+
for m in self.IMAGE_LINE_RE.finditer(text or ""):
|
| 40 |
+
p = m.group(1).strip().strip('"').strip("'")
|
| 41 |
+
p_abs = os.path.abspath(p)
|
| 42 |
+
if os.path.isfile(p_abs):
|
| 43 |
+
paths.append(p_abs)
|
| 44 |
+
return paths
|
| 45 |
+
|
| 46 |
+
# --- callbacks ----------------------------------------------------------
|
| 47 |
+
|
| 48 |
+
def _chat(self, history_state, message, gallery_state):
|
| 49 |
+
out = self.agent.run(message)
|
| 50 |
+
clean = self._pretty_text(out)
|
| 51 |
+
img_paths = self._extract_image_paths(clean)
|
| 52 |
+
|
| 53 |
+
# update conversation history
|
| 54 |
+
history = (history_state or []) + [(message, clean)]
|
| 55 |
+
# update gallery items
|
| 56 |
+
gallery_list = list(gallery_state or [])
|
| 57 |
+
for p in img_paths:
|
| 58 |
+
if p not in gallery_list:
|
| 59 |
+
gallery_list.append(p)
|
| 60 |
+
|
| 61 |
+
# Return updated states and component values
|
| 62 |
+
return history, gallery_list, history, gallery_list
|
| 63 |
+
|
| 64 |
+
def _clear(self):
|
| 65 |
+
# clear both the UI components and the states
|
| 66 |
+
return [], [], [], []
|
| 67 |
+
|
| 68 |
+
# --- layout -------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
def launch(self, **kwargs):
|
|
|
|
|
|
|
| 71 |
with gr.Blocks(fill_height=True) as demo:
|
| 72 |
+
gr.Markdown("## 🧠 Tools Agent (text + images) — Hugging Face Space")
|
| 73 |
+
|
| 74 |
+
with gr.Row():
|
| 75 |
+
chatbot = gr.Chatbot(label="Chat", height=420, type="messages")
|
| 76 |
+
gallery = gr.Gallery(label="Generated images", height=420, columns=[2], preview=True)
|
| 77 |
+
|
| 78 |
+
msg = gr.Textbox(placeholder="Ask: 'What's the time in America/New_York?' or 'Generate an image of a cat astronaut'", lines=2)
|
| 79 |
+
with gr.Row():
|
| 80 |
+
send = gr.Button("Send", variant="primary")
|
| 81 |
+
clear = gr.Button("Clear")
|
| 82 |
+
|
| 83 |
+
# persistent states
|
| 84 |
+
chat_state = gr.State([])
|
| 85 |
+
gallery_state = gr.State([])
|
| 86 |
+
|
| 87 |
+
send.click(
|
| 88 |
+
self._chat,
|
| 89 |
+
inputs=[chat_state, msg, gallery_state],
|
| 90 |
+
outputs=[chat_state, gallery_state, chatbot, gallery],
|
| 91 |
+
).then(
|
| 92 |
+
lambda: "",
|
| 93 |
+
inputs=None,
|
| 94 |
+
outputs=msg
|
| 95 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
+
clear.click(
|
| 98 |
+
self._clear,
|
| 99 |
+
inputs=None,
|
| 100 |
+
outputs=[chat_state, gallery_state, chatbot, gallery]
|
| 101 |
+
)
|
| 102 |
|
| 103 |
+
# queue() is recommended on Spaces
|
| 104 |
+
demo.queue().launch(**kwargs)
|