RemVdH/Test_based_on_agent_template
0
1#!/usr/bin/env python2# coding=utf-83# 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 at8#9# http://www.apache.org/licenses/LICENSE-2.010#11# Unless required by applicable law or agreed to in writing, software12# 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 and15# limitations under the License.16import mimetypes17import os18import re19import shutil20from typing import Optional21 22from smolagents.agent_types import AgentAudio, AgentImage, AgentText, handle_agent_output_types23from smolagents.agents import ActionStep, MultiStepAgent24from smolagents.memory import MemoryStep25from smolagents.utils import _is_package_available26 27def pull_messages_from_step(28 step_log: MemoryStep,29):30 """Extract ChatMessage objects from agent steps with proper nesting"""31 import gradio as gr32 33 if isinstance(step_log, ActionStep):34 # Output the step number35 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 LLM39 if hasattr(step_log, "model_output") and step_log.model_output is not None:40 # Clean up the LLM output41 model_output = step_log.model_output.strip()42 # Remove any trailing <end_code> and extra backticks, handling multiple possible formats43 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 message50 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 info56 # First we will handle arguments based on type57 args = first_tool_call.arguments58 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 tags65 content = re.sub(r"```.*?\n", "", content) # Remove existing code blocks66 content = re.sub(r"\s*<end_code>\s*", "", content) # Remove end_code tags67 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_tool81 82 # Nesting execution logs under the tool call if they exist83 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 content86 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 call96 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 message104 parent_message_tool.metadata["status"] = "done"105 106 # Handle standalone errors but not from tool calls107 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 information111 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_str117 if hasattr(step_log, "duration"):118 step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else None119 step_footnote += step_duration120 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 125def 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 gr137 138 total_input_tokens = 0139 total_output_tokens = 0140 141 for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):142 # Track tokens if model provides them143 if hasattr(agent.model, "last_input_token_count"):144 total_input_tokens += agent.model.last_input_token_count145 total_output_tokens += agent.model.last_output_token_count146 if isinstance(step_log, ActionStep):147 step_log.input_token_count = agent.model.last_input_token_count148 step_log.output_token_count = agent.model.last_output_token_count149 150 for message in pull_messages_from_step(151 step_log,152 ):153 yield message154 155 final_answer = step_log # Last log is the run's final_answer156 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 177class 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 = agent186 self.file_upload_folder = file_upload_folder187 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 gr193 194 messages.append(gr.ChatMessage(role="user", content=prompt))195 yield messages196 for msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):197 messages.append(msg)198 yield messages199 yield messages200 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 .txt213 """214 import gradio as gr215 216 if file is None:217 return gr.Textbox("No file uploaded", visible=True), file_uploads_log218 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_log223 224 if mime_type not in allowed_file_types:225 return gr.Textbox("File type disallowed", visible=True), file_uploads_log226 227 # Sanitize file name228 original_name = os.path.basename(file.name)229 sanitized_name = re.sub(230 r"[^\w\-.]", "_", original_name231 ) # Replace any non-alphanumeric, non-dash, or non-dot characters with underscores232 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] = ext237 238 # Ensure the extension correlates to the mime type239 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 folder244 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_input252 + (253 f"\nYou have been provided with these files, which might be helpful or not: {file_uploads_log}"254 if len(file_uploads_log) > 0255 else ""256 ),257 "",258 )259 260 def launch(self, **kwargs):261 import gradio as gr262 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,271 "https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/Alfred.png",272 ),273 resizeable=True,274 scale=1,275 )276 # If an upload folder is provided, enable the upload feature277 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"]