Spaces:
Running
Running
Download app.py from ApeMaster/First_agent_template: direct link, hf CLI and curl.
- Browser
- Download file 6 kB
-
https://huggingface.co/spaces/ApeMaster/First_agent_template/resolve/main/app.py
- Command line
-
hf download hf://spaces/ApeMaster/First_agent_template/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ApeMaster/First_agent_template/resolve/main/app.py
6 kB
| from smolagents import ( | |
| CodeAgent, | |
| DuckDuckGoSearchTool, | |
| VisitWebpageTool, | |
| HfApiModel, | |
| load_tool, | |
| tool, | |
| ) | |
| import datetime | |
| import requests | |
| import pytz | |
| import yaml | |
| from tools.final_answer import FinalAnswerTool | |
| from Gradio_UI import GradioUI | |
| # --------------------------------------------------------------------------- | |
| # Custom tool 1: Real-time weather (Open-Meteo — free, no API key required) | |
| # --------------------------------------------------------------------------- | |
| def get_weather(city: str) -> str: | |
| """Get the current weather for a given city. | |
| Args: | |
| city: the name of the city (e.g. 'Paris', 'New York'). | |
| """ | |
| try: | |
| # 1) Geocode the city name into lat/lon | |
| geo = requests.get( | |
| "https://geocoding-api.open-meteo.com/v1/search", | |
| params={"name": city, "count": 1, "language": "en", "format": "json"}, | |
| timeout=15, | |
| ).json() | |
| if not geo.get("results"): | |
| return f"Could not find a city named '{city}'." | |
| loc = geo["results"][0] | |
| lat, lon = loc["latitude"], loc["longitude"] | |
| # 2) Fetch current weather at that location | |
| weather = requests.get( | |
| "https://api.open-meteo.com/v1/forecast", | |
| params={ | |
| "latitude": lat, | |
| "longitude": lon, | |
| "current_weather": "true", | |
| "timezone": "auto", | |
| }, | |
| timeout=15, | |
| ).json() | |
| cur = weather.get("current_weather", {}) | |
| temp_c = cur.get("temperature") | |
| windspeed = cur.get("windspeed") | |
| wmo = cur.get("weathercode", 0) | |
| # Map WMO weather codes to readable descriptions | |
| descriptions = { | |
| 0: "clear sky", 1: "mainly clear", 2: "partly cloudy", 3: "overcast", | |
| 45: "fog", 48: "depositing rime fog", | |
| 51: "light drizzle", 53: "moderate drizzle", 55: "dense drizzle", | |
| 61: "slight rain", 63: "moderate rain", 65: "heavy rain", | |
| 71: "slight snow", 73: "moderate snow", 75: "heavy snow", | |
| 80: "slight rain showers", 81: "moderate rain showers", 82: "violent rain showers", | |
| 95: "thunderstorm", 96: "thunderstorm with slight hail", 99: "thunderstorm with heavy hail", | |
| } | |
| desc = descriptions.get(wmo, "unknown conditions") | |
| return ( | |
| f"Current weather in {loc['name']}: {desc}, " | |
| f"{temp_c}°C, wind {windspeed} km/h." | |
| ) | |
| except Exception as e: | |
| return f"Error fetching weather for '{city}': {str(e)}" | |
| # --------------------------------------------------------------------------- | |
| # Custom tool 2: Currency converter (free exchange-rate API, no key needed) | |
| # --------------------------------------------------------------------------- | |
| def convert_currency(amount: float, from_currency: str, to_currency: str) -> str: | |
| """Convert an amount from one currency to another. | |
| Args: | |
| amount: the amount of money to convert. | |
| from_currency: the source currency code (e.g. 'USD'). | |
| to_currency: the target currency code (e.g. 'EUR'). | |
| """ | |
| try: | |
| rates = requests.get( | |
| "https://open.er-api.com/v6/latest", | |
| params={"base": from_currency.upper()}, | |
| timeout=15, | |
| ).json() | |
| if rates.get("result") != "success": | |
| return f"Could not fetch rates for '{from_currency}'." | |
| rate = rates["rates"].get(to_currency.upper()) | |
| if rate is None: | |
| return f"Unknown currency code '{to_currency}'." | |
| converted = amount * rate | |
| return ( | |
| f"{amount} {from_currency.upper()} = {converted:.2f} " | |
| f"{to_currency.upper()} (rate {rate:.4f})" | |
| ) | |
| except Exception as e: | |
| return f"Error converting currency: {str(e)}" | |
| # --------------------------------------------------------------------------- | |
| # Existing tools | |
| # --------------------------------------------------------------------------- | |
| 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: | |
| 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() | |
| # 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, # don't remove | |
| DuckDuckGoSearchTool(), # web search (was imported but never added!) | |
| VisitWebpageTool(), # read the pages the search finds | |
| image_generation_tool, # text-to-image (was loaded but never added!) | |
| get_current_time_in_timezone, # current local time in any timezone | |
| get_weather, # real-time weather by city | |
| convert_currency, # currency conversion | |
| ], | |
| max_steps=6, | |
| verbosity_level=1, | |
| grammar=None, | |
| planning_interval=None, | |
| name=None, | |
| description=None, | |
| prompt_templates=prompt_templates, | |
| ) | |
| GradioUI(agent).launch() | |