File size: 5,490 Bytes
9b5b26a
 
 
 
c19d193
fb37c7c
 
 
6aae614
9b5b26a
 
78b2a16
 
 
9f3bf44
5dbc6a2
9f3bf44
 
c5bee10
9f3bf44
 
5dbc6a2
9f3bf44
78b2a16
fb37c7c
c5bee10
78b2a16
c5bee10
fb37c7c
c5bee10
fb37c7c
 
c5bee10
 
 
fb37c7c
c5bee10
 
 
 
 
 
 
 
0284e3f
c5bee10
0284e3f
c5bee10
0284e3f
c5bee10
0284e3f
 
c5bee10
fb37c7c
c5bee10
 
 
 
 
 
 
 
0284e3f
c5bee10
 
 
 
0284e3f
c5bee10
 
 
 
 
0284e3f
5dbc6a2
c5bee10
fb37c7c
 
78b2a16
fb37c7c
78b2a16
c5bee10
 
fb37c7c
c5bee10
5dbc6a2
c5bee10
fb37c7c
c5bee10
5dbc6a2
c5bee10
 
5dbc6a2
fb37c7c
5dbc6a2
c5bee10
 
 
 
9f3bf44
c5bee10
5dbc6a2
 
 
c5bee10
 
9b5b26a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c01ffb
 
6aae614
ae7a494
 
 
 
e121372
bf6d34c
 
61aaaf7
fe328e0
13d500a
8c01ffb
 
9b5b26a
 
8c01ffb
861422e
 
9b5b26a
8c01ffb
8fe992b
9079def
8c01ffb
 
 
 
 
 
861422e
8fe992b
 
9b5b26a
8c01ffb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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()