JasonJy14 commited on
Commit
51025ac
Β·
verified Β·
1 Parent(s): a2fae7b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +219 -0
app.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================
2
+ # ALFRED - Your AI Butler Agent
3
+ # HuggingFace AI Agents Course - Unit 1
4
+ # ============================================
5
+
6
+ import gradio as gr
7
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, VisitWebpageTool, HfApiModel, tool
8
+
9
+ # ============================================
10
+ # CUSTOM TOOLS FOR ALFRED
11
+ # ============================================
12
+
13
+ @tool
14
+ def calculator(operation: str) -> str:
15
+ """
16
+ Performs basic math calculations.
17
+
18
+ Args:
19
+ operation: A math expression like "2 + 2" or "10 * 5"
20
+
21
+ Returns:
22
+ The result of the calculation as a string
23
+ """
24
+ try:
25
+ # Only allow safe mathematical operations
26
+ allowed_chars = set('0123456789+-*/(). ')
27
+ if all(c in allowed_chars for c in operation):
28
+ result = eval(operation)
29
+ return f"The result of {operation} is: {result}"
30
+ else:
31
+ return "Invalid operation. Please use only numbers and basic operators (+, -, *, /)."
32
+ except Exception as e:
33
+ return f"Could not calculate that expression. Error: {str(e)}"
34
+
35
+
36
+ @tool
37
+ def get_current_time(timezone: str = "UTC") -> str:
38
+ """
39
+ Gets the current date and time.
40
+
41
+ Args:
42
+ timezone: The timezone to get time for (default is UTC)
43
+
44
+ Returns:
45
+ The current date and time as a string
46
+ """
47
+ from datetime import datetime
48
+ try:
49
+ now = datetime.utcnow()
50
+ return f"The current date and time (UTC) is: {now.strftime('%Y-%m-%d %H:%M:%S')}"
51
+ except Exception as e:
52
+ return f"Could not get the time. Error: {str(e)}"
53
+
54
+
55
+ @tool
56
+ def text_summarizer(text: str) -> str:
57
+ """
58
+ Summarizes a given text into key points.
59
+
60
+ Args:
61
+ text: The text to summarize
62
+
63
+ Returns:
64
+ A summarized version of the text
65
+ """
66
+ if len(text) < 100:
67
+ return f"Text is already short: {text}"
68
+
69
+ # Simple summarization: return first 500 characters with ellipsis
70
+ summary = text[:500] + "..." if len(text) > 500 else text
71
+ return f"Summary: {summary}"
72
+
73
+
74
+ # ============================================
75
+ # ALFRED AGENT SETUP
76
+ # ============================================
77
+
78
+ # Custom system prompt to give Alfred his personality
79
+ ALFRED_SYSTEM_PROMPT = """You are Alfred, a polite, professional, and highly capable AI butler assistant.
80
+
81
+ Your characteristics:
82
+ - You are courteous and address users respectfully
83
+ - You are thorough and provide complete answers
84
+ - You use your available tools wisely to help users
85
+ - You explain your reasoning when solving problems
86
+ - You admit when you don't know something
87
+
88
+ Available tools:
89
+ 1. DuckDuckGoSearchTool - Search the web for information
90
+ 2. VisitWebpageTool - Visit and read webpage content
91
+ 3. calculator - Perform mathematical calculations
92
+ 4. get_current_time - Get the current date and time
93
+ 5. text_summarizer - Summarize long texts
94
+
95
+ Always think step by step and use the most appropriate tool for each task.
96
+ """
97
+
98
+ # Initialize the language model (using HuggingFace's free inference API)
99
+ model = HfApiModel()
100
+
101
+ # Create Alfred with all tools
102
+ alfred = CodeAgent(
103
+ tools=[
104
+ DuckDuckGoSearchTool(),
105
+ VisitWebpageTool(),
106
+ calculator,
107
+ get_current_time,
108
+ text_summarizer,
109
+ ],
110
+ model=model,
111
+ system_prompt=ALFRED_SYSTEM_PROMPT,
112
+ max_steps=10, # Maximum number of steps Alfred can take
113
+ verbosity_level=1 # Show some logging for debugging
114
+ )
115
+
116
+
117
+ # ============================================
118
+ # GRADIO INTERFACE
119
+ # ============================================
120
+
121
+ def chat_with_alfred(message, history):
122
+ """
123
+ Process user message and return Alfred's response.
124
+
125
+ Args:
126
+ message: The user's input message
127
+ history: Chat history (for context)
128
+
129
+ Returns:
130
+ Alfred's response as a string
131
+ """
132
+ if not message.strip():
133
+ return "I beg your pardon, but you haven't asked me anything. How may I assist you?"
134
+
135
+ try:
136
+ # Run Alfred on the user's query
137
+ response = alfred.run(message)
138
+
139
+ # Format the response nicely
140
+ formatted_response = f"🎩 **Alfred's Response:**\n\n{str(response)}"
141
+ return formatted_response
142
+
143
+ except Exception as e:
144
+ error_message = (
145
+ f"I do apologize, but I encountered an issue while processing your request.\n\n"
146
+ f"**Error details:** {str(e)}\n\n"
147
+ f"Please try rephrasing your question or ask something else."
148
+ )
149
+ return error_message
150
+
151
+
152
+ # Create the Gradio interface
153
+ with gr.Blocks(
154
+ title="Alfred - AI Butler Agent",
155
+ theme=gr.themes.Soft()
156
+ ) as demo:
157
+
158
+ # Header
159
+ gr.Markdown(
160
+ """
161
+ # 🎩 Alfred - Your AI Butler
162
+
163
+ Welcome! I am Alfred, your personal AI assistant. I can help you with:
164
+ - πŸ” **Web searches** - Find information on any topic
165
+ - 🌐 **Reading webpages** - Extract content from URLs
166
+ - πŸ”’ **Calculations** - Perform mathematical operations
167
+ - πŸ• **Time queries** - Get current date and time
168
+ - πŸ“ **Text summarization** - Summarize long texts
169
+
170
+ *How may I be of service today?*
171
+
172
+ ---
173
+ """
174
+ )
175
+
176
+ # Chat interface
177
+ chatbot = gr.ChatInterface(
178
+ fn=chat_with_alfred,
179
+ examples=[
180
+ "What is the latest news about artificial intelligence?",
181
+ "Calculate 1547 * 32 + 89",
182
+ "What time is it now?",
183
+ "Search for information about climate change solutions",
184
+ "What are the top programming languages in 2024?",
185
+ ],
186
+ retry_btn="πŸ”„ Retry",
187
+ undo_btn="↩️ Undo",
188
+ clear_btn="πŸ—‘οΈ Clear",
189
+ )
190
+
191
+ # Footer
192
+ gr.Markdown(
193
+ """
194
+ ---
195
+
196
+ ### About Alfred
197
+
198
+ Alfred is an AI agent built using the **smolagents** framework from HuggingFace.
199
+ This agent was created as part of the **HuggingFace AI Agents Course - Unit 1**.
200
+
201
+ **Framework:** smolagents | **Model:** HuggingFace Inference API
202
+
203
+ *Built with ❀️ for the AI Agents Course*
204
+ """
205
+ )
206
+
207
+
208
+ # ============================================
209
+ # LAUNCH THE APPLICATION
210
+ # ============================================
211
+
212
+ if __name__ == "__main__":
213
+ # Launch with share=False for local testing
214
+ # Set share=True if you want a public link
215
+ demo.launch(
216
+ server_name="0.0.0.0",
217
+ server_port=7860,
218
+ share=False
219
+ )