File size: 7,248 Bytes
2d71051
9b5b26a
 
 
c19d193
ade4f52
 
6aae614
9b5b26a
 
ade4f52
 
 
9b5b26a
 
 
ade4f52
 
 
9b5b26a
ade4f52
9b5b26a
 
 
 
ade4f52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b5b26a
ade4f52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c01ffb
ade4f52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c01ffb
6aae614
ae7a494
ade4f52
 
 
ae7a494
2d71051
 
ade4f52
 
13d500a
8c01ffb
ade4f52
 
 
8c01ffb
ade4f52
 
 
 
 
 
8c01ffb
ade4f52
 
 
 
8c01ffb
8fe992b
ade4f52
 
 
 
 
 
 
 
 
 
 
 
 
 
8c01ffb
 
1dc6845
3cdc5d6
8fe992b
 
9b5b26a
ade4f52
 
 
 
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel, load_tool, tool
import datetime
import requests
import pytz
import yaml
import wikipedia
import io
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI

# ---------------------------------------------------
# TIME TOOL
# ---------------------------------------------------

@tool
def get_current_time_in_timezone(timezone: str) -> str:
    """
    Fetch current time in a given timezone.

    Args:
        timezone: Timezone like 'Asia/Kolkata', 'America/New_York'
    """
    try:
        tz = pytz.timezone(timezone)
        local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
        return f"Current time in {timezone}: {local_time}"
    except Exception as e:
        return f"Error: {str(e)}"


# ---------------------------------------------------
# WEATHER TOOL
# ---------------------------------------------------

@tool
def get_weather(city: str) -> str:
    """
    Get current weather of a city.

    Args:
        city: City name
    """
    try:
        geo_url = f"https://geocoding-api.open-meteo.com/v1/search?name={city}&count=1"
        geo = requests.get(geo_url).json()

        if "results" not in geo:
            return f"City {city} not found."

        lat = geo["results"][0]["latitude"]
        lon = geo["results"][0]["longitude"]

        weather_url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}&current_weather=true"
        weather = requests.get(weather_url).json()

        temp = weather["current_weather"]["temperature"]
        wind = weather["current_weather"]["windspeed"]

        return f"Weather in {city}: {temp}°C, wind speed {wind} km/h"

    except Exception as e:
        return f"Weather lookup failed: {str(e)}"


# ---------------------------------------------------
# CALCULATOR TOOL
# ---------------------------------------------------

@tool
def calculator(expression: str) -> str:
    """
    Evaluate a mathematical expression.

    Args:
        expression: Example "25*4+10"
    """
    try:
        result = eval(expression, {"__builtins__": {}})
        return str(result)
    except Exception as e:
        return f"Calculation error: {str(e)}"


# ---------------------------------------------------
# FETCH WEBPAGE TOOL
# ---------------------------------------------------

@tool
def fetch_webpage(url: str) -> str:
    """
    Fetch webpage content.

    Args:
        url: Website URL
    """
    try:
        response = requests.get(url, timeout=10)
        return response.text[:2000]
    except Exception as e:
        return f"Failed fetching webpage: {str(e)}"


# ---------------------------------------------------
# CRYPTO PRICE TOOL
# ---------------------------------------------------

@tool
def get_crypto_price(symbol: str) -> str:
    """
    Get cryptocurrency price.

    Args:
        symbol: Crypto symbol like BTC, ETH
    """
    try:
        url = f"https://api.coingecko.com/api/v3/simple/price?ids={symbol.lower()}&vs_currencies=usd"
        data = requests.get(url).json()

        if symbol.lower() not in data:
            return "Crypto not found."

        price = data[symbol.lower()]["usd"]
        return f"{symbol.upper()} price: ${price}"

    except Exception as e:
        return f"Crypto lookup failed: {str(e)}"


# ---------------------------------------------------
# NEWS TOOL
# ---------------------------------------------------

@tool
def get_news(topic: str) -> str:
    """
    Get latest news about a topic.

    Args:
        topic: News topic
    """
    try:
        url = f"https://newsapi.org/v2/everything?q={topic}&pageSize=5&apiKey=demo"
        data = requests.get(url).json()

        articles = data.get("articles", [])
        if not articles:
            return "No news found."

        result = ""
        for a in articles[:5]:
            result += f"{a['title']} - {a['source']['name']}\n"

        return result

    except Exception as e:
        return f"News lookup failed: {str(e)}"


# ---------------------------------------------------
# WIKIPEDIA TOOL
# ---------------------------------------------------

@tool
def wikipedia_search(query: str) -> str:
    """
    Search Wikipedia and return summary.

    Args:
        query: Topic to search
    """
    try:
        summary = wikipedia.summary(query, sentences=5)
        return summary
    except Exception as e:
        return f"Wikipedia search failed: {str(e)}"


# ---------------------------------------------------
# YOUTUBE SEARCH TOOL
# ---------------------------------------------------

@tool
def youtube_search(query: str) -> str:
    """
    Search YouTube videos.

    Args:
        query: Video topic
    """
    try:
        url = f"https://ytsearch.vercel.app/api?q={query}"
        data = requests.get(url).json()

        videos = data.get("videos", [])[:5]

        results = ""
        for v in videos:
            results += f"{v['title']} - {v['url']}\n"

        return results

    except Exception as e:
        return f"YouTube search failed: {str(e)}"


# ---------------------------------------------------
# PDF READER TOOL
# ---------------------------------------------------

@tool
def read_pdf_from_url(url: str) -> str:
    """
    Read text from a PDF file.

    Args:
        url: Direct PDF URL
    """
    try:
        import PyPDF2

        response = requests.get(url)
        file = io.BytesIO(response.content)

        reader = PyPDF2.PdfReader(file)

        text = ""
        for page in reader.pages[:3]:
            text += page.extract_text()

        return text[:2000]

    except Exception as e:
        return f"PDF reading failed: {str(e)}"


# ---------------------------------------------------
# LOAD FINAL ANSWER TOOL
# ---------------------------------------------------

final_answer = FinalAnswerTool()

# ---------------------------------------------------
# MODEL
# ---------------------------------------------------

model = InferenceClientModel(
    model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
    max_tokens=2096,
    temperature=0.5,
)

# ---------------------------------------------------
# LOAD HUB TOOL
# ---------------------------------------------------

image_generation_tool = load_tool(
    "agents-course/text-to-image",
    trust_remote_code=True
)

search_tool = DuckDuckGoSearchTool()

# ---------------------------------------------------
# CREATE AGENT
# ---------------------------------------------------

agent = CodeAgent(
    model=model,
    tools=[
        final_answer,
        search_tool,
        image_generation_tool,
        get_current_time_in_timezone,
        get_weather,
        calculator,
        fetch_webpage,
        get_crypto_price,
        get_news,
        wikipedia_search,
        youtube_search,
        read_pdf_from_url
    ],
    max_steps=6,
    verbosity_level=1,
    name="SmartAIAgent",
    description="An AI agent capable of search, weather lookup, crypto prices, calculations, reading PDFs, generating images, and web browsing."
)


# ---------------------------------------------------
# GRADIO UI
# ---------------------------------------------------

GradioUI(agent).launch()