MuhammadQASIM111 commited on
Commit
e920e8d
·
verified ·
1 Parent(s): d04f615

Update Gradio_UI.py

Browse files
Files changed (1) hide show
  1. Gradio_UI.py +63 -124
Gradio_UI.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import mimetypes
2
  import os
3
  import re
@@ -9,103 +10,7 @@ from smolagents.agents import ActionStep, MultiStepAgent
9
  from smolagents.memory import MemoryStep
10
  from smolagents.utils import _is_package_available
11
 
12
- def pull_messages_from_step(step_log: MemoryStep):
13
- import gradio as gr
14
-
15
- if isinstance(step_log, ActionStep):
16
- step_number = f"Step {step_log.step_number}" if step_log.step_number is not None else ""
17
- yield gr.ChatMessage(role="assistant", content=f"**{step_number}**")
18
-
19
- if hasattr(step_log, "model_output") and step_log.model_output is not None:
20
- model_output = step_log.model_output.strip()
21
- model_output = re.sub(r"```\s*<end_code>", "```", model_output)
22
- model_output = re.sub(r"<end_code>\s*```", "```", model_output)
23
- model_output = re.sub(r"```\s*\n\s*<end_code>", "```", model_output)
24
- model_output = model_output.strip()
25
- yield gr.ChatMessage(role="assistant", content=model_output)
26
-
27
- if hasattr(step_log, "tool_calls") and step_log.tool_calls is not None:
28
- first_tool_call = step_log.tool_calls[0]
29
- used_code = first_tool_call.name == "python_interpreter"
30
- parent_id = f"call_{len(step_log.tool_calls)}"
31
- args = first_tool_call.arguments
32
- content = str(args.get("answer", str(args))) if isinstance(args, dict) else str(args).strip()
33
- if used_code:
34
- content = re.sub(r"```.*?\n", "", content)
35
- content = re.sub(r"\s*<end_code>\s*", "", content)
36
- content = content.strip()
37
- if not content.startswith("```python"):
38
- content = f"```python\n{content}\n```"
39
-
40
- parent_message_tool = gr.ChatMessage(
41
- role="assistant",
42
- content=content,
43
- metadata={"title": f"🛠️ Used tool {first_tool_call.name}", "id": parent_id, "status": "pending"},
44
- )
45
- yield parent_message_tool
46
-
47
- if hasattr(step_log, "observations") and step_log.observations and step_log.observations.strip():
48
- log_content = step_log.observations.strip()
49
- log_content = re.sub(r"^Execution logs:\s*", "", log_content)
50
- yield gr.ChatMessage(
51
- role="assistant",
52
- content=f"{log_content}",
53
- metadata={"title": "📝 Execution Logs", "parent_id": parent_id, "status": "done"},
54
- )
55
-
56
- if hasattr(step_log, "error") and step_log.error is not None:
57
- yield gr.ChatMessage(
58
- role="assistant",
59
- content=str(step_log.error),
60
- metadata={"title": "💥 Error", "parent_id": parent_id, "status": "done"},
61
- )
62
-
63
- parent_message_tool.metadata["status"] = "done"
64
-
65
- elif hasattr(step_log, "error") and step_log.error is not None:
66
- yield gr.ChatMessage(role="assistant", content=str(step_log.error), metadata={"title": "💥 Error"})
67
-
68
- step_footnote = f"{step_number}"
69
- if hasattr(step_log, "input_token_count") and hasattr(step_log, "output_token_count"):
70
- token_str = f" | Input-tokens:{step_log.input_token_count:,} | Output-tokens:{step_log.output_token_count:,}"
71
- step_footnote += token_str
72
- if hasattr(step_log, "duration"):
73
- step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else None
74
- step_footnote += step_duration
75
- step_footnote = f"""<span style=\"color: #bbbbc2; font-size: 12px;\">{step_footnote}</span> """
76
- yield gr.ChatMessage(role="assistant", content=f"{step_footnote}")
77
- yield gr.ChatMessage(role="assistant", content="-----")
78
-
79
- def stream_to_gradio(agent, task: str, reset_agent_memory: bool = False, additional_args: Optional[dict] = None):
80
- if not _is_package_available("gradio"):
81
- raise ModuleNotFoundError("Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`")
82
- import gradio as gr
83
-
84
- total_input_tokens = 0
85
- total_output_tokens = 0
86
-
87
- for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):
88
- if hasattr(agent.model, "last_input_token_count"):
89
- total_input_tokens += agent.model.last_input_token_count
90
- total_output_tokens += agent.model.last_output_token_count
91
- if isinstance(step_log, ActionStep):
92
- step_log.input_token_count = agent.model.last_input_token_count
93
- step_log.output_token_count = agent.model.last_output_token_count
94
-
95
- for message in pull_messages_from_step(step_log):
96
- yield message
97
-
98
- final_answer = step_log
99
- final_answer = handle_agent_output_types(final_answer)
100
-
101
- if isinstance(final_answer, AgentText):
102
- yield gr.ChatMessage(role="assistant", content=f"**Final answer:**\n{final_answer.to_string()}\n")
103
- elif isinstance(final_answer, AgentImage):
104
- yield gr.ChatMessage(role="assistant", content={"path": final_answer.to_string(), "mime_type": "image/png"})
105
- elif isinstance(final_answer, AgentAudio):
106
- yield gr.ChatMessage(role="assistant", content={"path": final_answer.to_string(), "mime_type": "audio/wav"})
107
- else:
108
- yield gr.ChatMessage(role="assistant", content=f"**Final answer:** {str(final_answer)}")
109
 
