agarwalamit081 commited on
Commit
5e8644b
·
verified ·
1 Parent(s): 3d5f7d7

Update Gradio_UI.py

Browse files

Changed metadata status from invalid "running" → valid "pending"/"done"

Files changed (1) hide show
  1. Gradio_UI.py +10 -28
Gradio_UI.py CHANGED
@@ -11,7 +11,6 @@ from smolagents.utils import _is_package_available
11
  def pull_messages_from_step(step_log: MemoryStep):
12
  """Extract ChatMessage objects from agent steps with proper nesting and error resilience"""
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 "Processing"
17
  yield gr.ChatMessage(role="assistant", content=f"**{step_number}**")
@@ -29,32 +28,30 @@ def pull_messages_from_step(step_log: MemoryStep):
29
  if hasattr(step_log, "tool_calls") and step_log.tool_calls:
30
  tool_call = step_log.tool_calls[0]
31
  parent_id = f"tool_{step_log.step_number}"
32
-
33
  args = tool_call.arguments
34
  if isinstance(args, dict):
35
  content = "\n".join(f"• {k}: {v}" for k, v in args.items() if v and k != 'self')
36
  else:
37
  content = str(args).strip()
38
-
39
  metadata: Dict = {
40
  "title": f"🛠️ Using: {tool_call.name}",
41
  "id": parent_id,
42
- "status": "running",
43
  }
44
  yield gr.ChatMessage(role="assistant", content=content, metadata=metadata)
45
 
46
- # Show observations/results (only include parent_id if defined)
47
  if hasattr(step_log, "observations") and step_log.observations:
48
  obs = step_log.observations.strip()
49
  if obs and not obs.startswith("Execution logs:"):
50
- metadata = {"title": "✅ Result"}
51
  if parent_id is not None:
52
  metadata["parent_id"] = parent_id
53
  yield gr.ChatMessage(role="assistant", content=obs, metadata=metadata)
54
 
55
- # Show errors (only include parent_id if defined)
56
  if hasattr(step_log, "error") and step_log.error:
57
- metadata = {"title": "⚠️ Warning"}
58
  if parent_id is not None:
59
  metadata["parent_id"] = parent_id
60
  yield gr.ChatMessage(role="assistant", content=str(step_log.error), metadata=metadata)
@@ -65,7 +62,6 @@ def pull_messages_from_step(step_log: MemoryStep):
65
  footer_parts.append(f"⏱️ {float(step_log.duration):.1f}s")
66
  if hasattr(step_log, "input_token_count") and hasattr(step_log, "output_token_count"):
67
  footer_parts.append(f"💬 {step_log.input_token_count + step_log.output_token_count:,} tokens")
68
-
69
  yield gr.ChatMessage(
70
  role="assistant",
71
  content=f'<span style="color: #888; font-size: 0.85em;">{" | ".join(footer_parts)}</span>',
@@ -81,42 +77,35 @@ def stream_to_gradio(
81
  """Runs agent and streams messages as gradio ChatMessages with error resilience"""
82
  if not _is_package_available("gradio"):
83
  raise ModuleNotFoundError("Install gradio: `pip install 'smolagents[gradio]'`")
84
-
85
  import gradio as gr
86
-
87
  try:
88
  for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):
89
  if isinstance(step_log, ActionStep):
90
  if hasattr(agent.model, "last_input_token_count") and hasattr(agent.model, "last_output_token_count"):
91
  step_log.input_token_count = agent.model.last_input_token_count
92
  step_log.output_token_count = agent.model.last_output_token_count
93
-
94
  for message in pull_messages_from_step(step_log):
95
  yield message
96
-
97
  final = handle_agent_output_types(step_log)
98
  if isinstance(final, AgentText):
99
  content = final.to_string()
100
- yield gr.ChatMessage(role="assistant", content=content, metadata={"react": True})
101
  else:
102
- yield gr.ChatMessage(role="assistant", content=f"**Final Answer:** {str(final)}")
103
-
104
  except Exception as e:
105
  yield gr.ChatMessage(
106
  role="assistant",
107
- content=f"⚠️ **Error during planning:** {str(e)}\n\nPlease try again with a clearer trip description (include destination, dates, origin city, and budget).",
 
108
  )
109
 
110
  class GradioUI:
111
  """Production-ready Gradio interface for travel agent"""
112
-
113
  def __init__(self, agent: MultiStepAgent, file_upload_folder: Optional[str] = None):
114
  if not _is_package_available("gradio"):
115
  raise ModuleNotFoundError("Install gradio: `pip install 'smolagents[gradio]'`")
116
-
117
  self.agent = agent
118
  self.file_upload_folder = file_upload_folder
119
-
120
  if self.file_upload_folder and not os.path.exists(file_upload_folder):
121
  os.makedirs(file_upload_folder, exist_ok=True)
122
 
@@ -124,18 +113,15 @@ class GradioUI:
124
  import gradio as gr
125
  history.append(gr.ChatMessage(role="user", content=prompt))
126
  yield history
127
-
128
  for msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):
