Spaces:
Sleeping
Sleeping
| from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool | |
| import datetime | |
| import requests | |
| import pytz | |
| import yaml | |
| import json | |
| from tools.final_answer import FinalAnswerTool | |
| from tools.visit_webpage import VisitWebpageTool | |
| from tools.web_search import DuckDuckGoSearchTool as WebSearchTool | |
| from Gradio_UI import GradioUI | |
| def get_wikipedia_summary(topic: str) -> str: | |
| """Fetches a short summary from Wikipedia for a given topic. | |
| Args: | |
| topic: The topic to search for on Wikipedia (e.g., 'Python programming language'). | |
| """ | |
| try: | |
| url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + topic.replace(" ", "_") | |
| response = requests.get(url, timeout=15) | |
| if response.status_code == 200: | |
| data = response.json() | |
| title = data.get("title", topic) | |
| extract = data.get("extract", "No summary available.") | |
| page_url = data.get("content_urls", {}).get("desktop", {}).get("page", "") | |
| return f"**{title}**\n\n{extract}\n\nRead more: {page_url}" | |
| elif response.status_code == 404: | |
| return f"No Wikipedia article found for '{topic}'. Try a different search term." | |
| else: | |
| return f"Error fetching Wikipedia summary (HTTP {response.status_code})." | |
| except Exception as e: | |
| return f"Error fetching Wikipedia summary for '{topic}': {str(e)}" | |
| def get_random_fun_fact() -> str: | |
| """Fetches a random fun/useless fact from the uselessfacts API. No arguments needed. | |
| """ | |
| try: | |
| response = requests.get("https://uselessfacts.jsph.pl/api/v2/facts/random", timeout=10) | |
| if response.status_code == 200: | |
| data = response.json() | |
| return f"🎲 Fun fact: {data.get('text', 'No fact available.')}" | |
| return "Could not fetch a fun fact right now. Try again later." | |
| except Exception as e: | |
| return f"Error fetching fun fact: {str(e)}" | |
| def convert_units(value: float, from_unit: str, to_unit: str) -> str: | |
| """Converts a numeric value between common units of measurement. | |
| Supports length (km, miles, m, ft, in, cm), weight (kg, lbs, g, oz), | |
| and temperature (celsius, fahrenheit, kelvin). | |
| Args: | |
| value: The numeric value to convert. | |
| from_unit: The unit to convert from (e.g., 'km', 'lbs', 'celsius'). | |
| to_unit: The unit to convert to (e.g., 'miles', 'kg', 'fahrenheit'). | |
| """ | |
| conversions_to_base = { | |
| # Length → meters | |
| "km": ("length", lambda v: v * 1000), | |
| "m": ("length", lambda v: v), | |
| "cm": ("length", lambda v: v / 100), | |
| "miles": ("length", lambda v: v * 1609.344), | |
| "ft": ("length", lambda v: v * 0.3048), | |
| "in": ("length", lambda v: v * 0.0254), | |
| # Weight → grams | |
| "kg": ("weight", lambda v: v * 1000), | |
| "g": ("weight", lambda v: v), | |
| "lbs": ("weight", lambda v: v * 453.592), | |
| "oz": ("weight", lambda v: v * 28.3495), | |
| # Temperature → celsius | |
| "celsius": ("temp", lambda v: v), | |
| "fahrenheit": ("temp", lambda v: (v - 32) * 5 / 9), | |
| "kelvin": ("temp", lambda v: v - 273.15), | |
| } | |
| conversions_from_base = { | |
| "km": lambda v: v / 1000, "m": lambda v: v, "cm": lambda v: v * 100, | |
| "miles": lambda v: v / 1609.344, "ft": lambda v: v / 0.3048, "in": lambda v: v / 0.0254, | |
| "kg": lambda v: v / 1000, "g": lambda v: v, "lbs": lambda v: v / 453.592, "oz": lambda v: v / 28.3495, | |
| "celsius": lambda v: v, "fahrenheit": lambda v: v * 9 / 5 + 32, "kelvin": lambda v: v + 273.15, | |
| } | |
| fu = from_unit.lower().strip() | |
| tu = to_unit.lower().strip() | |
| if fu not in conversions_to_base or tu not in conversions_from_base: | |
| return f"Unsupported unit(s): '{from_unit}' or '{to_unit}'. Supported: {list(conversions_to_base.keys())}" | |
| cat_from, to_base = conversions_to_base[fu] | |
| cat_to, _ = conversions_to_base[tu] | |
| if cat_from != cat_to: | |
| return f"Cannot convert between '{from_unit}' ({cat_from}) and '{to_unit}' ({cat_to}). Units must be in the same category." | |
| base_value = to_base(value) | |
| result = conversions_from_base[tu](base_value) | |
| return f"{value} {from_unit} = {result:.4f} {to_unit}" | |
| 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)}" | |
| final_answer = FinalAnswerTool() | |
| web_search = WebSearchTool() | |
| visit_webpage = VisitWebpageTool() | |
| # 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, | |
| web_search, | |
| visit_webpage, | |
| get_current_time_in_timezone, | |
| get_wikipedia_summary, | |
| get_random_fun_fact, | |
| convert_units, | |
| image_generation_tool, | |
| ], | |
| max_steps=6, | |
| verbosity_level=1, | |
| grammar=None, | |
| planning_interval=None, | |
| name=None, | |
| description=None, | |
| prompt_templates=prompt_templates | |
| ) | |
| GradioUI(agent).launch() |