110
  class GradioUI:
111
  def __init__(self, agent: MultiStepAgent, file_upload_folder: str | None = None):
@@ -116,14 +21,35 @@ class GradioUI:
116
  if self.file_upload_folder is not None and not os.path.exists(file_upload_folder):
117
  os.mkdir(file_upload_folder)
118
 
119
- def interact_with_agent(self, prompt, messages):
120
- import gradio as gr
121
- messages.append(gr.ChatMessage(role="user", content=prompt))
122
- yield messages
123
- for msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):
124
- messages.append(msg)
125
- yield messages
126
- yield messages
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
 
128
  def upload_file(self, file, file_uploads_log, allowed_file_types=None):
129
  import gradio as gr
@@ -144,8 +70,11 @@ class GradioUI:
144
  original_name = os.path.basename(file.name)
145
  sanitized_name = re.sub(r"[^\w\-.]", "_", original_name)
146
  ext_map = {v: k for k, v in mimetypes.types_map.items()}
147
- sanitized_name = sanitized_name.split(".")[:-1] + [ext_map.get(mime_type, "txt")]
148
- sanitized_name = "".join(sanitized_name)
 
 
 
149
 
150
  file_path = os.path.join(self.file_upload_folder, sanitized_name)
151
  shutil.copy(file.name, file_path)
@@ -158,31 +87,41 @@ class GradioUI:
158
  context += f"\nAttached files: {file_uploads_log}"
159
  return context, ""
160
 
 
161
  def launch(self, **kwargs):
162
  import gradio as gr
163
 
164
  with gr.Blocks(fill_height=True) as demo:
165
- stored_messages = gr.State([])
166
  file_uploads_log = gr.State([])
167
- chatbot = gr.Chatbot(
168
- label="Agent",
169
- type="messages",
170
- avatar_images=(
171
- None,
172
- "https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/Alfred.png",
 
 
 
 
 
 
 
173
  ),
174
- resizeable=True,
175
- scale=1,
 
176
  )
177
- if self.file_upload_folder is not None:
178
- upload_file = gr.File(label="Upload a file")
179
- upload_status = gr.Textbox(label="Upload Status", interactive=False, visible=False)
180
- upload_file.change(self.upload_file, [upload_file, file_uploads_log], [upload_status, file_uploads_log])
181
 
182
- text_input = gr.Textbox(lines=1, label="Chat Message")
183
- text_input.submit(self.log_user_message, [text_input, file_uploads_log], [stored_messages, text_input])\
184
- .then(self.interact_with_agent, [stored_messages, chatbot], [chatbot])
 
 
 
 
 
 
185
 
186
  demo.launch(debug=True, share=True, **kwargs)
187
 
188
- __all__ = ["stream_to_gradio", "GradioUI"]
 
1
+ import gradio as gr
2
  import mimetypes
3
  import os
4
  import re
 
10
  from smolagents.memory import MemoryStep
11
  from smolagents.utils import _is_package_available
12
 
13
+ # ... (keep your existing pull_messages_from_step and stream_to_gradio functions as they are)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  class GradioUI:
16
  def __init__(self, agent: MultiStepAgent, file_upload_folder: str | None = None):
 
21
  if self.file_upload_folder is not None and not os.path.exists(file_upload_folder):
22
  os.mkdir(file_upload_folder)
