Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,297 +3,89 @@ import gradio as gr
|
|
| 3 |
import datetime
|
| 4 |
import pytz
|
| 5 |
import asyncio
|
| 6 |
-
import requests
|
| 7 |
|
| 8 |
# Framework 1: LlamaIndex
|
| 9 |
-
from llama_index.core.agent import
|
| 10 |
from llama_index.core.tools import FunctionTool
|
| 11 |
-
from llama_index.llms.
|
| 12 |
|
| 13 |
# Framework 2: smolagents
|
| 14 |
-
from smolagents import CodeAgent, DuckDuckGoSearchTool, tool
|
| 15 |
|
| 16 |
# 0. SHARED CONFIG
|
| 17 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
|
|
|
| 18 |
MODEL_ID = "Qwen/Qwen2.5-7B-Instruct"
|
| 19 |
|
| 20 |
# ==========================================
|
| 21 |
-
#
|
| 22 |
# ==========================================
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
if api_key:
|
| 30 |
-
url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid={api_key}&units=metric"
|
| 31 |
-
response = requests.get(url, timeout=5)
|
| 32 |
-
data = response.json()
|
| 33 |
-
|
| 34 |
-
if response.status_code == 200:
|
| 35 |
-
temp = data['main']['temp']
|
| 36 |
-
desc = data['weather'][0]['description']
|
| 37 |
-
humidity = data['main']['humidity']
|
| 38 |
-
return f"🌤️ Weather in {location}: {desc}, {temp}°C, Humidity: {humidity}%"
|
| 39 |
-
else:
|
| 40 |
-
# Fallback to mock data if API fails
|
| 41 |
-
return f"🌤️ Weather in {location}: Sunny, 22°C (mock data - add real API key for live weather)"
|
| 42 |
-
else:
|
| 43 |
-
# Mock weather if no API key
|
| 44 |
-
weather_data = {
|
| 45 |
-
"tokyo": "Cloudy, 18°C",
|
| 46 |
-
"london": "Rainy, 12°C",
|
| 47 |
-
"new york": "Sunny, 15°C",
|
| 48 |
-
"paris": "Partly Cloudy, 14°C",
|
| 49 |
-
"sydney": "Clear, 22°C"
|
| 50 |
-
}
|
| 51 |
-
for city, weather in weather_data.items():
|
| 52 |
-
if city in location.lower():
|
| 53 |
-
return f"🌤️ Weather in {location}: {weather} (mock data)"
|
| 54 |
-
return f"🌤️ Weather in {location}: Sunny, 22°C (mock data - set WEATHER_API_KEY for real data)"
|
| 55 |
-
except Exception as e:
|
| 56 |
-
return f"🌤️ Weather in {location}: Sunny, 22°C (error: {str(e)[:50]})"
|
| 57 |
|
| 58 |
-
# ==========================================
|
| 59 |
-
# TIME FUNCTIONS
|
| 60 |
-
# ==========================================
|
| 61 |
def get_tokyo_time() -> str:
|
| 62 |
"""Returns the current time in Tokyo, Japan."""
|
| 63 |
tz = pytz.timezone('Asia/Tokyo')
|
| 64 |
-
|
| 65 |
-
return f"🕐 Tokyo Time: {now.strftime('%A, %B %d, %Y %H:%M:%S')}"
|
| 66 |
|
| 67 |
-
|
| 68 |
-
"""Get current time for various cities."""
|
| 69 |
-
timezones = {
|
| 70 |
-
"Tokyo": "Asia/Tokyo",
|
| 71 |
-
"New York": "America/New_York",
|
| 72 |
-
"London": "Europe/London",
|
| 73 |
-
"Paris": "Europe/Paris",
|
| 74 |
-
"Sydney": "Australia/Sydney",
|
| 75 |
-
"Dubai": "Asia/Dubai",
|
| 76 |
-
"Singapore": "Asia/Singapore"
|
| 77 |
-
}
|
| 78 |
-
|
| 79 |
-
if city.lower() != "all" and city.title() in timezones:
|
| 80 |
-
tz = pytz.timezone(timezones[city.title()])
|
| 81 |
-
now = datetime.datetime.now(tz)
|
| 82 |
-
return f"🕐 {city} Time: {now.strftime('%H:%M:%S')}"
|
| 83 |
-
|
| 84 |
-
result = "🌍 World Clock:\n"
|
| 85 |
-
for city_name, tz_str in timezones.items():
|
| 86 |
-
tz = pytz.timezone(tz_str)
|
| 87 |
-
now = datetime.datetime.now(tz)
|
| 88 |
-
result += f"• {city_name}: {now.strftime('%H:%M:%S')}\n"
|
| 89 |
-
return result
|
| 90 |
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
|
|
|
| 96 |
try:
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
# Create a safe environment
|
| 101 |
-
safe_dict = {
|
| 102 |
-
'abs': abs, 'round': round, 'min': min, 'max': max,
|
| 103 |
-
'sum': sum, 'len': len, 'int': int, 'float': float,
|
| 104 |
-
'math': math, 'sqrt': math.sqrt, 'pow': math.pow,
|
| 105 |
-
'sin': math.sin, 'cos': math.cos, 'tan': math.tan,
|
| 106 |
-
'pi': math.pi, 'e': math.e
|
| 107 |
-
}
|
| 108 |
-
|
| 109 |
-
# Remove any dangerous characters
|
| 110 |
-
expression = ''.join(c for c in expression if c.isalnum() or c in ' +-*/().,')
|
| 111 |
-
|
| 112 |
-
result = eval(expression, {"__builtins__": {}}, safe_dict)
|
| 113 |
-
return f"🧮 {expression} = {result}"
|
| 114 |
except Exception as e:
|
| 115 |
-
return f"
|
| 116 |
-
|
| 117 |
-
# ==========================================
|
| 118 |
-
# PART 1: LLAMAINDEX AGENT (FIXED)
|
| 119 |
-
# ==========================================
|
| 120 |
-
try:
|
| 121 |
-
li_llm = HuggingFaceInferenceAPI(
|
| 122 |
-
model_name=MODEL_ID,
|
| 123 |
-
token=HF_TOKEN,
|
| 124 |
-
)
|
| 125 |
-
|
| 126 |
-
# Create tools for LlamaIndex
|
| 127 |
-
li_tools = [
|
| 128 |
-
FunctionTool.from_defaults(fn=get_tokyo_time, name="get_tokyo_time"),
|
| 129 |
-
FunctionTool.from_defaults(fn=get_weather, name="get_weather"),
|
| 130 |
-
FunctionTool.from_defaults(fn=get_world_time, name="get_world_time"),
|
| 131 |
-
FunctionTool.from_defaults(fn=calculate, name="calculate")
|
| 132 |
-
]
|
| 133 |
-
|
| 134 |
-
li_agent = ReActAgent.from_tools(
|
| 135 |
-
li_tools,
|
| 136 |
-
llm=li_llm,
|
| 137 |
-
verbose=False
|
| 138 |
-
)
|
| 139 |
-
|
| 140 |
-
async def chat_llama(message, history):
|
| 141 |
-
try:
|
| 142 |
-
response = await li_agent.achat(message)
|
| 143 |
-
return str(response)
|
| 144 |
-
except Exception as e:
|
| 145 |
-
return f"❌ LlamaIndex Error: {str(e)[:200]}"
|
| 146 |
-
|
| 147 |
-
except Exception as e:
|
| 148 |
-
print(f"LlamaIndex setup error: {e}")
|
| 149 |
-
async def chat_llama(message, history):
|
| 150 |
-
return f"❌ LlamaIndex not available: {str(e)[:200]}"
|
| 151 |
|
| 152 |
# ==========================================
|
| 153 |
# PART 2: SMOLAGENTS
|
| 154 |
# ==========================================
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
try:
|
| 181 |
-
response = smol_agent.run(message)
|
| 182 |
-
return str(response)
|
| 183 |
-
except Exception as e:
|
| 184 |
-
return f"❌ Smolagents Error: {str(e)[:200]}"
|
| 185 |
-
|
| 186 |
-
except Exception as e:
|
| 187 |
-
print(f"Smolagents setup error: {e}")
|
| 188 |
-
def chat_smol(message, history):
|
| 189 |
-
return f"❌ Smolagents not available: {str(e)[:200]}"
|
| 190 |
|
| 191 |
# ==========================================
|
| 192 |
# PART 3: UNIFIED GRADIO UI
|
| 193 |
# ==========================================
|
| 194 |
-
with gr.Blocks(theme=gr.themes.Soft()
|
| 195 |
-
#
|
| 196 |
-
gr.Markdown("
|
| 197 |
-
gr.Markdown(f"**Model:** {MODEL_ID} | **Provider:** Together AI")
|
| 198 |
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
# Weather Tool
|
| 205 |
-
with gr.Group():
|
| 206 |
-
weather_city = gr.Textbox(
|
| 207 |
-
label="Check Weather",
|
| 208 |
-
placeholder="Enter city name...",
|
| 209 |
-
scale=4
|
| 210 |
-
)
|
| 211 |
-
weather_btn = gr.Button("🌤️ Get Weather", scale=1)
|
| 212 |
-
weather_output = gr.Textbox(label="Result", interactive=False)
|
| 213 |
-
|
| 214 |
-
def get_weather_quick(city):
|
| 215 |
-
return get_weather(city) if city else "Please enter a city name."
|
| 216 |
-
|
| 217 |
-
weather_btn.click(
|
| 218 |
-
get_weather_quick,
|
| 219 |
-
inputs=weather_city,
|
| 220 |
-
outputs=weather_output
|
| 221 |
-
)
|
| 222 |
-
|
| 223 |
-
# Calculator Tool
|
| 224 |
-
with gr.Group():
|
| 225 |
-
calc_expr = gr.Textbox(
|
| 226 |
-
label="Calculator",
|
| 227 |
-
placeholder="Enter math expression...",
|
| 228 |
-
scale=4
|
| 229 |
-
)
|
| 230 |
-
calc_btn = gr.Button("🧮 Calculate", scale=1)
|
| 231 |
-
calc_output = gr.Textbox(label="Result", interactive=False)
|
| 232 |
-
|
| 233 |
-
calc_btn.click(
|
| 234 |
-
calculate,
|
| 235 |
-
inputs=calc_expr,
|
| 236 |
-
outputs=calc_output
|
| 237 |
-
)
|
| 238 |
-
|
| 239 |
-
# Time Tool
|
| 240 |
-
with gr.Group():
|
| 241 |
-
time_btn = gr.Button("🌍 Show World Clock")
|
| 242 |
-
time_output = gr.Textbox(label="World Times", interactive=False)
|
| 243 |
-
|
| 244 |
-
time_btn.click(
|
| 245 |
-
lambda: get_world_time("all"),
|
| 246 |
-
outputs=time_output
|
| 247 |
-
)
|
| 248 |
-
|
| 249 |
-
# Chat Agents Section
|
| 250 |
-
with gr.Row():
|
| 251 |
-
with gr.Tabs():
|
| 252 |
-
with gr.TabItem("🦙 LlamaIndex Agent"):
|
| 253 |
-
llama_chat = gr.ChatInterface(
|
| 254 |
-
fn=chat_llama,
|
| 255 |
-
title="LlamaIndex ReAct Agent",
|
| 256 |
-
description="Structured agent with reasoning capabilities",
|
| 257 |
-
examples=[
|
| 258 |
-
"What's the weather in Tokyo?",
|
| 259 |
-
"What time is it in New York?",
|
| 260 |
-
"Calculate 25 * 4 + 18",
|
| 261 |
-
"Tell me the time in London and Sydney"
|
| 262 |
-
]
|
| 263 |
-
)
|
| 264 |
-
|
| 265 |
-
with gr.TabItem("🔬 Smolagents"):
|
| 266 |
-
smol_chat = gr.ChatInterface(
|
| 267 |
-
fn=chat_smol,
|
| 268 |
-
title="Smolagents CodeAgent",
|
| 269 |
-
description="Code-based agent with web search",
|
| 270 |
-
examples=[
|
| 271 |
-
"Search for AI news",
|
| 272 |
-
"What's the weather like today?",
|
| 273 |
-
"Calculate 15% of 200",
|
| 274 |
-
"Tell me about machine learning"
|
| 275 |
-
]
|
| 276 |
-
)
|
| 277 |
-
|
| 278 |
-
# Footer
|
| 279 |
-
gr.Markdown("---")
|
| 280 |
-
gr.Markdown("""
|
| 281 |
-
### 💡 Try asking:
|
| 282 |
-
- "What's the weather in London and what time is it there?"
|
| 283 |
-
- "Calculate the area of a circle with radius 5"
|
| 284 |
-
- "Search for latest technology news"
|
| 285 |
-
- "Compare time between Tokyo and New York"
|
| 286 |
-
""")
|
| 287 |
-
|
| 288 |
-
# API Key Notice
|
| 289 |
-
if not os.getenv("WEATHER_API_KEY"):
|
| 290 |
-
gr.Markdown("""
|
| 291 |
-
⚠️ **Note:** Using mock weather data. For real weather, add `WEATHER_API_KEY` to your Hugging Face Space secrets.
|
| 292 |
-
""")
|
| 293 |
|
| 294 |
if __name__ == "__main__":
|
| 295 |
-
demo.launch(
|
| 296 |
-
server_name="0.0.0.0",
|
| 297 |
-
server_port=7860,
|
| 298 |
-
share=True
|
| 299 |
-
)
|
|
|
|
| 3 |
import datetime
|
| 4 |
import pytz
|
| 5 |
import asyncio
|
|
|
|
| 6 |
|
| 7 |
# Framework 1: LlamaIndex
|
| 8 |
+
from llama_index.core.agent.workflow import AgentWorkflow
|
| 9 |
from llama_index.core.tools import FunctionTool
|
| 10 |
+
from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI
|
| 11 |
|
| 12 |
# Framework 2: smolagents
|
| 13 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, tool, InferenceClientModel
|
| 14 |
|
| 15 |
# 0. SHARED CONFIG
|
| 16 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 17 |
+
# 7B is the sweet spot for free serverless inference in 2026
|
| 18 |
MODEL_ID = "Qwen/Qwen2.5-7B-Instruct"
|
| 19 |
|
| 20 |
# ==========================================
|
| 21 |
+
# PART 1: LLAMAINDEX AGENT
|
| 22 |
# ==========================================
|
| 23 |
+
li_llm = HuggingFaceInferenceAPI(
|
| 24 |
+
model_name=MODEL_ID,
|
| 25 |
+
token=HF_TOKEN,
|
| 26 |
+
provider="together"
|
| 27 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
|
|
|
|
|
|
|
|
|
| 29 |
def get_tokyo_time() -> str:
|
| 30 |
"""Returns the current time in Tokyo, Japan."""
|
| 31 |
tz = pytz.timezone('Asia/Tokyo')
|
| 32 |
+
return f"The current time in Tokyo is {datetime.datetime.now(tz).strftime('%H:%M:%S')}"
|
|
|
|
| 33 |
|
| 34 |
+
li_tools = [FunctionTool.from_defaults(fn=get_tokyo_time)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
+
li_agent = AgentWorkflow.from_tools_or_functions(
|
| 37 |
+
li_tools,
|
| 38 |
+
llm=li_llm,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
async def chat_llama(message, history):
|
| 42 |
try:
|
| 43 |
+
result = await li_agent.run(user_msg=message)
|
| 44 |
+
return str(result)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
except Exception as e:
|
| 46 |
+
return f"LlamaIndex Error: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
# ==========================================
|
| 49 |
# PART 2: SMOLAGENTS
|
| 50 |
# ==========================================
|
| 51 |
+
smol_model = InferenceClientModel(
|
| 52 |
+
model_id=MODEL_ID,
|
| 53 |
+
token=HF_TOKEN,
|
| 54 |
+
provider="together"
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
@tool
|
| 58 |
+
def weather_tool(location: str) -> str:
|
| 59 |
+
"""Get the current weather for a location.
|
| 60 |
+
Args:
|
| 61 |
+
location: The city name.
|
| 62 |
+
"""
|
| 63 |
+
return f"The weather in {location} is currently sunny and 22°C."
|
| 64 |
+
|
| 65 |
+
smol_agent = CodeAgent(
|
| 66 |
+
model=smol_model,
|
| 67 |
+
tools=[weather_tool, DuckDuckGoSearchTool()]
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
def chat_smol(message, history):
|
| 71 |
+
try:
|
| 72 |
+
response = smol_agent.run(message)
|
| 73 |
+
return str(response)
|
| 74 |
+
except Exception as e:
|
| 75 |
+
return f"Smolagents Error: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
# ==========================================
|
| 78 |
# PART 3: UNIFIED GRADIO UI
|
| 79 |
# ==========================================
|
| 80 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 81 |
+
gr.Markdown("# 🤖 Consolidated AI Agent Space")
|
| 82 |
+
gr.Markdown(f"Currently using **{MODEL_ID}** via Together AI Provider.")
|
|
|
|
| 83 |
|
| 84 |
+
with gr.Tab("LlamaIndex (Workflow)"):
|
| 85 |
+
gr.ChatInterface(fn=chat_llama)
|
| 86 |
+
|
| 87 |
+
with gr.Tab("smolagents (CodeAgent)"):
|
| 88 |
+
gr.ChatInterface(fn=chat_smol)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
if __name__ == "__main__":
|
| 91 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|