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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
|
| 3 |
+
import gradio as gr
|
| 4 |
+
|
| 5 |
+
import mimetypes
|
| 6 |
+
import os
|
| 7 |
+
import re
|
| 8 |
+
import shutil
|
| 9 |
+
from typing import Optional
|
| 10 |
+
|
| 11 |
+
from smolagents.agent_types import AgentAudio, AgentImage, AgentText, handle_agent_output_types
|
| 12 |
+
from smolagents.agents import ActionStep, MultiStepAgent
|
| 13 |
+
from smolagents.memory import MemoryStep
|
| 14 |
+
from smolagents.utils import _is_package_available
|
| 15 |
+
|
| 16 |
+
from pydub.audio_segment import AudioSegment
|
| 17 |
+
from SoundFile import SoundFile
|
| 18 |
+
|
| 19 |
+
def clean_up_LLM_output(p_output: str):
|
| 20 |
+
# Remove any trailing <end_code> and extra backticks, handling multiple possible formats
|
| 21 |
+
r_output = re.sub(r"```\s*<end_code>", "```", p_output) # handles ```<end_code>
|
| 22 |
+
r_output = re.sub(r"<end_code>\s*```", "```", r_output) # handles <end_code>```
|
| 23 |
+
r_output = re.sub(r"```\s*\n\s*<end_code>", "```", r_output) # handles ```\n<end_code>
|
| 24 |
+
r_output = r_output.strip()
|
| 25 |
+
return r_output
|
| 26 |
+
|
| 27 |
+
def clean_up_code_output(p_content: str):
|
| 28 |
+
r_content = re.sub(r"```.*?\n", "", p_content) # Remove existing code blocks
|
| 29 |
+
r_content = re.sub(r"\s*<end_code>\s*", "", r_content) # Remove end_code tags
|
| 30 |
+
r_content = r_content.strip()
|
| 31 |
+
if not r_content.startswith("```python"):
|
| 32 |
+
r_content = f"```python\n{r_content}\n```"
|
| 33 |
+
return r_content
|
| 34 |
+
|
| 35 |
+
def pull_messages_from_step(step_log: MemoryStep):
|
| 36 |
+
"""Extract ChatMessage objects from agent steps with proper nesting"""
|
| 37 |
+
|
| 38 |
+
print(f"MEMORY STEP => {step_log}")
|
| 39 |
+
if isinstance(step_log, ActionStep):
|
| 40 |
+
# Output the step number
|
| 41 |
+
step_number = f"Step {step_log.step_number}" if step_log.step_number is not None else ""
|
| 42 |
+
yield gr.ChatMessage(role="assistant", content=f"**{step_number}**")
|
| 43 |
+
|
| 44 |
+
# First yield the thought/reasoning from the LLM
|
| 45 |
+
if hasattr(step_log, "model_output") and step_log.model_output is not None:
|
| 46 |
+
model_output = clean_up_LLM_output(step_log.model_output.strip())
|
| 47 |
+
print(f"model_output={model_output}")
|
| 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 |
+
content = clean_up_code_output(content)
|
| 66 |
+
|
| 67 |
+
parent_message_tool = gr.ChatMessage(
|
| 68 |
+
role="assistant",
|
| 69 |
+
content=content,
|
| 70 |
+
metadata={
|
| 71 |
+
"title": f"🛠️ Used tool {first_tool_call.name}",
|
| 72 |
+
"id": parent_id,
|
| 73 |
+
"status": "pending",
|
| 74 |
+
},
|
| 75 |
+
)
|
| 76 |
+
yield parent_message_tool
|
| 77 |
+
|
| 78 |
+
# Nesting execution logs under the tool call if they exist
|
| 79 |
+
if hasattr(step_log, "observations") and (
|
| 80 |
+
step_log.observations is not None and step_log.observations.strip()
|
| 81 |
+
): # Only yield execution logs if there's actual content
|
| 82 |
+
log_content = step_log.observations.strip()
|
| 83 |
+
if log_content:
|
| 84 |
+
log_content = re.sub(r"^Execution logs:\s*", "", log_content)
|
| 85 |
+
yield gr.ChatMessage(
|
| 86 |
+
role="assistant",
|
| 87 |
+
content=f"{log_content}",
|
| 88 |
+
metadata={"title": "📝 Execution Logs", "parent_id": parent_id, "status": "done"},
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
# Nesting any errors under the tool call
|
| 92 |
+
if hasattr(step_log, "error") and step_log.error is not None:
|
| 93 |
+
yield gr.ChatMessage(
|
| 94 |
+
role="assistant",
|
| 95 |
+
content=str(step_log.error),
|
| 96 |
+
metadata={"title": "💥 Error", "parent_id": parent_id, "status": "done"},
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
# Update parent message metadata to done status without yielding a new message
|
| 100 |
+
parent_message_tool.metadata["status"] = "done"
|
| 101 |
+
|
| 102 |
+
# Handle standalone errors but not from tool calls
|
| 103 |
+
elif hasattr(step_log, "error") and step_log.error is not None:
|
| 104 |
+
yield gr.ChatMessage(role="assistant", content=str(step_log.error), metadata={"title": "💥 Error"})
|
| 105 |
+
|
| 106 |
+
# Calculate duration and token information
|
| 107 |
+
step_footnote = f"{step_number}"
|
| 108 |
+
if hasattr(step_log, "input_token_count") and hasattr(step_log, "output_token_count"):
|
| 109 |
+
token_str = (
|
| 110 |
+
f" | Input-tokens:{step_log.input_token_count:,} | Output-tokens:{step_log.output_token_count:,}"
|
| 111 |
+
)
|
| 112 |
+
step_footnote += token_str
|
| 113 |
+
if hasattr(step_log, "duration"):
|
| 114 |
+
step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else None
|
| 115 |
+
step_footnote += step_duration
|
| 116 |
+
step_footnote = f"""<span style="color: #bbbbc2; font-size: 12px;">{step_footnote}</span> """
|
| 117 |
+
yield gr.ChatMessage(role="assistant", content=f"{step_footnote}")
|
| 118 |
+
yield gr.ChatMessage(role="assistant", content="-----")
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def stream_to_gradio(agent, task: str, reset_agent_memory: bool = False, additional_args: Optional[dict] = None):
|
| 122 |
+
"""Runs an agent with the given task and streams the messages from the agent as gradio ChatMessages."""
|
| 123 |
+
|
| 124 |
+
print(f"agent ={agent}, task ={task}, reset_agent_memory={reset_agent_memory}, additional_args={additional_args}")
|
| 125 |
+
total_input_tokens = 0
|
| 126 |
+
total_output_tokens = 0
|
| 127 |
+
|
| 128 |
+
for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):
|
| 129 |
+
# Track tokens if model provides them
|
| 130 |
+
if hasattr(agent.model, "last_input_token_count"):
|
| 131 |
+
total_input_tokens += agent.model.last_input_token_count
|
| 132 |
+
total_output_tokens += agent.model.last_output_token_count
|
| 133 |
+
if isinstance(step_log, ActionStep):
|
| 134 |
+
step_log.input_token_count = agent.model.last_input_token_count
|
| 135 |
+
step_log.output_token_count = agent.model.last_output_token_count
|
| 136 |
+
|
| 137 |
+
for message in pull_messages_from_step(
|
| 138 |
+
step_log,
|
| 139 |
+
):
|
| 140 |
+
yield message
|
| 141 |
+
|
| 142 |
+
final_answer = step_log # Last log is the run's final_answer
|
| 143 |
+
final_answer = handle_agent_output_types(final_answer)
|
| 144 |
+
|
| 145 |
+
if isinstance(final_answer, AgentText):
|
| 146 |
+
yield gr.ChatMessage(
|
| 147 |
+
role="assistant",
|
| 148 |
+
content=f"**Final answer:**\n{final_answer.to_string()}\n",
|
| 149 |
+
)
|
| 150 |
+
elif isinstance(final_answer, AgentImage):
|
| 151 |
+
yield gr.ChatMessage(
|
| 152 |
+
role="assistant",
|
| 153 |
+
content={"path": final_answer.to_string(), "mime_type": "image/png"},
|
| 154 |
+
)
|
| 155 |
+
elif isinstance(final_answer, AgentAudio):
|
| 156 |
+
yield gr.ChatMessage(
|
| 157 |
+
role="assistant",
|
| 158 |
+
content={"path": final_answer.to_string(), "mime_type": "audio/wav"},
|
| 159 |
+
)
|
| 160 |
+
#elif isinstance(final_answer, AudioSegment):
|
| 161 |
+
elif isinstance(final_answer, SoundFile):
|
| 162 |
+
import os.path
|
| 163 |
+
|
| 164 |
+
file_path = "./resources/GenAIRev.mp3"
|
| 165 |
+
|
| 166 |
+
if os.path.isfile(file_path):
|
| 167 |
+
print(f"The file '{file_path}' exists.")
|
| 168 |
+
else:
|
| 169 |
+
print(f"The file '{file_path}' does not exist.")
|
| 170 |
+
|
| 171 |
+
yield gr.ChatMessage(
|
| 172 |
+
role="assistant",
|
| 173 |
+
content=gr.Audio(value=final_answer.get_filepath(), autoplay=True),
|
| 174 |
+
)
|
| 175 |
+
else:
|
| 176 |
+
yield gr.ChatMessage(role="assistant", content=f"**Final answer:** {str(final_answer)}")
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class GradioUI:
|
| 180 |
+
def __init__(self, agent: MultiStepAgent):
|
| 181 |
+
self.agent = agent
|
| 182 |
+
|
| 183 |
+
def interact_with_agent(self, prompt, messages):
|
| 184 |
+
|
| 185 |
+
print(f"interact_with_agent => prompt => {prompt}, messages => {messages}")
|
| 186 |
+
messages.append(gr.ChatMessage(role="user", content=prompt))
|
| 187 |
+
yield messages
|
| 188 |
+
for msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):
|
| 189 |
+
messages.append(msg)
|
| 190 |
+
yield messages
|
| 191 |
+
yield messages
|
| 192 |
+
|
| 193 |
+
def log_user_message(self, text_input):
|
| 194 |
+
return text_input, ""
|
| 195 |
+
|
| 196 |
+
def launch(self, **kwargs):
|
| 197 |
+
with gr.Blocks(fill_height=True) as demo:
|
| 198 |
+
stored_messages = gr.State([])
|
| 199 |
+
|
| 200 |
+
history = [
|
| 201 |
+
gr.ChatMessage(role="assistant", content="How can I help you?") ]
|
| 202 |
+
|
| 203 |
+
chatbot = gr.Chatbot(
|
| 204 |
+
history,
|
| 205 |
+
label="Agent",
|
| 206 |
+
type="messages",
|
| 207 |
+
avatar_images=(
|
| 208 |
+
None,
|
| 209 |
+
"./resources/pop_quiz_master.png",
|
| 210 |
+
#"https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/Alfred.png",
|
| 211 |
+
),
|
| 212 |
+
resizeable=True,
|
| 213 |
+
scale=1,
|
| 214 |
+
)
|
| 215 |
+
text_input = gr.Textbox(lines=1, label="Chat Message")
|
| 216 |
+
text_input.submit(
|
| 217 |
+
self.log_user_message,
|
| 218 |
+
[text_input],
|
| 219 |
+
[stored_messages, text_input],
|
| 220 |
+
).then(self.interact_with_agent, [stored_messages, chatbot], [chatbot])
|
| 221 |
+
|
| 222 |
+
demo.launch(debug=True, share=False, **kwargs)
|
| 223 |
+
|
| 224 |
+
__all__ = ["stream_to_gradio", "GradioUI"]
|