File size: 6,071 Bytes
7f12056
 
 
 
 
 
8098450
9b5b26a
 
 
c19d193
8fe992b
8098450
9b5b26a
 
7f12056
 
 
 
 
9b5b26a
 
 
f87b564
 
 
 
 
9b5b26a
 
 
f87b564
9b5b26a
f87b564
8c01ffb
 
7f12056
 
 
 
 
f87b564
 
 
 
 
7f12056
962ba63
 
 
 
 
8098450
962ba63
7f12056
962ba63
7f12056
 
 
 
 
 
 
f87b564
 
 
 
 
7f12056
8098450
962ba63
8098450
 
 
7f12056
 
962ba63
7f12056
 
 
 
 
962ba63
7f12056
 
 
 
 
8098450
7f12056
 
f87b564
 
 
 
 
 
7f12056
 
f87b564
ae7a494
7f12056
 
 
 
 
 
f87b564
 
 
 
 
7f12056
962ba63
 
 
8098450
 
962ba63
7f12056
f87b564
7f12056
 
ac2e343
 
 
 
962ba63
f87b564
 
 
 
 
ac2e343
962ba63
 
f87b564
962ba63
 
f87b564
 
962ba63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f87b564
962ba63
 
 
 
 
 
 
 
 
 
ac2e343
 
962ba63
f87b564
ac2e343
962ba63
ac2e343
 
962ba63
ac2e343
 
7f12056
962ba63
7f12056
 
 
 
ae7a494
e121372
7f12056
 
65ad701
13d500a
8c01ffb
 
7f12056
962ba63
7f12056
8c01ffb
7f12056
 
 
 
 
 
 
 
962ba63
7f12056
 
 
 
861422e
7f12056
 
 
 
 
 
 
8c01ffb
8fe992b
7a47608
 
 
7f12056
 
 
ac2e343
7a47608
 
8c01ffb
 
6f0a4f1
8098450
7f12056
8fe992b
 
9b5b26a
7f12056
 
 
 
 
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
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()