Spaces:
Sleeping
Sleeping
| 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 | |
| # Below is an example of a tool that does nothing. Amaze us with your creativity ! | |
| def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type | |
| #Keep this format for the description / args / args description but feel free to modify the tool | |
| """A tool that does nothing yet | |
| Args: | |
| arg1: the first argument | |
| arg2: the second argument | |
| """ | |
| return "What magic will you build ?" | |
| 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)}" | |
| def get_weather(city: str) -> str: | |
| """Get the current weather for a given city using the Open-Meteo free API. | |
| Args: | |
| city: The city name (e.g., 'Paris'). | |
| """ | |
| import requests | |
| # Geocoding | |
| geo = requests.get(f"https://geocoding-api.open-meteo.com/v1/search?name={city}&count=1").json() | |
| if not geo.get("results"): | |
| return f"City '{city}' not found." | |
| r = geo["results"][0] | |
| lat, lon = r["latitude"], r["longitude"] | |
| url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}¤t_weather=true" | |
| data = requests.get(url).json() | |
| w = data["current_weather"] | |
| return f"Weather in {city}: {w['temperature']}°C, wind {w['windspeed']} km/h, code {w['weathercode']}" | |
| def calculator(expression: str) -> str: | |
| """Safely evaluate a mathematical expression. | |
| Args: | |
| expression: A mathematical expression string (e.g., '(12 + 5) * 3 / 7'). | |
| """ | |
| import ast, operator | |
| ops = {ast.Add: operator.add, ast.Sub: operator.sub, | |
| ast.Mult: operator.mul, ast.Div: operator.truediv, | |
| ast.Pow: operator.pow, ast.USub: operator.neg} | |
| def _eval(node): | |
| if isinstance(node, ast.Constant): return node.value | |
| elif isinstance(node, ast.BinOp): return ops[type(node.op)](_eval(node.left), _eval(node.right)) | |
| elif isinstance(node, ast.UnaryOp): return ops[type(node.op)](_eval(node.operand)) | |
| raise ValueError("Unsupported expression") | |
| try: | |
| return str(_eval(ast.parse(expression, mode='eval').body)) | |
| except Exception as e: | |
| return f"Error: {e}" | |
| def get_news_headlines(topic: str) -> str: | |
| """Fetch the latest news headlines from Google News RSS for a given topic. | |
| Args: | |
| topic: The topic to search for (e.g., 'artificial intelligence'). | |
| """ | |
| import requests | |
| url = f"https://news.google.com/rss/search?q={topic.replace(' ', '+')}&hl=fr&gl=FR&ceid=FR:fr" | |
| r = requests.get(url) | |
| titles = [] | |
| for line in r.text.split("<title>")[2:7]: # skip first 2 which are feed metadata | |
| titles.append(line.split("</title>")[0]) | |
| return "\n".join(f"• {t}" for t in titles) if titles else "No results found." | |
| def wikipedia_summary(query: str) -> str: | |
| """Get a short Wikipedia summary for a given topic. | |
| Args: | |
| query: The topic to search for on Wikipedia. | |
| """ | |
| import requests | |
| url = "https://fr.wikipedia.org/api/rest_v1/page/summary/" + query.replace(" ", "_") | |
| r = requests.get(url).json() | |
| return r.get("extract", "No Wikipedia article found for this topic.") | |
| def date_calculator(days_offset: int) -> str: | |
| """Calculate a date relative to today (positive = future, negative = past). | |
| Args: | |
| days_offset: Number of days from today (e.g., 30 for one month ahead, -7 for last week). | |
| """ | |
| from datetime import datetime, timedelta | |
| target = datetime.now() + timedelta(days=days_offset) | |
| return f"Date ({days_offset:+d} days from today): {target.strftime('%A %d %B %Y')}" | |
| def fetch_webpage_text(url: str) -> str: | |
| """Fetch and return the visible text content from a webpage URL. | |
| Args: | |
| url: The full URL of the webpage to fetch (e.g., 'https://example.com'). | |
| """ | |
| import requests, re | |
| try: | |
| r = requests.get(url, timeout=10, headers={"User-Agent": "Mozilla/5.0"}) | |
| text = re.sub(r"<[^>]+>", " ", r.text) | |
| text = re.sub(r"\s+", " ", text).strip() | |
| return text[:2000] + "..." if len(text) > 2000 else text | |
| except Exception as e: | |
| return f"Error fetching URL: {e}" | |
| def convert_currency(amount: float, from_currency: str, to_currency: str) -> str: | |
| """Convert an amount from one currency to another using live exchange rates. | |
| Args: | |
| amount: The amount to convert. | |
| from_currency: The source currency code (e.g., 'EUR'). | |
| to_currency: The target currency code (e.g., 'USD'). | |
| """ | |
| import requests | |
| url = f"https://api.exchangerate-api.com/v4/latest/{from_currency.upper()}" | |
| r = requests.get(url).json() | |
| rate = r.get("rates", {}).get(to_currency.upper()) | |
| if not rate: | |
| return f"Currency '{to_currency}' not found." | |
| return f"{amount} {from_currency.upper()} = {round(amount * rate, 2)} {to_currency.upper()}" | |
| 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='Qwen/Qwen2.5-Coder-32B-Instruct',# 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, | |
| DuckDuckGoSearchTool(), | |
| get_weather, | |
| calculator, | |
| get_news_headlines, | |
| wikipedia_summary, | |
| date_calculator, | |
| fetch_webpage_text, | |
| convert_currency,], ## add your tools here (don't remove final answer) | |
| max_steps=6, | |
| verbosity_level=1, | |
| grammar=None, | |
| planning_interval=None, | |
| name=None, | |
| description=None, | |
| prompt_templates=prompt_templates | |
| ) | |
| GradioUI(agent).launch() |