129
  history.append(msg)
130
  yield history
131
 
132
  def launch(self, **kwargs):
133
  import gradio as gr
134
-
135
  with gr.Blocks(title="✈️ Travel Catalogue Creator", fill_height=True, theme=gr.themes.Soft()) as demo:
136
  gr.Markdown("# ✈️ Smart Travel Catalogue Creator")
137
  gr.Markdown("Plan your trip with AI: weather forecasts, custom itineraries, packing lists & visual inspiration")
138
-
139
  chatbot = gr.Chatbot(
140
  label="Your Travel Assistant",
141
  type="messages",
@@ -146,7 +132,6 @@ class GradioUI:
146
  height=600,
147
  show_copy_button=True,
148
  )
149
-
150
  with gr.Row():
151
  text_input = gr.Textbox(
152
  label="Describe your trip",
@@ -154,13 +139,11 @@ class GradioUI:
154
  lines=2,
155
  )
156
  submit_btn = gr.Button("Plan My Trip", variant="primary")
157
-
158
  gr.Markdown("""
159
  ### 💡 Tips for best results:
160
- • Include: destination, dates, origin city, budget amount + currency
161
  • Example: *"5-day Barcelona trip from NYC, Oct 15-19, budget $1500 USD"*
162
  """)
163
-
164
  submit_btn.click(
165
  self.interact_with_agent,
166
  inputs=[text_input, chatbot],
@@ -173,7 +156,6 @@ class GradioUI:
173
  outputs=[chatbot],
174
  show_progress="full",
175
  )
176
-
177
  demo.launch(**kwargs)
178
 
179
  __all__ = ["stream_to_gradio", "GradioUI"]
 
11
  def pull_messages_from_step(step_log: MemoryStep):
12
  """Extract ChatMessage objects from agent steps with proper nesting and error resilience"""
13
  import gradio as gr
 
14
  if isinstance(step_log, ActionStep):
15
  step_number = f"Step {step_log.step_number}" if step_log.step_number is not None else "Processing"
16
  yield gr.ChatMessage(role="assistant", content=f"**{step_number}**")
 
28
  if hasattr(step_log, "tool_calls") and step_log.tool_calls:
29
  tool_call = step_log.tool_calls[0]
30
  parent_id = f"tool_{step_log.step_number}"
 
31
  args = tool_call.arguments
32
  if isinstance(args, dict):
33
  content = "\n".join(f"• {k}: {v}" for k, v in args.items() if v and k != 'self')
34
  else:
35
  content = str(args).strip()
 
36
  metadata: Dict = {
37
  "title": f"🛠️ Using: {tool_call.name}",
38
  "id": parent_id,
39
+ "status": "pending", # FIXED: "running" → "pending" (Gradio validation)
40
  }
41
  yield gr.ChatMessage(role="assistant", content=content, metadata=metadata)
42
 
43
+ # Show observations/results
44
  if hasattr(step_log, "observations") and step_log.observations:
45
  obs = step_log.observations.strip()
46
  if obs and not obs.startswith("Execution logs:"):
47
+ metadata = {"title": "✅ Result", "status": "done"} # FIXED: added status
48
  if parent_id is not None:
49
  metadata["parent_id"] = parent_id
50
  yield gr.ChatMessage(role="assistant", content=obs, metadata=metadata)
51
 
52
+ # Show errors
53
  if hasattr(step_log, "error") and step_log.error:
54
+ metadata = {"title": "⚠️ Warning", "status": "done"} # FIXED: added status
55
  if parent_id is not None:
