SimpleSam/Manyata_agent
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 27 28def pull_messages_from_step(29 step_log: MemoryStep,30):31 """Extract ChatMessage objects from agent steps with proper nesting"""32 import gradio as gr33 34 if isinstance(step_log, ActionStep):35 # Output the step number36 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 LLM40 # if hasattr(step_log, "model_output") and step_log.model_output is not None:41 # Clean up the LLM output42 # model_output = step_log.model_output.strip()43 # Remove any trailing <end_code> and extra backticks, handling multiple possible formats44 # 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 message51 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 info57 # First we will handle arguments based on type58 args = first_tool_call.arguments59 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 tags66 content = re.sub(r"```.*?\n", "", content) # Remove existing code blocks67 content = re.sub(r"\s*<end_code>\s*", "", content) # Remove end_code tags68 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_tool82 83 # Nesting execution logs under the tool call if they exist84 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 content87 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 call97 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 message105 parent_message_tool.metadata["status"] = "done"106 107 # Handle standalone errors but not from tool calls108 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 information112 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_str118 if hasattr(step_log, "duration"):119 step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else None120 step_footnote += step_duration121 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 126def 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 gr138 139 total_input_tokens = 0140 total_output_tokens = 0141 142 for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):143 # Track tokens if model provides them144 if hasattr(agent.model, "last_input_token_count"):145 total_input_tokens += agent.model.last_input_token_count146 total_output_tokens += agent.model.last_output_token_count147 if isinstance(step_log, ActionStep):148 step_log.input_token_count = agent.model.last_input_token_count149 step_log.output_token_count = agent.model.last_output_token_count150 151 # for message in pull_messages_from_step(152 # step_log,153 # ):154 # yield message155 156 final_answer = step_log # Last log is the run's final_answer157 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 content=f"\n{final_answer.to_string.replace("FinalAnswerStep", "").replace("(final_answer='", "").replace("')", "")}\n",164 )165 elif isinstance(final_answer, AgentImage):166 yield gr.ChatMessage(167 role="assistant",168 content={"path": final_answer.to_string(), "mime_type": "image/png"},169 )170 elif isinstance(final_answer, AgentAudio):171 yield gr.ChatMessage(172 role="assistant",173 content={"path": final_answer.to_string(), "mime_type": "audio/wav"},174 )175 else:176 #yield gr.ChatMessage(role="assistant", content=f"**Final answer:** {str(final_answer)}")177 yield gr.ChatMessage(role="assistant", content=f"{str(final_answer).replace("FinalAnswerStep", "").replace("(final_answer='", "").replace("')", "")}")178 179 180class GradioUI:181 """A one-line interface to launch your agent in Gradio"""182 183 def __init__(self, agent: MultiStepAgent, file_upload_folder: str | None = None):184 if not _is_package_available("gradio"):185 raise ModuleNotFoundError(186 "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"187 )188 self.agent = agent189 self.file_upload_folder = file_upload_folder190 if self.file_upload_folder is not None:191 if not os.path.exists(file_upload_folder):192 os.mkdir(file_upload_folder)193 194 def interact_with_agent(self, prompt, messages):195 import gradio as gr196 197 messages.append(gr.ChatMessage(role="user", content=prompt))198 yield messages199 for msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):200 messages.append(msg)201 yield messages202 yield messages203 204 def upload_file(205 self,206 file,207 file_uploads_log,208 allowed_file_types=[209 "application/pdf",210 "application/vnd.openxmlformats-officedocument.wordprocessingml.document",211 "text/plain",212 ],213 ):214 """215 Handle file uploads, default allowed types are .pdf, .docx, and .txt216 """217 import gradio as gr218 219 if file is None:220 return gr.Textbox("No file uploaded", visible=True), file_uploads_log221 222 try:223 mime_type, _ = mimetypes.guess_type(file.name)224 except Exception as e:225 return gr.Textbox(f"Error: {e}", visible=True), file_uploads_log226 227 if mime_type not in allowed_file_types:228 return gr.Textbox("File type disallowed", visible=True), file_uploads_log229 230 # Sanitize file name231 original_name = os.path.basename(file.name)232 sanitized_name = re.sub(233 r"[^\w\-.]", "_", original_name234 ) # Replace any non-alphanumeric, non-dash, or non-dot characters with underscores235 236 type_to_ext = {}237 for ext, t in mimetypes.types_map.items():238 if t not in type_to_ext:239 type_to_ext[t] = ext240 241 # Ensure the extension correlates to the mime type242 sanitized_name = sanitized_name.split(".")[:-1]243 sanitized_name.append("" + type_to_ext[mime_type])244 sanitized_name = "".join(sanitized_name)245 246 # Save the uploaded file to the specified folder247 file_path = os.path.join(self.file_upload_folder, os.path.basename(sanitized_name))248 shutil.copy(file.name, file_path)249 250 return gr.Textbox(f"File uploaded: {file_path}", visible=True), file_uploads_log + [file_path]251 252 def log_user_message(self, text_input, file_uploads_log):253 return (254 text_input255 + (256 f"\nYou have been provided with these files, which might be helpful or not: {file_uploads_log}"257 if len(file_uploads_log) > 0258 else ""259 ),260 "",261 )262 263 def launch(self, **kwargs):264 import gradio as gr265 266 with gr.Blocks(fill_height=True) as demo:267 stored_messages = gr.State([])268 file_uploads_log = gr.State([])269 chatbot = gr.Chatbot(270 label="Agent",271 type="messages",272 avatar_images=(273 None,274 "https://dcatabydbmnedjtqnvsb.supabase.co/storage/v1/object/public/manyata/manyata_files/logo.svg",275 ),276 resizeable=True,277 scale=1,278 )279 # If an upload folder is provided, enable the upload feature280 if self.file_upload_folder is not None:281 upload_file = gr.File(label="Upload a file")282 upload_status = gr.Textbox(label="Upload Status", interactive=False, visible=False)283 upload_file.change(284 self.upload_file,285 [upload_file, file_uploads_log],286 [upload_status, file_uploads_log],287 )288 text_input = gr.Textbox(lines=1, label="Chat Message")289 text_input.submit(290 self.log_user_message,291 [text_input, file_uploads_log],292 [stored_messages, text_input],293 ).then(self.interact_with_agent, [stored_messages, chatbot], [chatbot])294 295 demo.launch(debug=True, share=True, **kwargs)296 297 298__all__ = ["stream_to_gradio", "GradioUI"]