harshera's picture
Update app.py
b940b05 verified
from smolagents import CodeAgent,DuckDuckGoSearchTool, InferenceClientModel,load_tool,tool
import datetime
import requests
import pytz
import yaml
from tools.final_answer import FinalAnswerTool
import csv
#from jobspy import scrape_jobs
from Gradio_UI import GradioUI
# Below is an example of a tool that does nothing. Amaze us with your creativity !
@tool
def finance_management_plan(budget: float, habits: str, goal: str, period: str) -> str:
"""A tool that gives a plan to optimize personal budget and spending based on habits and financial goals.
Args:
budget: A float representing the current budget (e.g., '100.000').
habits: The expense habits each day of the week (e.g., 'Monday: $50, Tuesday: $30, ...').
goal: Financial goals to achieve (e.g., 'Save $500 for a vacation').
period: The time period in which the user wants a plan to achieve the goal (e.g., 'week', 'month').
Returns:
str: A personalized plan to optimize the budget and achieve the financial goal.
"""
# Parse habits into a dictionary
habits_dict = {}
for day in habits.split(','):
day, amount = day.strip().split(':')
habits_dict[day.strip()] = float(amount.strip().replace('$', ''))
# Calculate total weekly spending based on habits
total_weekly_spending = sum(habits_dict.values())
# Determine the total budget for the specified period
if period.lower() == 'week':
total_budget = budget
elif period.lower() == 'month':
total_budget = budget * 4 # Assuming 4 weeks in a month
else:
return "Invalid period. Please specify 'week' or 'month'."
# Calculate savings needed to achieve the goal
goal_amount = float(''.join(filter(str.isdigit, goal))) # Extract numeric value from goal string
savings_needed = goal_amount - (total_budget - total_weekly_spending)
# Generate a plan
if savings_needed <= 0:
return f"Your current budget and spending habits already allow you to achieve your goal of {goal} within the {period}."
else:
# Suggest reducing daily expenses
daily_savings = savings_needed / 7 # Spread savings over 7 days
new_habits = {day: max(0, amount - daily_savings) for day, amount in habits_dict.items()}
# Format the new habits into a readable string
new_habits_str = ', '.join([f"{day}: ${amount:.2f}" for day, amount in new_habits.items()])
return (
f"To achieve your goal of {goal} within the {period}, you need to save an additional ${savings_needed:.2f}.\n"
f"Consider adjusting your daily spending habits as follows:\n"
f"{new_habits_str}\n"
f"This will help you stay on track with your financial goals."
)
print(finance_management_plan(1000.0, "Monday: $50, Tuesday: $30, Wednesday: $40, Thursday: $20, Friday: $60, Saturday: $80, Sunday: $70", "Save $500 for a vacation", "month"))
# @tool
# def webscraping_jobs(search_term: str, location: str, results_wanted: int = 20, hours_old: int = 72, country_indeed: str = 'USA') -> str:
# """
# A tool that scrapes job listings from multiple websites based on jobspy library.
# Args:
# search_term (str): The job title or keywords to search for (e.g., 'software engineer').
# location (str): The location to search for jobs (e.g., 'San Francisco, CA').
# results_wanted (int, optional): Number of results to retrieve (default is 20).
# hours_old (int, optional): Maximum age of job postings in hours (default is 72).
# country_indeed (str, optional): Country filter for Indeed searches (default is 'USA').
# Returns:
# str: A message with the number of jobs found and saves results to 'jobs.csv'.
# """
# jobs = scrape_jobs(
# site_name=["indeed", "LinkedIn", "google", "bayt", "naukri","Tanitjobs"], # other "zip_recruiter", "glassdoor",
# search_term=search_term,
# google_search_term=f"{search_term} jobs near {location} since yesterday",
# location=location,
# results_wanted=results_wanted,
# hours_old=hours_old,
# country_indeed=country_indeed,
# )
# if jobs.empty:
# return f"No jobs found for '{search_term}' in '{location}'."
# # Save results to CSV
# jobs.to_csv("jobs.csv", quoting=csv.QUOTE_NONNUMERIC, escapechar="\\", index=False)
# return f"Found {len(jobs)} jobs for '{search_term}' in '{location}'. Results saved to 'jobs.csv'."
@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()
# If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
model = InferenceClientModel(
max_tokens=2096,
temperature=0.5,
model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud',# it is possible that this model may be overloaded
custom_role_conversions=None,
)
# Import tool from Hub
image_generation_tool = load_tool("agents-course/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,finance_management_plan,image_generation_tool], ## add your tools here (don't remove final answer)
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name=None,
description=None,
prompt_templates=prompt_templates
)
GradioUI(agent).launch()