dawoodkhan82 commited on
Commit
3dd44e9
·
1 Parent(s): a215d4c
__pycache__/gradio_ui.cpython-313.pyc ADDED
Binary file (20.9 kB). View file
 
chatbot.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from smolagents import VisitWebpageTool, InferenceClientModel, CodeAgent, ToolCallingAgent, WebSearchTool
2
+ from gradio_ui import GradioUI
3
+
4
+ model = InferenceClientModel()
5
+ agent = CodeAgent(tools=[VisitWebpageTool(), WebSearchTool()], model=model, additional_authorized_imports=["xml.etree.ElementTree"])
6
+ agent.prompt_templates["system_prompt"] = agent.prompt_templates["system_prompt"] + "\nTake the final result and format it as a sms text message to a customer. You are a helpful customer support assistant. Keep your answers to a 30 word limit. You are a sms text box so keep it informal. Dont show your thinking in the final message. When the user mentions a time that works for them for a scheduled appointment, reply with `Great! We can schedule your visit for that time. Please call https://www.ohiocars.com at +1 513-712-8086 to confirm your appointment. Looking forward to seeing you then!'"
7
+ GradioUI(agent).launch()
gradio_ui.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import shutil
4
+ from pathlib import Path
5
+
6
+ from smolagents.agent_types import AgentAudio, AgentImage, AgentText
7
+ from smolagents.agents import MultiStepAgent, PlanningStep
8
+ from smolagents.memory import ActionStep, FinalAnswerStep, MemoryStep
9
+ from smolagents.models import ChatMessageStreamDelta
10
+ from smolagents.utils import _is_package_available
11
+ import xml.etree.ElementTree as ET
12
+
13
+
14
+ def get_step_footnote_content(step_log: MemoryStep, step_name: str) -> str:
15
+ """Get a footnote string for a step log with duration and token information"""
16
+ step_footnote = f"**{step_name}**"
17
+ if hasattr(step_log, "input_token_count") and hasattr(step_log, "output_token_count"):
18
+ token_str = f" | Input tokens:{step_log.input_token_count:,} | Output tokens: {step_log.output_token_count:,}"
19
+ step_footnote += token_str
20
+ if hasattr(step_log, "duration"):
21
+ step_duration = f" | Duration: {round(float(step_log.duration), 2)}" if step_log.duration else None
22
+ step_footnote += step_duration
23
+ step_footnote_content = f"""<span style="color: #bbbbc2; font-size: 12px;">{step_footnote}</span> """
24
+ return step_footnote_content
25
+
26
+
27
+ def pull_messages_from_step(step_log: MemoryStep, skip_model_outputs: bool = False):
28
+ """Extract ChatMessage objects from agent steps with proper nesting.
29
+
30
+ Args:
31
+ step_log: The step log to display as gr.ChatMessage objects.
32
+ skip_model_outputs: If True, skip the model outputs when creating the gr.ChatMessage objects:
33
+ This is used for instance when streaming model outputs have already been displayed.
34
+ """
35
+ if not _is_package_available("gradio"):
36
+ raise ModuleNotFoundError(
37
+ "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
38
+ )
39
+ import gradio as gr
40
+
41
+ if isinstance(step_log, ActionStep):
42
+ # Output the step number
43
+ step_number = f"Step {step_log.step_number}" if step_log.step_number is not None else "Step"
44
+
45
+ # First yield the thought/reasoning from the LLM
46
+ if not skip_model_outputs:
47
+ yield gr.ChatMessage(role="assistant", content=f"**{step_number}**", metadata={"status": "done"})
48
+ elif skip_model_outputs and hasattr(step_log, "model_output") and step_log.model_output is not None:
49
+ model_output = step_log.model_output.strip()
50
+ # Remove any trailing <end_code> and extra backticks, handling multiple possible formats
51
+ model_output = re.sub(r"```\s*<end_code>", "```", model_output) # handles ```<end_code>
52
+ model_output = re.sub(r"<end_code>\s*```", "```", model_output) # handles <end_code>```
53
+ model_output = re.sub(r"```\s*\n\s*<end_code>", "```", model_output) # handles ```\n<end_code>
54
+ model_output = model_output.strip()
55
+ yield gr.ChatMessage(role="assistant", content=model_output, metadata={"status": "done"})
56
+
57
+ # For tool calls, create a parent message
58
+ if hasattr(step_log, "tool_calls") and step_log.tool_calls is not None:
59
+ first_tool_call = step_log.tool_calls[0]
60
+ used_code = first_tool_call.name == "python_interpreter"
61
+
62
+ # Tool call becomes the parent message with timing info
63
+ # First we will handle arguments based on type
64
+ args = first_tool_call.arguments
65
+ if isinstance(args, dict):
66
+ content = str(args.get("answer", str(args)))
67
+ else:
68
+ content = str(args).strip()
69
+
70
+ if used_code:
71
+ # Clean up the content by removing any end code tags
72
+ content = re.sub(r"```.*?\n", "", content) # Remove existing code blocks
73
+ content = re.sub(r"\s*<end_code>\s*", "", content) # Remove end_code tags
74
+ content = content.strip()
75
+ if not content.startswith("```python"):
76
+ content = f"```python\n{content}\n```"
77
+
78
+ parent_message_tool = gr.ChatMessage(
79
+ role="assistant",
80
+ content=content,
81
+ metadata={
82
+ "title": f"🛠️ Used tool {first_tool_call.name}",
83
+ "status": "done",
84
+ },
85
+ )
86
+ yield parent_message_tool
87
+
88
+ # Display execution logs if they exist
89
+ if hasattr(step_log, "observations") and (
90
+ step_log.observations is not None and step_log.observations.strip()
91
+ ): # Only yield execution logs if there's actual content
92
+ log_content = step_log.observations.strip()
93
+ if log_content:
94
+ log_content = re.sub(r"^Execution logs:\s*", "", log_content)
95
+ yield gr.ChatMessage(
96
+ role="assistant",
97
+ content=f"```bash\n{log_content}\n",
98
+ metadata={"title": "📝 Execution Logs", "status": "done"},
99
+ )
100
+
101
+ # Display any errors
102
+ if hasattr(step_log, "error") and step_log.error is not None:
103
+ yield gr.ChatMessage(
104
+ role="assistant",
105
+ content=str(step_log.error),
106
+ metadata={"title": "💥 Error", "status": "done"},
107
+ )
108
+
109
+ # Update parent message metadata to done status without yielding a new message
110
+ if getattr(step_log, "observations_images", []):
111
+ for image in step_log.observations_images:
112
+ path_image = AgentImage(image).to_string()
113
+ yield gr.ChatMessage(
114
+ role="assistant",
115
+ content={"path": path_image, "mime_type": f"image/{path_image.split('.')[-1]}"},
116
+ metadata={"title": "🖼️ Output Image", "status": "done"},
117
+ )
118
+
119
+ # Handle standalone errors but not from tool calls
120
+ if hasattr(step_log, "error") and step_log.error is not None:
121
+ yield gr.ChatMessage(
122
+ role="assistant", content=str(step_log.error), metadata={"title": "💥 Error", "status": "done"}
123
+ )
124
+
125
+ yield gr.ChatMessage(
126
+ role="assistant", content=get_step_footnote_content(step_log, step_number), metadata={"status": "done"}
127
+ )
128
+ yield gr.ChatMessage(role="assistant", content="-----", metadata={"status": "done"})
129
+
130
+ elif isinstance(step_log, PlanningStep):
131
+ yield gr.ChatMessage(role="assistant", content="**Planning step**", metadata={"status": "done"})
132
+ yield gr.ChatMessage(role="assistant", content=step_log.plan, metadata={"status": "done"})
133
+ yield gr.ChatMessage(
134
+ role="assistant", content=get_step_footnote_content(step_log, "Planning step"), metadata={"status": "done"}
135
+ )
136
+ yield gr.ChatMessage(role="assistant", content="-----", metadata={"status": "done"})
137
+
138
+ elif isinstance(step_log, FinalAnswerStep):
139
+ final_answer = step_log.final_answer
140
+ if isinstance(final_answer, AgentText):
141
+ yield gr.ChatMessage(
142
+ role="assistant",
143
+ content=f"**Final answer:**\n{final_answer.to_string()}\n",
144
+ metadata={"status": "done"},
145
+ )
146
+ elif isinstance(final_answer, AgentImage):
147
+ yield gr.ChatMessage(
148
+ role="assistant",
149
+ content={"path": final_answer.to_string(), "mime_type": "image/png"},
150
+ metadata={"status": "done"},
151
+ )
152
+ elif isinstance(final_answer, AgentAudio):
153
+ yield gr.ChatMessage(
154
+ role="assistant",
155
+ content={"path": final_answer.to_string(), "mime_type": "audio/wav"},
156
+ metadata={"status": "done"},
157
+ )
158
+ else:
159
+ yield gr.ChatMessage(
160
+ role="assistant", content=f"**Final answer:** {str(final_answer)}", metadata={"status": "done"}
161
+ )
162
+
163
+ else:
164
+ raise ValueError(f"Unsupported step type: {type(step_log)}")
165
+
166
+
167
+ def stream_to_gradio(
168
+ agent,
169
+ task: str,
170
+ task_images: list | None = None,
171
+ reset_agent_memory: bool = False,
172
+ additional_args: dict | None = None,
173
+ ):
174
+ """Runs an agent with the given task and streams the messages from the agent as gradio ChatMessages."""
175
+ total_input_tokens = 0
176
+ total_output_tokens = 0
177
+
178
+ if not _is_package_available("gradio"):
179
+ raise ModuleNotFoundError(
180
+ "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
181
+ )
182
+
183
+ intermediate_text = ""
184
+
185
+ for step_log in agent.run(
186
+ task, images=task_images, stream=True, reset=reset_agent_memory, additional_args=additional_args
187
+ ):
188
+ # Track tokens if model provides them
189
+ if getattr(agent.model, "last_input_token_count", None) is not None:
190
+ total_input_tokens += agent.model.last_input_token_count
191
+ total_output_tokens += agent.model.last_output_token_count
192
+ if isinstance(step_log, (ActionStep, PlanningStep)):
193
+ step_log.input_token_count = agent.model.last_input_token_count
194
+ step_log.output_token_count = agent.model.last_output_token_count
195
+
196
+ if isinstance(step_log, MemoryStep):
197
+ intermediate_text = ""
198
+ for message in pull_messages_from_step(
199
+ step_log,
200
+ # If we're streaming model outputs, no need to display them twice
201
+ skip_model_outputs=getattr(agent, "stream_outputs", False),
202
+ ):
203
+ yield message
204
+ elif isinstance(step_log, ChatMessageStreamDelta):
205
+ intermediate_text += step_log.content or ""
206
+ yield intermediate_text
207
+
208
+ def extract_vehicle_info_as_string(adf_xml):
209
+ root = ET.fromstring(adf_xml)
210
+
211
+ # Find the vehicle element
212
+ vehicle = root.find('.//vehicle')
213
+
214
+ if vehicle is not None:
215
+ year = vehicle.find('year').text if vehicle.find('year') is not None else ""
216
+ make = vehicle.find('make').text if vehicle.find('make') is not None else ""
217
+ model = vehicle.find('model').text if vehicle.find('model') is not None else ""
218
+ vehicle_info = f"{year} {make} {model}".strip()
219
+
220
+ # Extract first name
221
+ first_name = ""
222
+ name_element = root.find('.//name[@part="first"]')
223
+ if name_element is not None:
224
+ first_name = name_element.text.strip() if name_element.text else ""
225
+ return first_name, vehicle_info
226
+
227
+
228
+ class GradioUI:
229
+ """A one-line interface to launch your agent in Gradio"""
230
+
231
+ def __init__(self, agent: MultiStepAgent, file_upload_folder: str | None = None):
232
+ if not _is_package_available("gradio"):
233
+ raise ModuleNotFoundError(
234
+ "Please install 'gradio' extra to use the GradioUI: `pip install 'smolagents[gradio]'`"
235
+ )
236
+ self.agent = agent
237
+ self.file_upload_folder = Path(file_upload_folder) if file_upload_folder is not None else None
238
+ self.name = getattr(agent, "name") or "OTTO: The Car Sales Agent"
239
+ self.description = getattr(agent, "description", None)
240
+ if self.file_upload_folder is not None:
241
+ if not self.file_upload_folder.exists():
242
+ self.file_upload_folder.mkdir(parents=True, exist_ok=True)
243
+
244
+ def interact_with_agent(self, prompt, messages, session_state, car_site, adf_lead):
245
+ import gradio as gr
246
+ self.agent.prompt_templates["system_prompt"] += f"\n\nWhen answering a customer's question about the dealership or other cars, use the following site to find the information:\n\nDealership Site: {car_site}\n\nWhen answering a customer's question about the specific car use the following ADF Lead:\n\nADF Lead: {adf_lead}"
247
+ # Get the agent type from the template agent
248
+ if "agent" not in session_state:
249
+ session_state["agent"] = self.agent
250
+
251
+ try:
252
+ messages.append(gr.ChatMessage(role="user", content=prompt, metadata={"status": "done"}))
253
+ yield messages
254
+
255
+ for msg in stream_to_gradio(session_state["agent"], task=prompt, reset_agent_memory=False):
256
+ if isinstance(msg, gr.ChatMessage):
257
+ messages.append(msg)
258
+ elif isinstance(msg, str): # Then it's only a completion delta
259
+ try:
260
+ if messages[-1].metadata["status"] == "pending":
261
+ messages[-1].content = msg
262
+ else:
263
+ messages.append(
264
+ gr.ChatMessage(role="assistant", content=msg, metadata={"status": "pending"})
265
+ )
266
+ except Exception as e:
267
+ raise e
268
+ yield messages
269
+
270
+ yield messages
271
+ except Exception as e:
272
+ print(f"Error in interaction: {str(e)}")
273
+ messages.append(gr.ChatMessage(role="assistant", content=f"Error: {str(e)}"))
274
+ yield messages
275
+
276
+ def upload_file(self, file, file_uploads_log, allowed_file_types=None):
277
+ """
278
+ Handle file uploads, default allowed types are .pdf, .docx, and .txt
279
+ """
280
+ import gradio as gr
281
+
282
+ if file is None:
283
+ return gr.Textbox(value="No file uploaded", visible=True), file_uploads_log
284
+
285
+ if allowed_file_types is None:
286
+ allowed_file_types = [".pdf", ".docx", ".txt"]
287
+
288
+ file_ext = os.path.splitext(file.name)[1].lower()
289
+ if file_ext not in allowed_file_types:
290
+ return gr.Textbox("File type disallowed", visible=True), file_uploads_log
291
+
292
+ # Sanitize file name
293
+ original_name = os.path.basename(file.name)
294
+ sanitized_name = re.sub(
295
+ r"[^\w\-.]", "_", original_name
296
+ ) # Replace any non-alphanumeric, non-dash, or non-dot characters with underscores
297
+
298
+ # Save the uploaded file to the specified folder
299
+ file_path = os.path.join(self.file_upload_folder, os.path.basename(sanitized_name))
300
+ shutil.copy(file.name, file_path)
301
+
302
+ return gr.Textbox(f"File uploaded: {file_path}", visible=True), file_uploads_log + [file_path]
303
+
304
+ def log_user_message(self, text_input, file_uploads_log):
305
+ import gradio as gr
306
+
307
+ return (
308
+ text_input
309
+ + (
310
+ f"\nYou have been provided with these files, which might be helpful or not: {file_uploads_log}"
311
+ if len(file_uploads_log) > 0
312
+ else ""
313
+ ),
314
+ "",
315
+ gr.Button(interactive=False),
316
+ )
317
+
318
+ def launch(self, share: bool = True, **kwargs):
319
+ self.create_app().launch(debug=True, share=share, **kwargs)
320
+
321
+ def create_app(self):
322
+ import gradio as gr
323
+
324
+ with gr.Blocks(theme="ocean", fill_height=True) as demo:
325
+ # Add session state to store session-specific data
326
+ session_state = gr.State({})
327
+ stored_messages = gr.State([])
328
+ file_uploads_log = gr.State([])
329
+
330
+ with gr.Sidebar():
331
+ gr.Markdown(
332
+ f"# {self.name.replace('_', ' ')}"
333
+ "\n> Test the OTTO Agent by asking it questions."
334
+ + (f"\n\n**Agent description:**\n{self.description}" if self.description else "")
335
+ )
336
+
337
+ with gr.Group():
338
+ gr.Markdown("**Your request**", container=True)
339
+ text_input = gr.Textbox(
340
+ lines=3,
341
+ label="Chat Message",
342
+ container=False,
343
+ placeholder="Enter your prompt here and press Shift+Enter or press the button",
344
+ )
345
+ submit_btn = gr.Button("Submit", variant="primary")
346
+ with gr.Accordion("Dealership Info", open=False):
347
+ car_site = gr.Textbox(label="Car Gurus Dealership Site", lines=2, value="https://www.cargurus.com/Cars/m-Ohio-Cars-sp458596", interactive=True)
348
+ adf_lead = gr.Textbox(label="ADF Lead", lines=4, value="<?xml version=\"1.0\"?><?ADF version=\"1.0\"?><adf><prospect><requestdate>2025-05-12T13:59:30</requestdate><vehicle status=\"used\"><id source=\"CarsForSale.com\">16f3114e-825f-4eb0-8165-ce43fe5143b6</id><year>2016</year><make>Toyota</make><model>Corolla</model><vin>5YFBURHE4GP511115</vin><stock></stock><comments>DP</comments><colorcombination><exteriorcolor>Super White</exteriorcolor></colorcombination><miles>131024.0</miles><price type=\"asking\">9950</price></vehicle><customer><contact><name part=\"first\">Test</name><name part=\"last\">Lead</name><name part=\"full\">Test Lead</name><email>123@gmail.com</email><phone>2582584568</phone><address><city></city><state></state><postalcode></postalcode></address></contact><comments><![CDATA[I'm interested and want to know more about the 2016 Toyota Corolla S Plus you have listed for $9,950 on Cars For Sale.]]></comments><timeframe><description></description></timeframe></customer><provider><id>19971</id><name part=\"full\">Carsforsale.com</name><service>Carsforsale.com</service><phone>866-388-9778</phone></provider><vendor><id>114483</id><vendorname>Ohio Cars</vendorname></vendor></prospect></adf>", interactive=False)
349
+ # If an upload folder is provided, enable the upload feature
350
+ if self.file_upload_folder is not None:
351
+ upload_file = gr.File(label="Upload a file")
352
+ upload_status = gr.Textbox(label="Upload Status", interactive=False, visible=False)
353
+ upload_file.change(
354
+ self.upload_file,
355
+ [upload_file, file_uploads_log],
356
+ [upload_status, file_uploads_log],
357
+ )
358
+
359
+ first_name, vehicle_info = extract_vehicle_info_as_string(adf_lead.value)
360
+ message = gr.ChatMessage(role="assistant", content=f"Hi {first_name}! The {vehicle_info} you're interested in is available at [OhioCars.com](https://www.ohiocars.com). Would you like to schedule a visit to check it out? We have appointment slots at 11 AM, 1 PM, or 3 PM. Which time works best for you?", metadata={"status": "done"})
361
+ # Main chat interface
362
+ chatbot = gr.Chatbot(
363
+ label="Agent",
364
+ type="messages",
365
+ value=[message],
366
+ avatar_images=(
367
+ None,
368
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/smolagents/mascot_smol.png",
369
+ ),
370
+ resizeable=True,
371
+ scale=1,
372
+ )
373
+
374
+ # Set up event handlers
375
+ text_input.submit(
376
+ self.log_user_message,
377
+ [text_input, file_uploads_log],
378
+ [stored_messages, text_input, submit_btn],
379
+ ).then(self.interact_with_agent, [stored_messages, chatbot, session_state, car_site, adf_lead], [chatbot]).then(
380
+ lambda: (
381
+ gr.Textbox(
382
+ interactive=True, placeholder="Enter your prompt here and press Shift+Enter or the button"
383
+ ),
384
+ gr.Button(interactive=True),
385
+ ),
386
+ None,
387
+ [text_input, submit_btn],
388
+ )
389
+
390
+ submit_btn.click(
391
+ self.log_user_message,
392
+ [text_input, file_uploads_log],
393
+ [stored_messages, text_input, submit_btn],
394
+ ).then(self.interact_with_agent, [stored_messages, chatbot, session_state, car_site, adf_lead], [chatbot]).then(
395
+ lambda: (
396
+ gr.Textbox(
397
+ interactive=True, placeholder="Enter your prompt here and press Shift+Enter or the button"
398
+ ),
399
+ gr.Button(interactive=True),
400
+ ),
401
+ None,
402
+ [text_input, submit_btn],
403
+ )
404
+
405
+ return demo
406
+
407
+
408
+ __all__ = ["stream_to_gradio", "GradioUI"]
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ smolagents
2
+ gradio
3
+ xml