23
 
24
+ # Your existing interact_with_agent, upload_file, and log_user_message methods remain the same
25
+ def interact_with_agent(self, prompt, chat_history): # Renamed 'messages' to 'chat_history' for clarity with ChatInterface
26
+ # The chat_history from ChatInterface is a list of [user_message, agent_response] tuples
27
+ # You'll need to adapt your processing slightly
28
+ yield chat_history # Yield initial history to show user message
29
+
30
+ # The prompt here will already be the user's input, so no need to append it to messages again
31
+ # For demonstration, I'll assume stream_to_gradio directly yields content for the chatbot
32
+ # You might need to adjust stream_to_gradio if it yields gr.ChatMessage objects directly,
33
+ # as gr.ChatInterface expects tuples.
34
+
35
+ # Example adaptation (might need further refinement based on stream_to_gradio's exact output)
36
+ full_response_content = ""
37
+ for msg_obj in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):
38
+ if isinstance(msg_obj, gr.ChatMessage):
39
+ # For simplicity, concatenate text content. For images/audio, you'd need more complex handling
40
+ if isinstance(msg_obj.content, str):
41
+ full_response_content += msg_obj.content + "\n"
42
+ elif isinstance(msg_obj.content, dict) and 'path' in msg_obj.content:
43
+ # Handle image/audio paths
44
+ full_response_content += f"[{msg_obj.content['mime_type']} at {msg_obj.content['path']}]\n"
45
+
46
+ # Update the last assistant message in the chat history
47
+ if chat_history and chat_history[-1][1] is None: # If the last assistant message is empty
48
+ chat_history[-1][1] = full_response_content
49
+ else:
50
+ chat_history.append([prompt, full_response_content]) # Append new turn
51
+ yield chat_history
52
+
53
 
54
  def upload_file(self, file, file_uploads_log, allowed_file_types=None):
55
  import gradio as gr
 
70
  original_name = os.path.basename(file.name)
71
  sanitized_name = re.sub(r"[^\w\-.]", "_", original_name)
72
  ext_map = {v: k for k, v in mimetypes.types_map.items()}
73
+ # Fix for sanitized_name generation
74
+ base_name, ext = os.path.splitext(original_name)
75
+ if not ext: # No extension, use 'txt' as default if mime_type is not specific
76
+ ext = "." + ext_map.get(mime_type, "txt")
77
+ sanitized_name = re.sub(r"[^\w\-.]", "_", base_name) + ext
78
 
79
  file_path = os.path.join(self.file_upload_folder, sanitized_name)
80
  shutil.copy(file.name, file_path)
 
87
  context += f"\nAttached files: {file_uploads_log}"
88
  return context, ""
89
 
90
+
91
  def launch(self, **kwargs):
92
  import gradio as gr
93
 
94
  with gr.Blocks(fill_height=True) as demo:
 
95
  file_uploads_log = gr.State([])
96
+
97
+ # Use gr.ChatInterface directly for the main chat
98
+ # This function will be called with the user's message and the current chat history
99
+ gr.ChatInterface(
100
+ fn=self.interact_with_agent,
101
+ chatbot=gr.Chatbot(
102
+ label="Agent",
103
+ avatar_images=(
104
+ None,
105
+ "https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/Alfred.png",
106
+ ),
107
+ resizeable=True,
108
+ scale=1,
109
  ),
110
+ textbox=gr.Textbox(lines=1, label="Chat Message"),
111
+ title="Agent Chat", # You can set a title for your app
112
+ # Additional components can be added here using `gr.Row`, `gr.Column`, etc.
113
  )
 
 
 
 
114
 
115
+ # Add file upload outside ChatInterface if desired, and link it
116
+ if self.file_upload_folder is not None:
117
+ with gr.Row():
118
+ upload_file = gr.File(label="Upload a file", file_count="multiple") # Allow multiple files
119
+ upload_status = gr.Textbox(label="Upload Status", interactive=False, visible=False)
120
+ upload_file.upload(self.upload_file, [upload_file, file_uploads_log], [upload_status, file_uploads_log])
121
+ # You'll need to figure out how to pass file_uploads_log to interact_with_agent
122
+ # One way is to modify interact_with_agent to accept it, or use a global/class variable if appropriate.
123
+ # For now, I'm just showing how to add it to the UI.
124
 
125
  demo.launch(debug=True, share=True, **kwargs)
126
 
127
+ __all__ = ["stream_to_gradio", "GradioUI"]