56
  metadata["parent_id"] = parent_id
57
  yield gr.ChatMessage(role="assistant", content=str(step_log.error), metadata=metadata)
 
62
  footer_parts.append(f"⏱️ {float(step_log.duration):.1f}s")
63
  if hasattr(step_log, "input_token_count") and hasattr(step_log, "output_token_count"):
64
  footer_parts.append(f"💬 {step_log.input_token_count + step_log.output_token_count:,} tokens")
 
65
  yield gr.ChatMessage(
66
  role="assistant",
67
  content=f'<span style="color: #888; font-size: 0.85em;">{" | ".join(footer_parts)}</span>',
 
77
  """Runs agent and streams messages as gradio ChatMessages with error resilience"""
78
  if not _is_package_available("gradio"):
79
  raise ModuleNotFoundError("Install gradio: `pip install 'smolagents[gradio]'`")
 
80
  import gradio as gr
 
81
  try:
82
  for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):
83
  if isinstance(step_log, ActionStep):
84
  if hasattr(agent.model, "last_input_token_count") and hasattr(agent.model, "last_output_token_count"):
85
  step_log.input_token_count = agent.model.last_input_token_count
86
  step_log.output_token_count = agent.model.last_output_token_count
 
87
  for message in pull_messages_from_step(step_log):
88
  yield message
 
89
  final = handle_agent_output_types(step_log)
90
  if isinstance(final, AgentText):
91
  content = final.to_string()
92
+ yield gr.ChatMessage(role="assistant", content=content, metadata={"react": True, "status": "done"})
93
  else:
94
+ yield gr.ChatMessage(role="assistant", content=f"**Final Answer:** {str(final)}", metadata={"status": "done"})
 
95
  except Exception as e:
96
  yield gr.ChatMessage(
97
  role="assistant",
98
+ content=f"⚠️ **Error during planning:** {str(e)}\nPlease try again with a clearer trip description (include destination, dates, origin city, and budget).",
99
+ metadata={"status": "done"}
100
  )
101
 
102
  class GradioUI:
103
  """Production-ready Gradio interface for travel agent"""
 
104
  def __init__(self, agent: MultiStepAgent, file_upload_folder: Optional[str] = None):
105
  if not _is_package_available("gradio"):
106
  raise ModuleNotFoundError("Install gradio: `pip install 'smolagents[gradio]'`")
 
107
  self.agent = agent
108
  self.file_upload_folder = file_upload_folder
 
109
  if self.file_upload_folder and not os.path.exists(file_upload_folder):
110
  os.makedirs(file_upload_folder, exist_ok=True)
111
 
 
113
  import gradio as gr
114
  history.append(gr.ChatMessage(role="user", content=prompt))
115
  yield history
 
116
  for msg in stream_to_gradio(self.agent, task=prompt, reset_agent_memory=False):
117
  history.append(msg)
118
  yield history
119
 
120
  def launch(self, **kwargs):
121
  import gradio as gr
 
122
  with gr.Blocks(title="✈️ Travel Catalogue Creator", fill_height=True, theme=gr.themes.Soft()) as demo:
123
  gr.Markdown("# ✈️ Smart Travel Catalogue Creator")
124
  gr.Markdown("Plan your trip with AI: weather forecasts, custom itineraries, packing lists & visual inspiration")
 
125
  chatbot = gr.Chatbot(
126
  label="Your Travel Assistant",
127
  type="messages",
 
132
  height=600,
133
  show_copy_button=True,
134
  )
 
135
  with gr.Row():
136
  text_input = gr.Textbox(
137
  label="Describe your trip",
 
139
  lines=2,
140
  )
141
  submit_btn = gr.Button("Plan My Trip", variant="primary")
 
142
  gr.Markdown("""
143
  ### 💡 Tips for best results:
144
+ • Include: destination, dates, origin city, budget amount + currency
145
  • Example: *"5-day Barcelona trip from NYC, Oct 15-19, budget $1500 USD"*
146
  """)
 
147
  submit_btn.click(
148
  self.interact_with_agent,
149
  inputs=[text_input, chatbot],
 
156
  outputs=[chatbot],
157
  show_progress="full",
158
  )
 
159
  demo.launch(**kwargs)
160
 
161
  __all__ = ["stream_to_gradio", "GradioUI"]