Spaces:
Sleeping
Sleeping
Update Gradio_UI.py
Browse files23 unmodified lines24252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869701 unmodified line727374757677787980818283848586878889909192939495969798991 unmodified line1011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461 unmodified line1481491501511521531541551561571581591601611621631641651 unmodified line1671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122131 unmodified line2152162172182192202212222232242252262272282292302312322332342355 unmodified lines2412422432442452462472482492502512522532542552562572582592602612622631 unmodified line2652662672682692702712722732742752762772782792802818 unmodified lines2902912922932942952962 unmodified lines2993003013023033041 unmodified line30630730830931031131223 unmodified linesfrom smolagents.memory import MemoryStepfrom smolagents.utils import _is_package_availabledef pull_messages_from_step(step_log: MemoryStep,):"""Extract ChatMessage objects from agent steps with proper nesting"""import gradio as grif isinstance(step_log, ActionStep):# Output the step numberstep_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}**")# First yield the thought/reasoning from the LLMif hasattr(step_log, "model_output") and step_log.model_output is not None:# Clean up the LLM outputmodel_output = step_log.model_output.strip()# Remove any trailing <end_code> and extra backticks, handling multiple possible formatsmodel_output = re.sub(r"```\s*<end_code>", "```", model_output) # handles ```<end_code>model_output = re.sub(r"<end_code>\s*```", "```", model_output) # handles <end_code>```model_output = re.sub(r"```\s*\n\s*<end_code>", "```", model_output) # handles ```\n<end_code>model_output = model_output.strip()yield gr.ChatMessage(role="assistant", content=model_output)# For tool calls, create a parent messageif 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)}"# Tool call becomes the parent message with timing info# First we will handle arguments based on typeargs = first_tool_call.argumentsif isinstance(args, dict):content = str(args.get("answer", str(args)))else:content = str(args).strip()if used_code:# Clean up the content by removing any end code tagscontent = re.sub(r"```.*?\n", "", content) # Remove existing code blockscontent = re.sub(r"\s*<end_code>\s*", "", content) # Remove end_code tagscontent = content.strip()if not content.startswith("```python"):content = f"```python\n{content}\n```"1 unmodified lineparent_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# Nesting execution logs under the tool call if they existif hasattr(step_log, "observations") and (step_log.observations is not None and step_log.observations.strip()): # Only yield execution logs if there's actual contentlog_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"},)# Nesting any errors under the tool callif hasattr(step_log, "error") and step_log.error is not None:yield gr.ChatMessage(role="assistant",1 unmodified linemetadata={"title": "💥 Error", "parent_id": parent_id, "status": "done"},)# Update parent message metadata to done status without yielding a new messageparent_message_tool.metadata["status"] = "done"# Handle standalone errors but not from tool callselif hasattr(step_log, "error") and step_log.error is not None:yield gr.ChatMessage(role="assistant", content=str(step_log.error), metadata={"title": "💥 Error"})# Calculate duration and token informationstep_footnote = f"{step_number}"if hasattr(step_log, "input_token_count") and hasattr(step_log, "output_token_count"):token_str = (f" | Input-tokens:{step_log.input_token_count:,} | Output-tokens:{step_log.output_token_count:,}")step_footnote += token_strif hasattr(step_log, "duration"):step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else Nonestep_footnote += step_durationstep_footnote = f"""<span style="color: #bbbbc2; font-size: 12px;">{step_footnote}</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 grtotal_input_tokens = 0total_output_tokens = 0for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):# Track tokens if model provides themif hasattr(agent.model, "last_input_token_count"):total_input_tokens += agent.model.last_input_token_counttotal_output_tokens += agent.model.last_output_token_count1 unmodified linestep_log.input_token_count = agent.model.last_input_token_countstep_log.output_token_count = agent.model.last_output_token_countfor message in pull_messages_from_step(step_log,):yield messagefrom smolagents.agents import FinalAnswerStep# Safely extract the final output from the last stepif isinstance(step_log, FinalAnswerStep):final_output = step_log.final_answerelse:# If not a FinalAnswerStep, fallback to tool_output or tool_callsfinal_output = getattr(step_log, "tool_output", None)if not final_output and hasattr(step_log, "tool_calls"):for call in step_log.tool_calls:1 unmodified linefinal_output = call.arguments.get("answer")breakfinal_output = handle_agent_output_types(final_output)if isinstance(final_output, AgentText):yield gr.ChatMessage(role="assistant",content=final_output.to_string().strip(),)elif isinstance(final_output, AgentImage):yield gr.ChatMessage(role="assistant",content={"path": final_output.to_string(), "mime_type": "image/png"},)elif isinstance(final_output, AgentAudio):yield gr.ChatMessage(role="assistant",content={"path": final_output.to_string(), "mime_type": "audio/wav"},)else:yield gr.ChatMessage(role="assistant", content=str(final_output).strip())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 = agentself.file_upload_folder = file_upload_folderif self.file_upload_folder is not None:if not os.path.exists(file_upload_folder):os.mkdir(file_upload_folder)def interact_with_agent(self, prompt, messages):import gradio as grmessages.append(gr.ChatMessage(role="user", content=prompt))yield messagesfor msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):1 unmodified lineyield messagesyield messagesdef upload_file(self,file,file_uploads_log,allowed_file_types=["application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain",],):"""Handle file uploads, default allowed types are .pdf, .docx, and .txt"""import gradio as grif file is None:return gr.Textbox("No file uploaded", visible=True), file_uploads_log5 unmodified linesif mime_type not in allowed_file_types:return gr.Textbox("File type disallowed", visible=True), file_uploads_log# Sanitize file nameoriginal_name = os.path.basename(file.name)sanitized_name = re.sub(r"[^\w\-.]", "_", original_name) # Replace any non-alphanumeric, non-dash, or non-dot characters with underscorestype_to_ext = {}for ext, t in mimetypes.types_map.items():if t not in type_to_ext:type_to_ext[t] = ext# Ensure the extension correlates to the mime typesanitized_name = sanitized_name.split(".")[:-1]sanitized_name.append("" + type_to_ext[mime_type])sanitized_name = "".join(sanitized_name)# Save the uploaded file to the specified folderfile_path = os.path.join(self.file_upload_folder, os.path.basename(sanitized_name))shutil.copy(file.name, file_path)1 unmodified linedef log_user_message(self, text_input, file_uploads_log):return (text_input+ (f"\nYou have been provided with these files, which might be helpful or not: {file_uploads_log}"if len(file_uploads_log) > 0else ""),"",)def launch(self, **kwargs):import gradio as grwith gr.Blocks(fill_height=True) as demo:stored_messages = gr.State([])8 unmodified linesresizeable=True,scale=1,)# If an upload folder is provided, enable the upload featureif self.file_upload_folder is not None:upload_file = gr.File(label="Upload a file")upload_status = gr.Textbox(label="Upload Status", interactive=False, visible=False)2 unmodified lines[upload_file, file_uploads_log],[upload_status, file_uploads_log],)text_input = gr.Textbox(lines=1, label="Chat Message")text_input.submit(self.log_user_message,1 unmodified line[stored_messages, text_input],).then(self.interact_with_agent, [stored_messages, chatbot], [chatbot])demo.launch(debug=True, share=True, show_error=True, **kwargs)__all__ = ["stream_to_gradio", "GradioUI"]23 unmodified lines24252627282930313233343536373839404142434445464748495051525354551 unmodified line5758596061626364656667686970717273741 unmodified line7677787980818283848586878889909192939495969798991001011021031041051061 unmodified line1081091101111121131141151161171181191201211 unmodified line1231241251261271281291301311321331341351361371381391401411421431441451461471481491501 unmodified line1521531541551561571581591601611621631641655 unmodified lines1711721731741751761771781791801811821831841851861871881 unmodified line1901911921931941951961971981992002012022032042058 unmodified lines2142152162172182192202 unmodified lines2232242252262272282291 unmodified line23123223323423523623723823924024124224324424524624724824925023 unmodified linesfrom smolagents.memory import MemoryStepfrom smolagents.utils import _is_package_availabledef pull_messages_from_step(step_log: MemoryStep):import gradio as grif 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)}"args = first_tool_call.argumentscontent = str(args.get("answer", str(args))) if isinstance(args, dict) else 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```"1 unmodified lineparent_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_toolif hasattr(step_log, "observations") and step_log.observations and step_log.observations.strip():log_content = re.sub(r"^Execution logs:\s*", "", step_log.observations.strip())yield gr.ChatMessage(role="assistant",content=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",1 unmodified linemetadata={"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 = f"{step_number}"if hasattr(step_log, "input_token_count") and hasattr(step_log, "output_token_count"):token_str = f" | Input-tokens:{step_log.input_token_count:,} | Output-tokens:{step_log.output_token_count:,}"step_footnote += token_strif hasattr(step_log, "duration"):step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else Nonestep_footnote += step_durationstep_footnote = f'<span style="color: #bbbbc2; font-size: 12px;">{step_footnote}</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):if not _is_package_available("gradio"):raise ModuleNotFoundError("Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`")import gradio as grtotal_input_tokens = 0total_output_tokens = 0for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):if hasattr(agent.model, "last_input_token_count"):total_input_tokens += agent.model.last_input_token_counttotal_output_tokens += agent.model.last_output_token_count1 unmodified linestep_log.input_token_count = agent.model.last_input_token_countstep_log.output_token_count = agent.model.last_output_token_countfor message in pull_messages_from_step(step_log):yield messagefrom smolagents.agents import FinalAnswerStepif isinstance(step_log, FinalAnswerStep):final_output = step_log.final_answerelse:final_output = getattr(step_log, "tool_output", None)if not final_output and hasattr(step_log, "tool_calls"):for call in step_log.tool_calls:1 unmodified linefinal_output = call.arguments.get("answer")breakfinal_output = handle_agent_output_types(final_output)if isinstance(final_output, AgentText):yield gr.ChatMessage(role="assistant", content=final_output.to_string().strip())elif isinstance(final_output, AgentImage):yield gr.ChatMessage(role="assistant", content={"path": final_output.to_string(), "mime_type": "image/png"})elif isinstance(final_output, AgentAudio):yield gr.ChatMessage(role="assistant", content={"path": final_output.to_string(), "mime_type": "audio/wav"})else:yield gr.ChatMessage(role="assistant", content=str(final_output).strip())class GradioUI: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 = agentself.file_upload_folder = file_upload_folderif self.file_upload_folder and not os.path.exists(file_upload_folder):os.mkdir(file_upload_folder)def interact_with_agent(self, prompt, messages):import gradio as grmessages.append(gr.ChatMessage(role="user", content=prompt))yield messagesfor msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):1 unmodified lineyield messagesyield messagesdef upload_file(self, file, file_uploads_log, allowed_file_types=None):import gradio as grif allowed_file_types is None:allowed_file_types = ["application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","text/plain",]if file is None:return gr.Textbox("No file uploaded", visible=True), file_uploads_log5 unmodified linesif mime_type not in allowed_file_types:return gr.Textbox("File type disallowed", visible=True), file_uploads_logoriginal_name = os.path.basename(file.name)sanitized_name = re.sub(r"[^\w\-.]", "_", original_name)type_to_ext = {}for ext, t in mimetypes.types_map.items():if t not in type_to_ext:type_to_ext[t] = extsanitized_name = sanitized_name.split(".")[:-1]sanitized_name.append("" + type_to_ext[mime_type])sanitized_name = "".join(sanitized_name)file_path = os.path.join(self.file_upload_folder, os.path.basename(sanitized_name))shutil.copy(file.name, file_path)1 unmodified linedef log_user_message(self, text_input, file_uploads_log):return (text_input + (f"\nYou have been provided with these files, which might be helpful or not: {file_uploads_log}"if len(file_uploads_log) > 0 else ""),"",)def launch(self, **kwargs):import gradio as grfrom submit import main as submit_answerswith gr.Blocks(fill_height=True) as demo:stored_messages = gr.State([])8 unmodified linesresizeable=True,scale=1,)if self.file_upload_folder is not None:upload_file = gr.File(label="Upload a file")upload_status = gr.Textbox(label="Upload Status", interactive=False, visible=False)2 unmodified lines[upload_file, file_uploads_log],[upload_status, file_uploads_log],)text_input = gr.Textbox(lines=1, label="Chat Message")text_input.submit(self.log_user_message,1 unmodified line[stored_messages, text_input],).then(self.interact_with_agent, [stored_messages, chatbot], [chatbot])with gr.Row():submit_btn = gr.Button("📤 Submit All GAIA Answers")submission_status = gr.Textbox(label="Submission Status", interactive=False)def trigger_submission():submit_answers()return "✅ Submitted to GAIA scoring API"submit_btn.click(fn=trigger_submission,inputs=[],outputs=[submission_status])demo.launch(debug=True, share=True, show_error=True, **kwargs)__all__ = ["stream_to_gradio", "GradioUI"]
Gradio_UI.py+56-118