Ventahana commited on
Commit
2aff823
Β·
verified Β·
1 Parent(s): 4b47493

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -95
app.py CHANGED
@@ -1,6 +1,6 @@
1
  import gradio as gr
2
  from smolagents import GradioUI, CodeAgent, HfApiModel
3
- import re
4
 
5
  # Import our custom tools from their modules
6
  from tools import DuckDuckGoSearchTool, WeatherInfoTool, HubStatsTool
@@ -21,100 +21,73 @@ hub_stats_tool = HubStatsTool()
21
  # Load the guest dataset and initialize the guest info tool
22
  guest_tool = load_guest_dataset()
23
 
24
- class FormattedCodeAgent(CodeAgent):
 
 
 
 
 
 
 
25
  def run(self, query: str):
26
- # Get the raw response
27
- raw_response = super().run(query)
28
-
29
- print(f"πŸ“¦ Raw response from Alfred:\n{raw_response}")
30
 
31
- # Parse the response to extract meaningful content
32
- if "Final answer:" in raw_response:
33
- # Extract just the final answer
34
- parts = raw_response.split("Final answer:")
35
- if len(parts) > 1:
36
- final_answer = parts[-1].strip()
37
-
38
- # Clean up Python list formatting
39
- if final_answer.startswith('[') and final_answer.endswith(']'):
40
- # It's a Python list - format as bullet points
41
- try:
42
- import ast
43
- guest_list = ast.literal_eval(final_answer)
44
- if isinstance(guest_list, list):
45
- formatted = "🎩 **Gala Guests Found:**\n\n"
46
- for guest in guest_list:
47
- formatted += f"β€’ {guest}\n"
48
- return formatted
49
- except:
50
- pass
51
-
52
- # Return cleaned answer
53
- return final_answer.replace("['", "").replace("']", "").replace("', '", "\nβ€’ ")
54
 
55
- # Check for printed output
56
- if "Attending the gala are:" in raw_response:
57
- # Extract the guest list from print statement
58
- lines = raw_response.split('\n')
59
- for line in lines:
60
- if "Attending the gala are:" in line:
61
- # Try to extract list
62
- import re
63
- match = re.search(r"\[(.*?)\]", line)
64
- if match:
65
- guest_str = match.group(1)
66
- guests = [g.strip().strip("'\"") for g in guest_str.split(',')]
67
  formatted = "🎩 **Gala Guests:**\n\n"
68
- for guest in guests:
69
  formatted += f"β€’ {guest}\n"
70
  return formatted
71
-
72
- # Default: clean up code execution traces
73
- lines = raw_response.split('\n')
74
- cleaned = []
75
- skip = False
76
-
77
- for line in lines:
78
- # Skip execution headers
79
- if line.startswith('━━━━') or line.startswith('─ Executing'):
80
- skip = True
81
- continue
82
- if skip and (line.startswith('─') or line.strip() == ''):
83
- continue
84
- skip = False
85
 
86
- # Skip code blocks and execution logs
87
- if line.startswith('```') or line.startswith('Execution logs:'):
88
- continue
89
-
90
- cleaned.append(line)
 
 
91
 
92
- return '\n'.join(cleaned).strip()
93
 
94
- # Create Alfred with custom formatting
95
- alfred = FormattedCodeAgent(
96
  tools=[guest_tool, weather_info_tool, hub_stats_tool, search_tool],
97
  model=model,
98
  add_base_tools=True,
99
- planning_interval=3,
100
- max_steps=5
101
  )
102
 
103
  # Test
104
- print("\nπŸ§ͺ TESTING ALFRED...")
105
- test_query = "Who is coming to the gala?"
106
- print(f"Query: '{test_query}'")
107
- response = alfred.run(test_query)
108
- print(f"Response:\n{response}")
109
 
110
- # Create a custom Gradio interface
111
  with gr.Blocks(title="🎩 Alfred Assistant") as demo:
112
  gr.Markdown("# 🎩 Alfred Assistant")
113
- gr.Markdown("Your AI assistant with multiple capabilities including guest information retrieval.")
114
 
115
- # Main chat interface
116
  chatbot = gr.Chatbot(height=400)
117
- msg = gr.Textbox(label="Ask Alfred anything...")
118
  clear = gr.ClearButton([msg, chatbot])
119
 
120
  def respond(message, chat_history):
@@ -124,26 +97,19 @@ with gr.Blocks(title="🎩 Alfred Assistant") as demo:
124
 
125
  msg.submit(respond, [msg, chatbot], [msg, chatbot])
126
 
