agarwalamit081 commited on
Commit
5165223
·
verified ·
1 Parent(s): feb1107

Update Gradio_UI.py

Browse files

Fixed UnboundLocalError

Files changed (1) hide show
  1. Gradio_UI.py +39 -24
Gradio_UI.py CHANGED
@@ -9,7 +9,7 @@ from smolagents.memory import MemoryStep
9
  from smolagents.utils import _is_package_available
10
 
11
  def pull_messages_from_step(step_log: MemoryStep):
12
- """Extract ChatMessage objects from agent steps with proper nesting"""
13
  import gradio as gr
14
 
15
  if isinstance(step_log, ActionStep):
@@ -21,8 +21,14 @@ def pull_messages_from_step(step_log: MemoryStep):
21
  model_output = re.sub(r"```\s*<end_code>.*", "```", step_log.model_output.strip())
22
  model_output = re.sub(r"<end_code>\s*```", "```", model_output)
23
  if model_output.strip():
 
 
 
24
  yield gr.ChatMessage(role="assistant", content=model_output)
25
 
 
 
 
26
  # Handle tool calls
27
  if hasattr(step_log, "tool_calls") and step_log.tool_calls:
28
  tool_call = step_log.tool_calls[0]
@@ -52,15 +58,15 @@ def pull_messages_from_step(step_log: MemoryStep):
52
  yield gr.ChatMessage(
53
  role="assistant",
54
  content=obs,
55
- metadata={"title": "✅ Result", "parent_id": parent_id if hasattr(step_log, 'tool_calls') else None},
56
  )
57
 
58
- # Show errors if any
59
  if hasattr(step_log, "error") and step_log.error:
60
  yield gr.ChatMessage(
61
  role="assistant",
62
  content=str(step_log.error),
63
- metadata={"title": "⚠️ Warning", "parent_id": parent_id if hasattr(step_log, 'tool_calls') else None},
64
  )
65
 
66
  # Step footer with metrics
@@ -82,33 +88,42 @@ def stream_to_gradio(
82
  reset_agent_memory: bool = False,
83
  additional_args: Optional[dict] = None,
84
  ):
85
- """Runs agent and streams messages as gradio ChatMessages"""
86
  if not _is_package_available("gradio"):
87
  raise ModuleNotFoundError("Install gradio: `pip install 'smolagents[gradio]'`")
88
 
89
  import gradio as gr
90
 
91
- for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):
92
- if isinstance(step_log, ActionStep):
93
- # Track tokens if available
94
- if hasattr(agent.model, "last_input_token_count") and hasattr(agent.model, "last_output_token_count"):
95
- step_log.input_token_count = agent.model.last_input_token_count
96
- step_log.output_token_count = agent.model.last_output_token_count
97
-
98
- for message in pull_messages_from_step(step_log):
99
- yield message
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
- # Final answer handling
102
- final = handle_agent_output_types(step_log)
103
- if isinstance(final, AgentText):
104
- content = final.to_string()
105
  yield gr.ChatMessage(
106
  role="assistant",
107
- content=content,
108
- metadata={"react": True}
109
  )
110
- else:
111
- yield gr.ChatMessage(role="assistant", content=f"**Final Answer:** {str(final)}")
112
 
113
  class GradioUI:
114
  """Production-ready Gradio interface for travel agent"""
@@ -153,7 +168,7 @@ class GradioUI:
153
  with gr.Row():
154
  text_input = gr.Textbox(
155
  label="Describe your trip",
156
- placeholder="e.g., '5-day trip to Barcelona from New York, Oct 15-19, budget $1500 USD'",
157
  lines=2,
158
  )
159
  submit_btn = gr.Button("Plan My Trip", variant="primary")
@@ -161,7 +176,7 @@ class GradioUI:
161
  gr.Markdown("""
162
  ### 💡 Tips for best results:
163
  • Include: destination, dates, origin city, budget amount + currency
164
- • Example: *"4-day Tokyo trip from London, Nov 5-8, budget 2000 GBP"*
165
  • Agent will research attractions, check weather, convert currency, and generate images
166
  """)
