from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool import datetime import requests import pytz import yaml from tools.final_answer import FinalAnswerTool from Gradio_UI import GradioUI @tool def fetch_webpage(url: str) -> str: """Fetches the content of a webpage and returns clean text (first 3000 chars). Useful to read articles, company pages, or any URL after a web search. Args: url: The full URL to fetch (e.g., 'https://www.anthropic.com/news'). """ try: headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36" } response = requests.get(url, headers=headers, timeout=15) response.raise_for_status() # Extraction texte basique sans BeautifulSoup pour éviter dépendance import re text = re.sub(r'', '', response.text, flags=re.DOTALL) text = re.sub(r'', '', text, flags=re.DOTALL) text = re.sub(r'<[^>]+>', ' ', text) text = re.sub(r'\s+', ' ', text).strip() return text[:3000] except Exception as e: return f"Error fetching {url}: {str(e)}" @tool def convert_currency(amount: float, from_currency: str, to_currency: str) -> str: """Converts an amount from one currency to another using current exchange rates. Args: amount: The amount of money to convert (e.g., 1500.0). from_currency: Source currency 3-letter code (e.g., 'USD', 'EUR', 'GBP'). to_currency: Target currency 3-letter code (e.g., 'USD', 'EUR', 'GBP'). """ try: url = f"https://api.exchangerate-api.com/v4/latest/{from_currency.upper()}" response = requests.get(url, timeout=10) data = response.json() rate = data["rates"][to_currency.upper()] converted = amount * rate return f"{amount} {from_currency.upper()} = {converted:.2f} {to_currency.upper()} (rate: {rate:.4f})" except Exception as e: return f"Error converting currency: {str(e)}" @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', 'Europe/Paris'). """ 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}': {str(e)}" final_answer = FinalAnswerTool() model = HfApiModel( max_tokens=2096, temperature=0.5, model_id='Qwen/Qwen2.5-Coder-32B-Instruct', custom_role_conversions=None, ) 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, DuckDuckGoSearchTool(), fetch_webpage, image_generation_tool, get_current_time_in_timezone, convert_currency, ], max_steps=6, verbosity_level=1, grammar=None, planning_interval=None, name=None, description=None, prompt_templates=prompt_templates ) GradioUI(agent).launch()