adithyagv's picture
Update app.py
2967d23 verified
raw
history blame
3.19 kB
from smolagents import CodeAgent, HfApiModel, tool
from smolagents.default_tools import FinalAnswerTool
import datetime
import pytz
import yaml
import geopy
from geopy.geocoders import Nominatim
import pycountry
# Define your tools
@tool
def get_currency_from_timezone(timezone: str) -> str:
"""A tool that returns the official currency of the location specified in the timezone
Args:
timezone: A string representing a valid timezone as city. (e.g London)
"""
print(f"get_currency_from_timezone called with timezone: {timezone}") # ADD THIS LINE
try:
geolocator = Nominatim(user_agent="currency_finder")
location = geolocator.geocode(timezone)
if location:
address_parts = location.address.split(",")
country_name = address_parts[-2].strip()
try:
country = pycountry.countries.search_fuzzy(country_name)[0]
if hasattr(country, 'currencies'):
print(f"get_currency_from_timezone returning currency: {currency_info}")
return ", ".join(country.currencies) # Return currencies as a comma-separated string
else:
return f"No currency information found for {country_name}"
except LookupError:
return f"Country '{country_name}' not found."
else:
return f"Location '{timezone}' not found." # Corrected variable name
except Exception as e:
return f"An error occurred: {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').
"""
print(f"get_current_time_in_timezone called with timezone: {timezone}") # ADD THIS LINE
try:
tz = pytz.timezone(timezone)
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
print(f"get_current_time_in_timezone returning time: {local_time_str}")
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_tool = FinalAnswerTool() # Initialize FinalAnswerTool
# Model setup
model = HfApiModel(
max_tokens=2096,
temperature=0.5,
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
custom_role_conversions=None,
)
# Load prompt templates
with open("prompts.yaml", 'r') as stream:
prompt_templates = yaml.safe_load(stream)
# Initialize CodeAgent - CORRECT WAY TO USE CodeAgent
agent = CodeAgent(
model=model,
tools=[get_currency_from_timezone, get_current_time_in_timezone, final_answer_tool], # Use final_answer_tool instance
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name="TimeZoneCurrencyAgent", # Give your agent a name
description="An agent that can fetch the current time and currency for a given location.", # Add a description
prompt_templates=prompt_templates,
)
from Gradio_UI import GradioUI # Import GradioUI after agent definition
GradioUI(agent).launch()