yuvrajpant56's picture
Update app.py
dc77b94 verified
import feedparser
import urllib.parse
import yaml
from tools.final_answer import FinalAnswerTool
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import gradio as gr
from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
import nltk
import datetime
import requests
import pytz
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI
nltk.download("stopwords")
from nltk.corpus import stopwords
@tool
def convert_usd_to_eur(amount: float) -> str:
"""Converts a given amount in USD to NPR using real-time exchange rates.
Args:
amount: The amount in USD to be converted.
Returns:
A string with the converted amount in NPR.
"""
try:
# API Endpoint (Replace 'YOUR-API-KEY' with your actual key)
url = "https://v6.exchangerate-api.com/v6/a0a73cc16fef27d4a2c1fd40/latest/USD"
# Fetch data from the exchange rate API
response = requests.get(url)
data = response.json()
# Check if the API response contains the exchange rate
if "conversion_rates" not in data or "NPR" not in data["conversion_rates"]:
return "Error: Unable to fetch exchange rate."
# Extract USD to EUR exchange rate
exchange_rate = data["conversion_rates"]["NPR"]
# Convert USD to EUR
converted_amount = amount * exchange_rate
return f"{amount} USD is equivalent to {converted_amount:.2f} NPR"
except Exception as e:
return f"Error fetching exchange rate: {str(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:
# 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)}"
final_answer = FinalAnswerTool()
# AI Model
model = HfApiModel(
max_tokens=2096,
temperature=0.5,
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
custom_role_conversions=None,
)
# Import tool from Hub
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
# Load prompt templates
with open("prompts.yaml", 'r') as stream:
prompt_templates = yaml.safe_load(stream)
# Create the AI Agent
agent = CodeAgent(
model=model,
tools=[final_answer,convert_usd_to_eur], # Add your tools here
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name="CurrencyConverterAgent",
description="An AI agent that convert USD to NPR using real-time exchange rates.",
prompt_templates=prompt_templates
)
# Create Gradio UI
with gr.Blocks() as demo:
gr.Markdown("# 💱 Exchange Rate Converter")
# Textbox for user input (amount in USD)
amount_input = gr.Number(label="Enter Amount in USD", value=1, precision=2)
# Output display for the converted value
output_display = gr.Markdown()
# Button to trigger conversion
convert_button = gr.Button("🔄 Convert to NPR")
# Function call when button is clicked
convert_button.click(convert_usd_to_eur, inputs=[amount_input], outputs=[output_display])
print("DEBUG: Gradio UI is running. Waiting for user input...")
# Launch the UI
demo.launch()