Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,6 @@
|
|
| 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,
|
| 8 |
|
| 9 |
# ============================================
|
| 10 |
# CUSTOM TOOLS FOR ALFRED
|
|
@@ -22,198 +18,142 @@ def calculator(operation: str) -> str:
|
|
| 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
|
| 34 |
|
| 35 |
|
| 36 |
@tool
|
| 37 |
-
def get_current_time(
|
| 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 |
-
|
| 49 |
-
|
| 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
|
| 57 |
"""
|
| 58 |
-
|
| 59 |
|
| 60 |
Args:
|
| 61 |
-
|
| 62 |
|
| 63 |
Returns:
|
| 64 |
-
A
|
| 65 |
"""
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
return f"
|
| 72 |
|
| 73 |
|
| 74 |
# ============================================
|
| 75 |
-
#
|
| 76 |
# ============================================
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 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 |
-
#
|
| 99 |
-
|
|
|
|
| 100 |
|
| 101 |
-
# Create Alfred with all tools
|
| 102 |
alfred = CodeAgent(
|
| 103 |
tools=[
|
| 104 |
DuckDuckGoSearchTool(),
|
| 105 |
-
VisitWebpageTool(),
|
| 106 |
calculator,
|
| 107 |
get_current_time,
|
| 108 |
-
|
| 109 |
],
|
| 110 |
model=model,
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
verbosity_level=1 # Show some logging for debugging
|
| 114 |
)
|
| 115 |
|
| 116 |
-
|
| 117 |
# ============================================
|
| 118 |
-
#
|
| 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 "
|
| 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 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
)
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
|
|
|
|
|
|
| 157 |
|
| 158 |
-
# Header
|
| 159 |
gr.Markdown(
|
| 160 |
"""
|
| 161 |
# 🎩 Alfred - Your AI Butler
|
| 162 |
|
| 163 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
---
|
| 173 |
"""
|
| 174 |
)
|
| 175 |
|
| 176 |
-
# Chat interface
|
| 177 |
chatbot = gr.ChatInterface(
|
| 178 |
fn=chat_with_alfred,
|
| 179 |
examples=[
|
| 180 |
-
"What is
|
| 181 |
-
"Calculate
|
| 182 |
"What time is it now?",
|
| 183 |
-
"
|
| 184 |
-
"
|
|
|
|
| 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
|
| 210 |
# ============================================
|
| 211 |
|
| 212 |
-
if
|
| 213 |
-
|
| 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 |
-
)
|
|
|
|
| 1 |
+
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel, tool
|
| 4 |
|
| 5 |
# ============================================
|
| 6 |
# CUSTOM TOOLS FOR ALFRED
|
|
|
|
| 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()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|