167
 
 
9
  from smolagents.utils import _is_package_available
10
 
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):
 
21
  model_output = re.sub(r"```\s*<end_code>.*", "```", step_log.model_output.strip())
22
  model_output = re.sub(r"<end_code>\s*```", "```", model_output)
23
  if model_output.strip():
24
+ # Prevent code generation display - show as plain text
25
+ if model_output.startswith("```"):
26
+ model_output = model_output.replace("```python", "```\n💭 Reasoning:").replace("```", "")
27
  yield gr.ChatMessage(role="assistant", content=model_output)
28
 
29
+ # Initialize parent_id to None for safe referencing
30
+ parent_id = None
31
+
32
  # Handle tool calls
33
  if hasattr(step_log, "tool_calls") and step_log.tool_calls:
34
  tool_call = step_log.tool_calls[0]
 
58
  yield gr.ChatMessage(
59
  role="assistant",
60
  content=obs,
61
+ metadata={"title": "✅ Result", "parent_id": parent_id},
62
  )
63
 
64
+ # Show errors if any (safe parent_id reference)
65
  if hasattr(step_log, "error") and step_log.error:
66
  yield gr.ChatMessage(
67
  role="assistant",
68
  content=str(step_log.error),
69
+ metadata={"title": "⚠️ Warning", "parent_id": parent_id},
70
  )
71
 
72
  # Step footer with metrics
 
88
  reset_agent_memory: bool = False,
89
  additional_args: Optional[dict] = None,
90
  ):
91
+ """Runs agent and streams messages as gradio ChatMessages with error resilience"""
92
  if not _is_package_available("gradio"):
93
  raise ModuleNotFoundError("Install gradio: `pip install 'smolagents[gradio]'`")
94
 
95
  import gradio as gr
96
 
97
+ try:
98
+ for step_log in agent.run(task, stream=True, reset=reset_agent_memory, additional_args=additional_args):
99
+ if isinstance(step_log, ActionStep):
100
+ # Track tokens if available
101
+ if hasattr(agent.model, "last_input_token_count") and hasattr(agent.model, "last_output_token_count"):
102
+ step_log.input_token_count = agent.model.last_input_token_count
103
+ step_log.output_token_count = agent.model.last_output_token_count
104
+
105
+ for message in pull_messages_from_step(step_log):
106
+ yield message
107
+
108
+ # Final answer handling
109
+ final = handle_agent_output_types(step_log)
110
+ if isinstance(final, AgentText):
111
+ content = final.to_string()
112
+ # Format catalogue nicely with Markdown rendering
113
+ yield gr.ChatMessage(
114
+ role="assistant",
115
+ content=content,
116
+ metadata={"react": True}
117
+ )
118
+ else:
119
+ yield gr.ChatMessage(role="assistant", content=f"**Final Answer:** {str(final)}")
120
 
121
+ except Exception as e:
 
 
 
122
  yield gr.ChatMessage(
123
  role="assistant",
124
+ content=f"⚠️ **Error during planning:** {str(e)}\n\nPlease try again with a clearer trip description (include destination, dates, origin city, and budget).",
125
+ metadata={"title": "❌ Planning Failed"}
126
  )
 
 
127
 
128
  class GradioUI:
129
  """Production-ready Gradio interface for travel agent"""
 
168
  with gr.Row():
169
  text_input = gr.Textbox(
170
  label="Describe your trip",
171
+ placeholder="e.g., '3-day trip to Lisbon from London, Sep 20-22, budget £600 GBP'",
172
  lines=2,
173
  )
174
  submit_btn = gr.Button("Plan My Trip", variant="primary")
 
176
  gr.Markdown("""
177
  ### 💡 Tips for best results:
178
  • Include: destination, dates, origin city, budget amount + currency
179
+ • Example: *"5-day Barcelona trip from NYC, Oct 15-19, budget $1500 USD"*
180
  • Agent will research attractions, check weather, convert currency, and generate images
181
  """)
182