Spaces:
Sleeping
Sleeping
File size: 4,690 Bytes
12c0855 04a0c3a 9b5b26a c19d193 9b5b26a 7f4931c 9b5b26a 8c01ffb 2e4d0ba 6aae614 ae7a494 e121372 12c0855 13d500a 8c01ffb 169965a 12c0855 861422e 12c0855 8c01ffb 8fe992b 12c0855 2e4d0ba 7f4931c 2e4d0ba 12c0855 8c01ffb 861422e 8fe992b 8c01ffb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 | from smolagents import (
CodeAgent,
DuckDuckGoSearchTool,
HfApiModel,
load_tool,
tool,
FinalAnswerTool,
GradioUI
)
from typing import Optional
import datetime
import requests
import pytz
import yaml
@tool
def get_travel_duration(start_location: str, destination_location: str, transportation_mode: Optional[str] = None) -> str:
"""
Get travel time between two places.
Args:
start_location: Place from which you start your drive.
destination_location: Place of arrival.
transportation_mode: Transportation mode, e.g. 'walking', 'driving', 'bicycling', 'transit','motobike'.
"""
import os
import googlemaps
from datetime import datetime
gmaps = googlemaps.Client(os.getenv("AIzaSyAFjYCOmBgyvaNNFSk1rW71hX1nWbrR6Ew"))
if transportation_mode is None:
transportation_mode = "motobike"
try:
directions_result = gmaps.directions(
start_location,
destination_location,
mode = transportation_mode,
departure_time = datetime(2026, 6, 6, 11, 0)
)
if len(directions_result) ==0:
return "No way found between these places with the required transportation mode."
return directions_result[0]['legs'][0]["duration"]["text"]
except Exception as e:
print(e)
return 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').
"""
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)}"
@tool
def get_current_weather(location: str) -> str:
"""A tool that fetches the current weather for a given city/location.
Args:
location: The name of the city or location (e.g., 'Ho Chi Minh City').
"""
try:
# Geocode
geo_response = requests.get(
f"https://geocoding-api.open-meteo.com/v1/search?name={location}&count=1"
).json()
if not geo_response.get("results"):
return f"Could not find location: {location}"
result = geo_response["results"][0]
lat, lon = result["latitude"], result["longitude"]
city_name = result["name"]
country = result.get("country", "")
# Fetch weather
weather_response = requests.get(
f"https://api.open-meteo.com/v1/forecast?"
f"latitude={lat}&longitude={lon}"
f"¤t_weather=true"
).json()
current = weather_response["current_weather"]
weather_codes = {
0: "Clear sky", 1: "Mainly clear", 2: "Partly cloudy", 3: "Overcast",
45: "Foggy", 48: "Icy fog", 51: "Light drizzle", 53: "Moderate drizzle",
61: "Slight rain", 63: "Moderate rain", 65: "Heavy rain",
71: "Slight snow", 73: "Moderate snow", 75: "Heavy snow",
80: "Slight showers", 81: "Moderate showers", 82: "Violent showers",
95: "Thunderstorm", 96: "Thunderstorm with hail",
}
description = weather_codes.get(current["weathercode"], "Unknown")
return (
f"Weather in {city_name}, {country}:\n"
f" 🌡️ Temperature : {current['temperature']}°C\n"
f" 💨 Wind Speed : {current['windspeed']} km/h\n"
f" 🧭 Wind Direction : {current['winddirection']}°\n"
f" 🌤️ Condition : {description}\n"
)
except Exception as e:
return f"Error fetching weather for '{location}': {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("m-ric/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,
image_generation_tool,
get_current_time_in_timezone,
get_current_weather, # ✅ new weather tool
get_travel_duration,
DuckDuckGoSearchTool(),
],
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name=None,
description=None,
prompt_templates=prompt_templates
)
GradioUI(agent).launch() |