127
- # Test Section
128
- with gr.Accordion("πŸ§ͺ Test Queries", open=False):
129
- gr.Markdown("Try these example queries:")
130
-
131
- test_queries = [
132
- "Tell me about 'Lady Ada Lovelace'",
133
- "What's the weather in Paris?",
134
- "Show me stats for the gpt2 model",
135
- "Search for latest AI news",
136
- "Who is coming to the gala?"
137
- ]
138
-
139
- with gr.Row():
140
- for query in test_queries:
141
- test_btn = gr.Button(query, size="sm")
142
- test_btn.click(
143
- fn=lambda q=query: q,
144
- inputs=[],
145
- outputs=[msg]
146
- )
147
 
148
  if __name__ == "__main__":
149
  demo.launch()
 
1
  import gradio as gr
2
  from smolagents import GradioUI, CodeAgent, HfApiModel
3
+ import ast
4
 
5
  # Import our custom tools from their modules
6
  from tools import DuckDuckGoSearchTool, WeatherInfoTool, HubStatsTool
 
21
  # Load the guest dataset and initialize the guest info tool
22
  guest_tool = load_guest_dataset()
23
 
24
+ # Make guest tool description VERY clear
25
+ guest_tool.description = """USE THIS TOOL FOR GALA GUEST QUESTIONS!
26
+ Official guest database with names, relations, descriptions, emails.
27
+ Query examples: "all guests", "Lady Ada Lovelace", "scientists".
28
+ Returns formatted guest information."""
29
+
30
+ # Simple agent that formats output
31
+ class SimpleAgent(CodeAgent):
32
  def run(self, query: str):
33
+ response = super().run(query)
 
 
 
34
 
35
+ # Handle list responses
36
+ if isinstance(response, list):
37
+ if response:
38
+ formatted = "🎩 **Gala Guests:**\n\n"
39
+ for guest in response:
40
+ formatted += f"β€’ {guest}\n"
41
+ return formatted
42
+ return "No guests found."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
+ # Handle string responses that contain lists
45
+ if isinstance(response, str):
46
+ # Check if it's a string representation of a list
47
+ response = response.strip()
48
+ if (response.startswith('[') and response.endswith(']')) or \
49
+ (response.startswith("['") and response.endswith("']")):
50
+ try:
51
+ guest_list = ast.literal_eval(response)
52
+ if isinstance(guest_list, list):
 
 
 
53
  formatted = "🎩 **Gala Guests:**\n\n"
54
+ for guest in guest_list:
55
  formatted += f"β€’ {guest}\n"
56
  return formatted
57
+ except:
58
+ pass
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
+ # Clean up code execution traces
61
+ lines = response.split('\n')
62
+ clean_lines = []
63
+ for line in lines:
64
+ if not any(line.startswith(x) for x in ['━━━━', '─ Executing', '```', 'Execution logs:']):
65
+ clean_lines.append(line)
66
+ return '\n'.join(clean_lines).strip()
67
 
68
+ return str(response)
69
 
70
+ # Create Alfred
71
+ alfred = SimpleAgent(
72
  tools=[guest_tool, weather_info_tool, hub_stats_tool, search_tool],
73
  model=model,
74
  add_base_tools=True,
75
+ planning_interval=2,
76
+ max_steps=3
77
  )
78
 
79
  # Test
80
+ print("\n🎩 Testing Alfred...")
81
+ test_response = alfred.run("Who is coming to the gala?")
82
+ print(f"Test response:\n{test_response}")
 
 
83
 
84
+ # Create Gradio interface
85
  with gr.Blocks(title="🎩 Alfred Assistant") as demo:
86
  gr.Markdown("# 🎩 Alfred Assistant")
87
+ gr.Markdown("Ask about gala guests, weather, model stats, or search the web.")
88
 
 
89
  chatbot = gr.Chatbot(height=400)
90
+ msg = gr.Textbox(label="Your question...")
91
  clear = gr.ClearButton([msg, chatbot])
92
 
93
  def respond(message, chat_history):
 
97
 
98
  msg.submit(respond, [msg, chatbot], [msg, chatbot])
99
 
100
+ # Examples
101
+ with gr.Accordion("πŸ“‹ Example Questions", open=True):
102
+ gr.Examples(
103
+ examples=[
104
+ "Who is coming to the gala?",
105
+ "Tell me about Lady Ada Lovelace",
106
+ "What's the weather in London?",
107
+ "Show me stats for GPT-2",
108
+ "Search for Python programming news"
109
+ ],
110
+ inputs=msg,
111
+ label="Click any example:"
112
+ )
 
 
 
 
 
 
 
113
 
114
  if __name__ == "__main__":
115
  demo.launch()