lmrkmrcs commited on
Commit
92ccbca
·
verified ·
1 Parent(s): 99e044a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +159 -0
app.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel, tool
4
+
5
+ # ============================================
6
+ # CUSTOM TOOLS FOR ALFRED
7
+ # ============================================
8
+
9
+ @tool
10
+ def calculator(operation: str) -> str:
11
+ """
12
+ Performs basic math calculations.
13
+
14
+ Args:
15
+ operation: A math expression like "2 + 2" or "10 * 5"
16
+
17
+ Returns:
18
+ The result of the calculation as a string
19
+ """
20
+ try:
21
+ allowed_chars = set('0123456789+-*/(). ')
22
+ if all(c in allowed_chars for c in operation):
23
+ result = eval(operation)
24
+ return f"The result of {operation} is: {result}"
25
+ else:
26
+ return "Invalid operation. Please use only numbers and basic operators."
27
+ except Exception as e:
28
+ return f"Could not calculate. Error: {str(e)}"
29
+
30
+
31
+ @tool
32
+ def get_current_time() -> str:
33
+ """
34
+ Gets the current date and time in UTC.
35
+
36
+ Returns:
37
+ The current date and time as a string
38
+ """
39
+ from datetime import datetime
40
+ now = datetime.utcnow()
41
+ return f"Current date and time (UTC): {now.strftime('%Y-%m-%d %H:%M:%S')}"
42
+
43
+
44
+ @tool
45
+ def get_weather_info(city: str) -> str:
46
+ """
47
+ Gets a simple weather description for a city (mock data for demo).
48
+
49
+ Args:
50
+ city: The name of the city to get weather for
51
+
52
+ Returns:
53
+ A weather description string
54
+ """
55
+ # This is mock data - in production you'd use a real weather API
56
+ import random
57
+ conditions = ["sunny", "partly cloudy", "cloudy", "rainy", "windy"]
58
+ temp = random.randint(15, 30)
59
+ condition = random.choice(conditions)
60
+ return f"Weather in {city}: {temp}°C, {condition}"
61
+
62
+
63
+ # ============================================
64
+ # MODEL SETUP - Using free-tier compatible model
65
+ # ============================================
66
+
67
+ model = InferenceClientModel(
68
+ model_id="Qwen/Qwen2.5-7B-Instruct", # Smaller model that works on free tier
69
+ token=os.environ.get("HF_TOKEN"),
70
+ )
71
+
72
+ # ============================================
73
+ # ALFRED AGENT SETUP
74
+ # ============================================
75
+
76
+ alfred = CodeAgent(
77
+ tools=[
78
+ DuckDuckGoSearchTool(),
79
+ calculator,
80
+ get_current_time,
81
+ get_weather_info,
82
+ ],
83
+ model=model,
84
+ max_steps=5,
85
+ verbosity_level=1,
86
+ )
87
+
88
+ # ============================================
89
+ # CHAT FUNCTION
90
+ # ============================================
91
+
92
+ def chat_with_alfred(message, history):
93
+ """
94
+ Process user message and return Alfred's response.
95
+ """
96
+ if not message.strip():
97
+ return "Please ask me something. How may I assist you today?"
98
+
99
+ try:
100
+ response = alfred.run(message)
101
+ return str(response)
102
+ except Exception as e:
103
+ error_msg = str(e)
104
+ # Provide helpful error messages
105
+ if "404" in error_msg or "not found" in error_msg.lower():
106
+ return "I'm having trouble connecting to my AI backend. Please check the HF_TOKEN and model availability."
107
+ elif "rate" in error_msg.lower() or "limit" in error_msg.lower():
108
+ return "I've hit a rate limit. Please wait a moment and try again."
109
+ else:
110
+ return f"I encountered an issue: {error_msg}"
111
+
112
+
113
+ # ============================================
114
+ # GRADIO INTERFACE
115
+ # ============================================
116
+
117
+ with gr.Blocks(title="Alfred - AI Butler Agent") as demo:
118
+
119
+ gr.Markdown(
120
+ """
121
+ # 🎩 Alfred - Your AI Butler
122
+
123
+ Good day! I am Alfred, your personal AI assistant. I am at your service.
124
+
125
+ ### My Capabilities:
126
+ - 🔍 **Web Search** - I can search the internet for information
127
+ - 🧮 **Calculator** - I can perform mathematical calculations
128
+ - 🕐 **Current Time** - I can tell you the current time (UTC)
129
+ - 🌤️ **Weather** - I can provide weather information
130
+
131
+ ---
132
+ """
133
+ )
134
+
135
+ chatbot = gr.ChatInterface(
136
+ fn=chat_with_alfred,
137
+ examples=[
138
+ "What is artificial intelligence?",
139
+ "Calculate 25 * 4 + 10",
140
+ "What time is it now?",
141
+ "What's the weather in London?",
142
+ "Search for the latest news about AI",
143
+ "Calculate (100 + 50) * 2 / 5",
144
+ ],
145
+ )
146
+
147
+ gr.Markdown(
148
+ """
149
+ ---
150
+ *Built with [smolagents](https://github.com/huggingface/smolagents) and Gradio | Unit 1 Project*
151
+ """
152
+ )
153
+
154
+ # ============================================
155
+ # LAUNCH APP
156
+ # ============================================
157
+
158
+ if __name__ == "__main__":
159
+ demo.launch()