issuaste's picture
Update app.py
901e741 verified
raw
history blame
3.42 kB
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
import datetime
import requests
import pytz
import yaml
import os
from typing import Optional, Dict, Any, List
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI
# Timezone tools
@tool
def get_current_time_in_timezone(timezone: str) -> str:
"""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)}"
@tool
def list_available_timezones() -> str:
"""Lists all available timezone names grouped by region."""
all_timezones = pytz.all_timezones
timezone_dict = {}
for tz in all_timezones:
region = tz.split('/', 1)[0] if '/' in tz else 'Other'
if region not in timezone_dict:
timezone_dict[region] = []
timezone_dict[region].append(tz)
result = []
for region, zones in timezone_dict.items():
result.append(f"{region}: {', '.join(zones[:5])}" +
(f" and {len(zones)-5} more..." if len(zones) > 5 else ""))
return "\n".join(result)
# Weather tool
@tool
def get_weather(location: str) -> str:
"""Fetches current weather information for a specified location.
Args:
location: A string representing a city or location (e.g., 'New York').
"""
# This is a mock implementation - in a real app, you would use a weather API
# Example with OpenWeatherMap: https://openweathermap.org/api
return f"Weather information for {location}: Simulated weather data (add API key and implement actual API call)"
# Load prompt templates
try:
with open("prompts.yaml", 'r') as stream:
prompt_templates = yaml.safe_load(stream)
except Exception as e:
print(f"Error loading prompt templates: {e}")
prompt_templates = {}
# Initialize tools
final_answer = FinalAnswerTool()
# If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint
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,
)
# Load image generation tool
try:
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
except Exception as e:
print(f"Failed to load image generation tool: {e}")
image_generation_tool = None
# Setup the agent with all tools
tools = [
final_answer,
get_current_time_in_timezone,
list_available_timezones,
get_weather
]
# Conditionally add image generation if loaded successfully
if image_generation_tool:
tools.append(image_generation_tool)
# Initialize the agent
agent = CodeAgent(
model=model,
tools=tools,
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name=None,
description=None,
prompt_templates=prompt_templates
)
# Launch the Gradio UI
GradioUI(agent).launch()