laverdes commited on
Commit
c882c35
·
verified ·
1 Parent(s): 8507438

feat: gradio ui chat integration with LangGraph `invoke`

Browse files
Files changed (1) hide show
  1. gradio_ui_langgraph.py +336 -0
gradio_ui_langgraph.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # 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 at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # 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 and
15
+ # limitations under the License.
16
+ import os
17
+ import re
18
+ import shutil
19
+ from typing import Optional
20
+
21
+ from smolagents.agent_types import AgentAudio, AgentImage, AgentText, handle_agent_output_types
22
+ from smolagents.agents import ActionStep, MultiStepAgent
23
+ from smolagents.memory import MemoryStep
24
+ from smolagents.utils import _is_package_available
25
+
26
+
27
+ def pull_messages_from_step(
28
+ step_log: MemoryStep,
29
+ ):
30
+ """Extract ChatMessage objects from agent steps with proper nesting"""
31
+ import gradio as gr
32
+
33
+ if isinstance(step_log, ActionStep):
34
+ # Output the step number
35
+ 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 LLM
39
+ if hasattr(step_log, "model_output") and step_log.model_output is not None:
40
+ # Clean up the LLM output
41
+ model_output = step_log.model_output.strip()
42
+ # Remove any trailing <end_code> and extra backticks, handling multiple possible formats
43
+ 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 message
50
+ 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 info
56
+ # First we will handle arguments based on type
57
+ args = first_tool_call.arguments
58
+ 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 tags
65
+ content = re.sub(r"```.*?\n", "", content) # Remove existing code blocks
66
+ content = re.sub(r"\s*<end_code>\s*", "", content) # Remove end_code tags
67
+ 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_tool
81
+
82
+ # Nesting execution logs under the tool call if they exist
83
+ 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 content
86
+ 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"```bash\n{log_content}\n",
92
+ metadata={"title": "📝 Execution Logs", "parent_id": parent_id, "status": "done"},
93
+ )
94
+
95
+ # Nesting any errors under the tool call
96
+ 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 message
104
+ parent_message_tool.metadata["status"] = "done"
105
+
106
+ # Handle standalone errors but not from tool calls
107
+ 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 information
111
+ 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_str
117
+ if hasattr(step_log, "duration"):
118
+ step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else None
119
+ step_footnote += step_duration
120
+ 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="-----", metadata={"status": "done"})
123
+
124
+
125
+ def 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 gr
137
+
138
+ # todo: change run for invoke and create AgentText out of final answer
139
+
140
+ response = agent.invoke({"messages": task})
141
+
142
+ # Show the messages
143
+ for m in response['messages']:
144
+ m.pretty_print()
145
+
146
+ final_answer = response['messages'][-1].content
147
+ final_answer = handle_agent_output_types(final_answer)
148
+
149
+ if isinstance(final_answer, AgentText):
150
+ yield gr.ChatMessage(
151
+ role="assistant",
152
+ content=f"**Final answer:**\n{final_answer.to_string()}\n",
153
+ )
154
+ elif isinstance(final_answer, AgentImage):
155
+ yield gr.ChatMessage(
156
+ role="assistant",
157
+ content={"path": final_answer.to_string(), "mime_type": "image/png"},
158
+ )
159
+ elif isinstance(final_answer, AgentAudio):
160
+ yield gr.ChatMessage(
161
+ role="assistant",
162
+ content={"path": final_answer.to_string(), "mime_type": "audio/wav"},
163
+ )
164
+ else:
165
+ yield gr.ChatMessage(role="assistant", content=f"**Final answer:** {str(final_answer)}")
166
+
167
+
168
+ class GradioUI:
169
+ """A one-line interface to launch your agent in Gradio"""
170
+
171
+ def __init__(self, agent: MultiStepAgent, file_upload_folder: str | None = None):
172
+ if not _is_package_available("gradio"):
173
+ raise ModuleNotFoundError(
174
+ "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
175
+ )
176
+ self.agent = agent
177
+ self.file_upload_folder = file_upload_folder
178
+ self.name = getattr(agent, "name") or "Agent interface"
179
+ self.description = getattr(agent, "description", None)
180
+ if self.file_upload_folder is not None:
181
+ if not os.path.exists(file_upload_folder):
182
+ os.mkdir(file_upload_folder)
183
+
184
+ def interact_with_agent(self, prompt, messages, session_state):
185
+ import gradio as gr
186
+
187
+ # Get the agent type from the template agent
188
+ if "agent" not in session_state:
189
+ session_state["agent"] = self.agent
190
+
191
+ try:
192
+ messages.append(gr.ChatMessage(role="user", content=prompt))
193
+ yield messages
194
+
195
+ for msg in stream_to_gradio(session_state["agent"], task=prompt, reset_agent_memory=False):
196
+ messages.append(msg)
197
+ yield messages
198
+
199
+ yield messages
200
+ except Exception as e:
201
+ print(f"Error in interaction: {str(e)}")
202
+ messages.append(gr.ChatMessage(role="assistant", content=f"Error: {str(e)}"))
203
+ yield messages
204
+
205
+ def upload_file(self, file, file_uploads_log, allowed_file_types=None):
206
+ """
207
+ Handle file uploads, default allowed types are .pdf, .docx, and .txt
208
+ """
209
+ import gradio as gr
210
+
211
+ if file is None:
212
+ return gr.Textbox(value="No file uploaded", visible=True), file_uploads_log
213
+
214
+ if allowed_file_types is None:
215
+ allowed_file_types = [".pdf", ".docx", ".txt"]
216
+
217
+ file_ext = os.path.splitext(file.name)[1].lower()
218
+ if file_ext not in allowed_file_types:
219
+ return gr.Textbox("File type disallowed", visible=True), file_uploads_log
220
+
221
+ # Sanitize file name
222
+ original_name = os.path.basename(file.name)
223
+ sanitized_name = re.sub(
224
+ r"[^\w\-.]", "_", original_name
225
+ ) # Replace any non-alphanumeric, non-dash, or non-dot characters with underscores
226
+
227
+ # Save the uploaded file to the specified folder
228
+ file_path = os.path.join(self.file_upload_folder, os.path.basename(sanitized_name))
229
+ shutil.copy(file.name, file_path)
230
+
231
+ return gr.Textbox(f"File uploaded: {file_path}", visible=True), file_uploads_log + [file_path]
232
+
233
+ def log_user_message(self, text_input, file_uploads_log):
234
+ import gradio as gr
235
+
236
+ return (
237
+ text_input
238
+ + (
239
+ f"\nYou have been provided with these files, which might be helpful or not: {file_uploads_log}"
240
+ if len(file_uploads_log) > 0
241
+ else ""
242
+ ),
243
+ "",
244
+ gr.Button(interactive=False),
245
+ )
246
+
247
+ def launch(self, share: bool = True, **kwargs):
248
+ import gradio as gr
249
+
250
+ with gr.Blocks(theme="ocean", fill_height=True) as demo:
251
+ # Add session state to store session-specific data
252
+ session_state = gr.State({})
253
+ stored_messages = gr.State([])
254
+ file_uploads_log = gr.State([])
255
+
256
+ with gr.Sidebar():
257
+ gr.Markdown(
258
+ f"# {self.name.replace('_', ' ').capitalize()}"
259
+ "\n> This web ui allows you to interact with a `smolagents` agent that can use tools and execute steps to complete tasks."
260
+ + (f"\n\n**Agent description:**\n{self.description}" if self.description else "")
261
+ )
262
+
263
+ with gr.Group():
264
+ gr.Markdown("**Your request**", container=True)
265
+ text_input = gr.Textbox(
266
+ lines=3,
267
+ label="Chat Message",
268
+ container=False,
269
+ placeholder="Enter your prompt here and press Shift+Enter or press the button",
270
+ )
271
+ submit_btn = gr.Button("Submit", variant="primary")
272
+
273
+ # If an upload folder is provided, enable the upload feature
274
+ if self.file_upload_folder is not None:
275
+ upload_file = gr.File(label="Upload a file")
276
+ upload_status = gr.Textbox(label="Upload Status", interactive=False, visible=False)
277
+ upload_file.change(
278
+ self.upload_file,
279
+ [upload_file, file_uploads_log],
280
+ [upload_status, file_uploads_log],
281
+ )
282
+
283
+ gr.HTML("<br><br><h4><center>Powered by:</center></h4>")
284
+ with gr.Row():
285
+ gr.HTML("""<div style="display: flex; align-items: center; gap: 8px; font-family: system-ui, -apple-system, sans-serif;">
286
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/smolagents/mascot_smol.png" style="width: 32px; height: 32px; object-fit: contain;" alt="logo">
287
+ <a target="_blank" href="https://github.com/huggingface/smolagents"><b>huggingface/smolagents</b></a>
288
+ </div>""")
289
+
290
+ # Main chat interface
291
+ chatbot = gr.Chatbot(
292
+ label="Agent",
293
+ type="messages",
294
+ avatar_images=(
295
+ None,
296
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/smolagents/mascot_smol.png",
297
+ ),
298
+ resizeable=True,
299
+ scale=1,
300
+ )
301
+
302
+ # Set up event handlers
303
+ text_input.submit(
304
+ self.log_user_message,
305
+ [text_input, file_uploads_log],
306
+ [stored_messages, text_input, submit_btn],
307
+ ).then(self.interact_with_agent, [stored_messages, chatbot, session_state], [chatbot]).then(
308
+ lambda: (
309
+ gr.Textbox(
310
+ interactive=True, placeholder="Enter your prompt here and press Shift+Enter or the button"
311
+ ),
312
+ gr.Button(interactive=True),
313
+ ),
314
+ None,
315
+ [text_input, submit_btn],
316
+ )
317
+
318
+ submit_btn.click(
319
+ self.log_user_message,
320
+ [text_input, file_uploads_log],
321
+ [stored_messages, text_input, submit_btn],
322
+ ).then(self.interact_with_agent, [stored_messages, chatbot, session_state], [chatbot]).then(
323
+ lambda: (
324
+ gr.Textbox(
325
+ interactive=True, placeholder="Enter your prompt here and press Shift+Enter or the button"
326
+ ),
327
+ gr.Button(interactive=True),
328
+ ),
329
+ None,
330
+ [text_input, submit_btn],
331
+ )
332
+
333
+ demo.launch(debug=True, share=share, **kwargs)
334
+
335
+
336
+ __all__ = ["stream_to_gradio", "GradioUI"]