|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import mimetypes |
|
import os |
|
import re |
|
import shutil |
|
from typing import Optional |
|
|
|
from smolagents.agent_types import AgentAudio, AgentImage, AgentText, handle_agent_output_types |
|
from smolagents.agents import ActionStep, MultiStepAgent |
|
from smolagents.memory import MemoryStep |
|
from smolagents.utils import _is_package_available |
|
|
|
|
|
def pull_messages_from_step( |
|
step_log: MemoryStep, |
|
): |
|
"""Extract ChatMessage objects from agent steps with proper nesting""" |
|
import gradio as gr |
|
|
|
if isinstance(step_log, ActionStep): |
|
|
|
step_number = f"Step {step_log.step_number}" if step_log.step_number is not None else "" |
|
yield gr.ChatMessage(role="assistant", content=f"**{step_number}**") |
|
|
|
|
|
if hasattr(step_log, "model_output") and step_log.model_output is not None: |
|
|
|
model_output = step_log.model_output.strip() |
|
|
|
model_output = re.sub(r"```\s*<end_code>", "```", model_output) |
|
model_output = re.sub(r"<end_code>\s*```", "```", model_output) |
|
model_output = re.sub(r"```\s*\n\s*<end_code>", "```", model_output) |
|
model_output = model_output.strip() |
|
yield gr.ChatMessage(role="assistant", content=model_output) |
|
|
|
|
|
if hasattr(step_log, "tool_calls") and step_log.tool_calls is not None: |
|
first_tool_call = step_log.tool_calls[0] |
|
used_code = first_tool_call.name == "python_interpreter" |
|
parent_id = f"call_{len(step_log.tool_calls)}_{step_log.step_number or 'x'}" |
|
|
|
|
|
args = first_tool_call.arguments |
|
if isinstance(args, dict): |
|
content = str(args.get("answer", str(args))) |
|
else: |
|
content = str(args).strip() |
|
|
|
if used_code: |
|
content = re.sub(r"```.*?\n", "", content) |
|
content = re.sub(r"\s*<end_code>\s*", "", content) |
|
content = content.strip() |
|
if not content.startswith("```python"): |
|
content = f"```python\n{content}\n```" |
|
else: |
|
content = content.replace("```python", "```python\n").replace("\n```", "\n```") |
|
|
|
|
|
parent_message_tool = gr.ChatMessage( |
|
role="assistant", |
|
content=content, |
|
metadata={ |
|
"title": f"🛠️ Used tool {first_tool_call.name}", |
|
"id": parent_id, |
|
"status": "pending", |
|
}, |
|
) |
|
yield parent_message_tool |
|
|
|
if hasattr(step_log, "observations") and ( |
|
step_log.observations is not None and step_log.observations.strip() |
|
): |
|
log_content = step_log.observations.strip() |
|
if log_content: |
|
log_content = re.sub(r"^Execution logs:\s*", "", log_content) |
|
yield gr.ChatMessage( |
|
role="assistant", |
|
content=f"{log_content}", |
|
metadata={"title": "📝 Execution Logs", "parent_id": parent_id, "status": "done"}, |
|
) |
|
|
|
if hasattr(step_log, "error") and step_log.error is not None: |
|
yield gr.ChatMessage( |
|
role="assistant", |
|
content=str(step_log.error), |
|
metadata={"title": "💥 Error", "parent_id": parent_id, "status": "done"}, |
|
) |
|
|
|
|
|
parent_message_tool.metadata["status"] = "done" |
|
|
|
elif hasattr(step_log, "error") and step_log.error is not None: |
|
yield gr.ChatMessage(role="assistant", content=str(step_log.error), metadata={"title": "💥 Error"}) |
|
|
|
step_footnote_parts = [step_number] |
|
if hasattr(step_log, "input_token_count") and step_log.input_token_count is not None and \ |
|
hasattr(step_log, "output_token_count") and step_log.output_token_count is not None: |
|
token_str = ( |
|
f" | Input-tokens:{step_log.input_token_count:,} | Output-tokens:{step_log.output_token_count:,}" |
|
) |
|
step_footnote_parts.append(token_str) |
|
if hasattr(step_log, "duration") and step_log.duration is not None: |
|
step_duration = f" | Duration: {round(float(step_log.duration), 2)}s" |
|
step_footnote_parts.append(step_duration) |
|
|
|
step_footnote_text = "".join(filter(None, step_footnote_parts)) |
|
if step_footnote_text: |
|
step_footnote = f"""<span style="color: #bbbbc2; font-size: 12px;">{step_footnote_text}</span> """ |
|
yield gr.ChatMessage(role="assistant", content=f"{step_footnote}") |
|
yield gr.ChatMessage(role="assistant", content="-----") |
|
|
|
|
|
def stream_to_gradio( |
|
agent, |
|
task: str, |
|
reset_agent_memory: bool = False, |
|
additional_args: Optional[dict] = None, |
|
): |
|
"""Runs an agent with the given task and streams the messages from the agent as gradio ChatMessages.""" |
|
if not _is_package_available("gradio"): |
|
raise ModuleNotFoundError( |
|
"Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`" |
|
) |
|
import gradio as gr |
|
|
|
|
|
if hasattr(agent, 'interaction_logs'): |
|
agent.interaction_logs.clear() |
|
print("DEBUG: Cleared agent interaction_logs for new run.") |
|
|
|
|
|
for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args): |
|
if hasattr(agent.model, "last_input_token_count") and agent.model.last_input_token_count is not None: |
|
if isinstance(step_log, ActionStep): |
|
step_log.input_token_count = agent.model.last_input_token_count |
|
step_log.output_token_count = agent.model.last_output_token_count |
|
|
|
for message in pull_messages_from_step(step_log): |
|
yield message |
|
|
|
|
|
final_answer_content = step_log |
|
final_answer_processed = handle_agent_output_types(final_answer_content) |
|
|
|
if isinstance(final_answer_processed, AgentText): |
|
yield gr.ChatMessage(role="assistant", content=f"**Final answer:**\n{final_answer_processed.to_string()}\n") |
|
elif isinstance(final_answer_processed, AgentImage): |
|
yield gr.ChatMessage(role="assistant", content={"path": final_answer_processed.to_string(), "mime_type": "image/png"}) |
|
elif isinstance(final_answer_processed, AgentAudio): |
|
yield gr.ChatMessage(role="assistant", content={"path": final_answer_processed.to_string(), "mime_type": "audio/wav"}) |
|
else: |
|
yield gr.ChatMessage(role="assistant", content=f"**Final answer:** {str(final_answer_processed)}") |
|
|
|
|
|
class GradioUI: |
|
"""A one-line interface to launch your agent in Gradio""" |
|
|
|
def __init__(self, agent: MultiStepAgent, file_upload_folder: str | None = None): |
|
if not _is_package_available("gradio"): |
|
raise ModuleNotFoundError( |
|
"Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`" |
|
) |
|
self.agent = agent |
|
self.file_upload_folder = file_upload_folder |
|
if self.file_upload_folder is not None: |
|
if not os.path.exists(file_upload_folder): |
|
os.makedirs(self.file_upload_folder, exist_ok=True) |
|
|
|
self._latest_file_path_for_download = None |
|
|
|
def _check_for_created_file(self): |
|
"""Helper function to check interaction logs for a created file path.""" |
|
self._latest_file_path_for_download = None |
|
if hasattr(self.agent, 'interaction_logs') and self.agent.interaction_logs: |
|
print(f"DEBUG UI: Checking {len(self.agent.interaction_logs)} interaction log entries.") |
|
for log_entry in self.agent.interaction_logs: |
|
if log_entry.get("tool_name") == "create_document": |
|
tool_output_value = log_entry.get("tool_output") |
|
print(f"DEBUG UI: Log for 'create_document', output: {tool_output_value}") |
|
if tool_output_value and isinstance(tool_output_value, str): |
|
if not tool_output_value.strip().startswith("ERROR:"): |
|
normalized_path = os.path.normpath(tool_output_value) |
|
if os.path.exists(normalized_path): |
|
self._latest_file_path_for_download = normalized_path |
|
print(f"DEBUG UI: File path for download set: {self._latest_file_path_for_download}") |
|
return True |
|
else: |
|
print(f"DEBUG UI: Path from log ('{normalized_path}') does not exist.") |
|
else: |
|
print(f"DEBUG UI: 'create_document' tool reported error: {tool_output_value}") |
|
return False |
|
|
|
|
|
def interact_with_agent(self, prompt, messages_history, download_btn_state, file_output_state): |
|
import gradio as gr |
|
|
|
messages_history.append(gr.ChatMessage(role="user", content=prompt)) |
|
yield messages_history, gr.update(visible=False), gr.update(value=None, visible=False) |
|
|
|
|
|
for msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False): |
|
messages_history.append(msg) |
|
yield messages_history, gr.update(visible=False), gr.update(value=None, visible=False) |
|
|
|
|
|
file_found = self._check_for_created_file() |
|
|
|
|
|
|
|
yield messages_history, gr.update(visible=file_found), gr.update(value=None, visible=False) |
|
|
|
|
|
def upload_file( |
|
self, |
|
file, |
|
file_uploads_log, |
|
allowed_file_types=[ |
|
"application/pdf", |
|
"application/vnd.openxmlformats-officedocument.wordprocessingml.document", |
|
"text/plain", |
|
], |
|
): |
|
import gradio as gr |
|
|
|
if file is None: |
|
return gr.Textbox("No file uploaded", visible=True), file_uploads_log |
|
|
|
try: |
|
mime_type, _ = mimetypes.guess_type(file.name) |
|
if mime_type is None: |
|
mime_type = file.type |
|
except Exception as e: |
|
return gr.Textbox(f"Error: {e}", visible=True), file_uploads_log |
|
|
|
if mime_type not in allowed_file_types: |
|
return gr.Textbox(f"File type '{mime_type}' disallowed", visible=True), file_uploads_log |
|
|
|
original_name = os.path.basename(file.name) |
|
sanitized_name = re.sub(r"[^\w\-.]", "_", original_name) |
|
|
|
|
|
base_name, current_ext = os.path.splitext(sanitized_name) |
|
|
|
type_to_ext_map = { |
|
"application/pdf": ".pdf", |
|
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx", |
|
"text/plain": ".txt", |
|
} |
|
expected_ext = type_to_ext_map.get(mime_type) |
|
if expected_ext and current_ext.lower() != expected_ext: |
|
sanitized_name = base_name + expected_ext |
|
|
|
file_path = os.path.join(self.file_upload_folder, sanitized_name) |
|
shutil.copy(file.name, file_path) |
|
|
|
return gr.Textbox(f"File uploaded: {file_path}", visible=True), file_uploads_log + [file_path] |
|
|
|
def log_user_message(self, text_input, file_uploads_log): |
|
|
|
|
|
full_prompt = text_input |
|
if file_uploads_log: |
|
full_prompt += ( |
|
f"\nYou have been provided with these files, which might be helpful or not: {file_uploads_log}" |
|
) |
|
return full_prompt, "" |
|
|
|
def prepare_and_show_download_file(self): |
|
import gradio as gr |
|
if self._latest_file_path_for_download and os.path.exists(self._latest_file_path_for_download): |
|
print(f"DEBUG UI: Preparing download for UI: {self._latest_file_path_for_download}") |
|
return gr.File.update(value=self._latest_file_path_for_download, |
|
label=os.path.basename(self._latest_file_path_for_download), |
|
visible=True) |
|
else: |
|
print("DEBUG UI: No valid file path to prepare for download component.") |
|
gr.Warning("No file available for download or path is invalid.") |
|
return gr.File.update(visible=False) |
|
|
|
def launch(self, **kwargs): |
|
import gradio as gr |
|
|
|
with gr.Blocks(fill_height=True, theme=gr.themes.Soft()) as demo: |
|
|
|
|
|
|
|
|
|
chat_history_state = gr.State([]) |
|
file_uploads_log = gr.State([]) |
|
|
|
|
|
gr.Markdown("# Smol Talk with your Agent") |
|
|
|
with gr.Row(): |
|
with gr.Column(scale=3): |
|
chatbot = gr.Chatbot( |
|
label="Agent Interaction", |
|
|
|
|
|
avatar_images=( |
|
None, |
|
"https://huggingface.co/datasets/huggingface/brand-assets/resolve/main/hf-logo-round.png" |
|
), |
|
height=600 |
|
) |
|
text_input = gr.Textbox( |
|
lines=1, |
|
label="Your Message to the Agent", |
|
placeholder="Type your message and press Enter..." |
|
) |
|
|
|
with gr.Column(scale=1): |
|
if self.file_upload_folder is not None: |
|
gr.Markdown("### File Upload") |
|
upload_file_component = gr.File(label="Upload a supporting file") |
|
upload_status_display = gr.Textbox(label="Upload Status", interactive=False, visible=True, lines=2) |
|
upload_file_component.upload( |
|
self.upload_file, |
|
[upload_file_component, file_uploads_log], |
|
[upload_status_display, file_uploads_log], |
|
) |
|
|
|
gr.Markdown("### Generated File") |
|
|
|
download_btn = gr.Button("Download Generated File", visible=False) |
|
|
|
file_output_display = gr.File(label="Downloadable Document", visible=False, interactive=False) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
prepared_prompt_state = gr.State("") |
|
|
|
text_input.submit( |
|
self.log_user_message, |
|
[text_input, file_uploads_log], |
|
[prepared_prompt_state, text_input] |
|
).then( |
|
self.interact_with_agent, |
|
[prepared_prompt_state, chat_history_state, download_btn, file_output_display], |
|
[chat_history_state, download_btn, file_output_display] |
|
) |
|
|
|
|
|
download_btn.click( |
|
self.prepare_and_show_download_file, |
|
[], |
|
[file_output_display] |
|
) |
|
|
|
|
|
|
|
demo.launch(debug=True, share=kwargs.get("share", False), **kwargs) |
|
|
|
|
|
__all__ = ["stream_to_gradio", "GradioUI"] |