CryptoBrief / app.py
walidukdz's picture
Update app.py
5dbc6a2 verified
from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
import datetime
import requests
import pytz
import yaml
import requests
import xml.etree.ElementTree as ET
from requests.exceptions import RequestException
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI
@tool
def coin_price_and_news(coin: str) -> str:
"""
Fetch cryptocurrency price, trends, and recent news in a concise format.
Args:
coin (str): Cryptocurrency identifier (e.g., "bitcoin", "ethereum").
Returns:
str: Concise summary of price, trends, and news.
"""
coin = coin.lower()
# Fetch current price
try:
price_response = requests.get(
"https://api.coingecko.com/api/v3/simple/price",
params={"ids": coin, "vs_currencies": "usd", "include_24hr_change": "true"},
timeout=10
)
price_data = price_response.json()
price = price_data.get(coin, {}).get("usd", "N/A")
day_change = price_data.get(coin, {}).get("usd_24h_change", "N/A")
# Format price and 24h change
price_display = f"${price:.2f}" if isinstance(price, (int, float)) else "N/A"
day_trend = "↓" if isinstance(day_change, (int, float)) and day_change < 0 else "↑"
day_change_display = f"{abs(day_change):.2f}%" if isinstance(day_change, (int, float)) else "N/A"
except Exception:
price_display = "N/A"
day_trend = "-"
day_change_display = "N/A"
# Fetch historical trends
try:
hist_response = requests.get(
f"https://api.coingecko.com/api/v3/coins/{coin}/market_chart",
params={"vs_currency": "usd", "days": "30", "interval": "daily"},
timeout=10
)
hist_data = hist_response.json().get('prices', [])
# Calculate week and month trends
if len(hist_data) >= 7:
week_change = ((hist_data[-1][1] - hist_data[-7][1]) / hist_data[-7][1]) * 100
week_trend = "↓" if week_change < 0 else "↑"
week_change_display = f"{abs(week_change):.2f}%"
else:
week_trend = "-"
week_change_display = "N/A"
if len(hist_data) >= 30:
month_change = ((hist_data[-1][1] - hist_data[0][1]) / hist_data[0][1]) * 100
month_trend = "↓" if month_change < 0 else "↑"
month_change_display = f"{abs(month_change):.2f}%"
else:
month_trend = "-"
month_change_display = "N/A"
except Exception:
week_trend = month_trend = "-"
week_change_display = month_change_display = "N/A"
# Fetch news
news_items = []
try:
rss = requests.get("https://cointelegraph.com/rss", timeout=10)
root = ET.fromstring(rss.content)
for item in root.findall(".//item"):
title = (item.find("title").text if item.find("title") is not None else "").strip()
link = (item.find("link").text if item.find("link") is not None else "").strip()
if coin in title.lower():
news_items.append(f"• {title[:80]}{'...' if len(title) > 80 else ''}")
if len(news_items) >= 3:
break
except Exception:
news_items = ["• Unable to fetch news"]
if not news_items:
news_items = [f"• No recent news found for {coin}"]
# Build the final output
result = f"""🪙 {coin.upper()} PRICE: {price_display}
1 day {day_trend} {day_change_display}
1 week {week_trend} {week_change_display}
1 month {month_trend} {month_change_display}
RECENT NEWS:
{news_items[0]}
{news_items[1] if len(news_items) > 1 else ""}
{news_items[2] if len(news_items) > 2 else ""}"""
return result
@tool
def get_current_time_in_timezone(timezone: str) -> str:
"""A tool that fetches the current local time in a specified timezone.
Args:
timezone: A string representing a valid timezone (e.g., 'America/New_York').
"""
try:
# Create timezone object
tz = pytz.timezone(timezone)
# Get current time in that 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}': {str(e)}"
final_answer = FinalAnswerTool()
# If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
model = HfApiModel(
max_tokens=2096,
temperature=0.5,
model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud',# it is possible that this model may be overloaded
custom_role_conversions=None,
)
# Import tool from Hub
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
with open("prompts.yaml", 'r') as stream:
prompt_templates = yaml.safe_load(stream)
agent = CodeAgent(
model=model,
tools=[final_answer, get_current_time_in_timezone, image_generation_tool, coin_price_and_news],
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name=None,
description=None,
prompt_templates=prompt_templates
)
GradioUI(agent).launch()