rahulren003's picture
Update app.py
65ad701 verified
from smolagents import (
CodeAgent,
HfApiModel,
load_tool,
tool,
)
import datetime
import requests
import pytz
import yaml
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI
# ======================================================
# 🛠️ TOOLS
# ======================================================
@tool
def get_current_time_in_timezone(timezone: str) -> str:
"""Get the current local time in a timezone.
Args:
timezone: Timezone string like 'Asia/Tokyo', 'UTC', 'Europe/London'
"""
try:
tz = pytz.timezone(timezone)
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
return f"The current local time in {timezone} is {local_time}"
except Exception as e:
return f"Error fetching time for timezone {timezone}: {e}"
# ------------------------------------------------------
@tool
def get_bitcoin_price() -> str:
"""Fetch the current Bitcoin price in USD.
Args:
None
"""
try:
r = requests.get(
"https://api.coingecko.com/api/v3/simple/price",
params={"ids": "bitcoin", "vs_currencies": "usd"},
timeout=10,
)
r.raise_for_status()
return f"Bitcoin price: ${r.json()['bitcoin']['usd']:,} USD"
except Exception as e:
return f"Bitcoin fetch failed: {e}"
# ------------------------------------------------------
@tool
def get_weather_city(city: str) -> str:
"""Get current weather for a city.
Args:
city: City name like Tokyo, London, Paris
"""
try:
geo = requests.get(
"https://geocoding-api.open-meteo.com/v1/search",
params={"name": city, "count": 1},
timeout=10,
).json()
if "results" not in geo:
return f"City not found: {city}"
lat = geo["results"][0]["latitude"]
lon = geo["results"][0]["longitude"]
weather = requests.get(
"https://api.open-meteo.com/v1/forecast",
params={
"latitude": lat,
"longitude": lon,
"current_weather": True,
},
timeout=10,
).json()
current = weather["current_weather"]
return (
f"Weather in {city}: {current['temperature']}°C, "
f"wind {current['windspeed']} km/h"
)
except Exception as e:
return f"Weather lookup failed: {e}"
# ------------------------------------------------------
@tool
def summarize_neural_networks() -> str:
"""Summarize history of neural networks.
Args:
None
"""
try:
r = requests.get(
"https://en.wikipedia.org/api/rest_v1/page/summary/Artificial_neural_network",
timeout=10,
)
r.raise_for_status()
return r.json().get("extract", "")[:1500]
except Exception as e:
return f"Wikipedia fetch failed: {e}"
# ------------------------------------------------------
@tool
def search_ai_news(_: str = "") -> str:
"""Fetch latest AI news from RSS + HackerNews.
Args:
_: Dummy parameter required by tool interface.
"""
try:
articles = []
# RSS feeds
feeds = [
"https://venturebeat.com/category/ai/feed/",
"https://www.technologyreview.com/feed/",
"https://www.artificialintelligence-news.com/feed/",
]
for url in feeds:
r = requests.get(url, timeout=10)
if r.status_code != 200:
continue
from xml.etree import ElementTree as ET
root = ET.fromstring(r.text)
for item in root.findall(".//item")[:3]:
title = item.findtext("title")
link = item.findtext("link")
if title and link:
articles.append(f"- {title}{link}")
# Fallback: HackerNews API
if not articles:
hn = requests.get(
"https://hn.algolia.com/api/v1/search_by_date",
params={"query": "artificial intelligence", "tags": "story"},
timeout=10,
).json()
for hit in hn.get("hits", [])[:6]:
articles.append(
f"- {hit['title']}{hit.get('url','https://news.ycombinator.com')}"
)
if not articles:
return "No AI news found today."
return "\n".join(articles[:10])
except Exception as e:
return f"News fetch failed: {e}"
# ======================================================
# 🧠 MODEL
# ======================================================
final_answer = FinalAnswerTool()
model = HfApiModel(
max_tokens=2096,
temperature=0.5,
model_id="meta-llama/Llama-3.1-8B-Instruct",
)
# ======================================================
# 🌍 IMAGE TOOL
# ======================================================
image_generation_tool = load_tool(
"agents-course/text-to-image",
trust_remote_code=True,
)
# ======================================================
# 📜 PROMPTS
# ======================================================
with open("prompts.yaml", "r") as stream:
prompt_templates = yaml.safe_load(stream)
# ======================================================
# 🤖 AGENT
# ======================================================
agent = CodeAgent(
model=model,
tools=[
final_answer,
get_current_time_in_timezone,
get_bitcoin_price,
get_weather_city,
summarize_neural_networks,
search_ai_news,
image_generation_tool,
],
max_steps=6,
verbosity_level=1,
name="MultiSkillAgent",
description="AI news, crypto, weather, history, timezone and image assistant",
prompt_templates=prompt_templates,
)
# ======================================================
# 🖥️ UI
# ======================================================
GradioUI(agent).launch()