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}¤t_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()