MallikarjunSonna's picture
Update app.py
31f8d29 verified
raw
history blame
4.42 kB
import datetime
import requests
import pytz
import yaml
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI
# 1. Tool: Get Current Time in Any Timezone
@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:
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)}"
# 2. Tool: Get Current Weather Data (Requires OpenWeatherMap API)
@tool
def get_weather(city: str) -> str:
"""Fetches current weather information for a specified city.
Args:
city: The name of the city (e.g., 'New York').
"""
api_key = "YOUR_OPENWEATHER_API_KEY" # Replace with your OpenWeather API key
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
try:
response = requests.get(url).json()
if response["cod"] != 200:
return f"Error: {response['message']}"
temp = response["main"]["temp"]
weather_desc = response["weather"][0]["description"]
return f"The current weather in {city} is {weather_desc} with a temperature of {temp}°C."
except Exception as e:
return f"Error fetching weather data: {str(e)}"
# 3. Tool: Currency Exchange Converter
@tool
def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
"""Converts currency from one type to another using real-time exchange rates.
Args:
amount: The amount to convert.
from_currency: The source currency code (e.g., 'USD').
to_currency: The target currency code (e.g., 'INR').
"""
api_key = "YOUR_EXCHANGERATE_API_KEY" # Replace with a valid API key from ExchangeRate API
url = f"https://v6.exchangerate-api.com/v6/{api_key}/latest/{from_currency}"
try:
response = requests.get(url).json()
if "conversion_rates" not in response:
return f"Error: Unable to fetch exchange rates."
rate = response["conversion_rates"].get(to_currency, None)
if rate is None:
return f"Error: Unsupported currency code."
converted_amount = round(amount * rate, 2)
return f"{amount} {from_currency} is equal to {converted_amount} {to_currency}."
except Exception as e:
return f"Error fetching exchange rates: {str(e)}"
@tool
def interaction_tool(user_input: str) -> str:
"""A tool that allows the agent to respond to basic user interactions.
Args:
user_input: The user's message.
"""
responses = {
"hi": "Hello! I'm an AI Agent here to assist you.",
"hello": "Hey there! How can I help?",
"how are you": "I'm just a virtual agent, but I'm always ready to assist!",
"what can you do": "I can generate images, search the web, check time zones, and much more!",
"what are you doing": "I'm here, waiting for your instructions to assist you."
}
return responses.get(user_input.lower(), "I'm not sure, but I'm here to help!")
# Load Hugging Face Text-to-Image Tool
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
# Load Final Answer Tool
final_answer = FinalAnswerTool()
# Initialize Model
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)
# Create Agent with Additional Tools
agent = CodeAgent(
model=model,
tools=[
final_answer,
get_current_time_in_timezone,
get_weather,
convert_currency,
DuckDuckGoSearchTool(),
Interaction_tool,
image_generation_tool,
],
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name=None,
description=None,
prompt_templates=prompt_templates,
)
# Launch Gradio UI
GradioUI(agent).launch()