Spaces:
Sleeping
Sleeping
| # 1🌟 Importing Libraries | |
| # What does this section do? It imports the necessary Python libraries and Agent tools to give the agent functionalities. | |
| from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool | |
| import datetime | |
| import requests | |
| import pytz | |
| import yaml | |
| from typing import Dict | |
| from tools.final_answer import FinalAnswerTool | |
| from Gradio_UI import GradioUI | |
| import os | |
| from huggingface_hub import InferenceClient | |
| """ | |
| Breakdown of Key Imports: | |
| smolagents – The core AI agent framework. | |
| CodeAgent → The agent that can run Python code as actions. | |
| DuckDuckGoSearchTool → Enables web searching. | |
| HfApiModel → The language model (LLM) for reasoning. | |
| load_tool → Allows importing tools from Hugging Face Hub. | |
| tool → A decorator for defining tools. | |
| Utility Libraries: | |
| datetime, requests, pytz → Work with dates, HTTP requests, and time zones. | |
| yaml → Reads prompt configurations. | |
| FinalAnswerTool – A built-in tool that lets the agent provide a final answer. | |
| """ | |
| # 2🌟 Defining Custom Tools | |
| # Tools allow the agent to interact with its environment (e.g., checking time, fetching images, etc.). | |
| # ✅ Nicaragua Weather Tool | |
| import os | |
| import requests | |
| from typing import Dict | |
| def get_nicaragua_weather(city: str = "Managua") -> str: | |
| """Gets current weather information for a city in Nicaragua. | |
| Args: | |
| city: The name of the Nicaraguan city to check weather for. | |
| Valid options are: Managua, León, Granada, Matagalpa, and Bluefields. | |
| If invalid city provided, defaults to Managua. | |
| Returns: | |
| str: Current weather conditions including temperature, description, humidity and wind speed. | |
| """ | |
| # API Configuration | |
| API_KEY = os.getenv("WEATHER_API_KEY") | |
| if not API_KEY: | |
| return "Error: API key is missing. Please add WEATHER_API_KEY in Hugging Face Secrets." | |
| # Valid cities and their coordinates | |
| VALID_CITIES = { | |
| "Managua": "12.1328,-86.2504", | |
| "León": "12.4375,-86.8833", | |
| "Granada": "11.9313,-85.9595", | |
| "Matagalpa": "12.9167,-85.9167", | |
| "Bluefields": "12.0137,-83.7647" | |
| } | |
| # Validate city (case-insensitive) | |
| valid_city = next( | |
| (c for c in VALID_CITIES if c.lower() == city.lower().strip()), | |
| "Managua" | |
| ) | |
| try: | |
| # Make API request | |
| url = f"http://api.weatherapi.com/v1/current.json?key={API_KEY}&q={VALID_CITIES[valid_city]}&lang=es" | |
| response = requests.get(url, timeout=10) | |
| response.raise_for_status() | |
| data = response.json() | |
| # Extract weather data | |
| current = data["current"] | |
| weather = { | |
| "description": current["condition"]["text"], | |
| "temp": current["temp_c"], | |
| "humidity": current["humidity"], | |
| "wind_speed": current["wind_kph"] | |
| } | |
| # Format response | |
| prefix = f"Using Managua instead of {city}. " if valid_city != city else "" | |
| return (f"{prefix}{weather['description']}, " | |
| f"{weather['temp']}°C, humidity: {weather['humidity']}%, " | |
| f"wind speed: {weather['wind_speed']} km/h.") | |
| except requests.Timeout: | |
| return f"Error: Request timed out for {city}" | |
| except requests.RequestException as e: | |
| return f"Error: Network error for {city}: {str(e)}" | |
| except KeyError as e: | |
| return f"Error: Invalid API response: {str(e)}" | |
| except Exception as e: | |
| return f"Error: Unexpected error: {str(e)}" | |
| # ✅ Nicaragua Biodiversity Facts | |
| def biodiversity_fact() -> str: | |
| """Provides a random fact about biodiversity and forests in Nicaragua.""" | |
| facts = [ | |
| "Nicaragua is home to the Bosawás Biosphere Reserve, one of the largest tropical rainforests in Central America.", | |
| "The country has over 7,000 plant species and 250 mammal species.", | |
| "Lake Nicaragua is the only freshwater lake in the world that has sharks—the famous Nicaragua Bull Shark!", | |
| "The Mombacho Volcano Cloud Forest hosts a rich variety of endemic species, including the Mombacho Salamander.", | |
| "More than 90% of Nicaragua's forests are protected reserves, ensuring biodiversity conservation." | |
| ] | |
| import random | |
| return random.choice(facts) | |
| # ✅ Nicaragua Volcano Information Tool | |
| def nicaragua_volcanoes(volcano: str) -> str: | |
| """ | |
| Provides information about a volcano in Nicaragua. | |
| Args: | |
| volcano: The name of a volcano in Nicaragua (e.g., 'Momotombo', 'Masaya', 'Mombacho'). | |
| Returns: | |
| A brief description of the volcano. | |
| """ | |
| volcano_data = { | |
| "Momotombo": "Momotombo is an active stratovolcano near Lake Managua, known for its conical shape and eruptions.", | |
| "Masaya": "Masaya is one of the most active volcanoes in Nicaragua, famous for its 'Lava Lake'.", | |
| "Mombacho": "Mombacho is a dormant volcano with a cloud forest and rich biodiversity, located near Granada.", | |
| "Concepción": "Concepción is a symmetrical stratovolcano on Ometepe Island, offering challenging hikes.", | |
| "San Cristóbal": "San Cristóbal is Nicaragua’s highest volcano, frequently emitting gas and ash." | |
| } | |
| return volcano_data.get(volcano, "Sorry, I don't have information on that volcano.") | |
| # 3🌟 Building the AI Agent | |
| final_answer = FinalAnswerTool() | |
| HF_TOKEN = os.getenv("HF_TOKEN") | |
| if HF_TOKEN is None: | |
| raise ValueError("Hugging Face API token is missing. Please set it in Hugging Face Spaces Secrets.") | |
| model = HfApiModel( | |
| max_tokens=2096, | |
| temperature=0.5, | |
| model_id="Qwen/Qwen2.5-Coder-32B-Instruct", | |
| token=HF_TOKEN, | |
| 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_nicaragua_weather, | |
| biodiversity_fact, | |
| nicaragua_volcanoes | |
| ], | |
| max_steps=6, | |
| verbosity_level=1, | |
| grammar=None, | |
| planning_interval=None, | |
| name=None, | |
| description=None, | |
| prompt_templates=prompt_templates | |
| ) | |
| # 4🌟 Launching the Agent UI | |
| GradioUI(agent).launch() | |