ogulcancicek's picture
Update app.py
331ab94 verified
Raw
History Blame Contribute Delete
4.74 kB
from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
import datetime
import requests
import pytz
import yaml
import json
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI
@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)}"
@tool
def read_todo_data() -> dict:
"""A tool to read the json file which is used for storage of todo data."""
with open('./todo.json', 'r') as f:
data = json.load(f)
return data
@tool
def print_out_todo_data(data: dict) -> str:
"""A tool to convert retrieved json data into a well structured string to show it to the user..
Args:
data: A dictionary representing the data read from json file by using `read_todo_data`
"""
output = '"""\n'
for task in data['tasks']:
task_str = (
f"Task ID: {task['id']}\n"
f"Title: {task['title']}\n"
f"Description: {task['description']}\n"
f"Due Date: {task['due_date']}\n"
f"Priority: {task['priority'].capitalize()}\n"
f"Status: {task['status'].replace('_', ' ').capitalize()}\n"
f"{'-'*40}\n\n"
)
output += task_str
return output
@tool
def add_todo_task(title: str, description: str, due_date: str, priority: str) -> None:
"""A tool to add new items into todo task storage.
Args:
title: A string representing the title of task
description: A string describing the task
due_date: A string representing the final date to complete task
priority: A string representing the priority of the task among whole tasks. It would take the following value: ['pending', 'in_progress', 'completed']
"""
data = read_todo_data()
# Create a new task
new_task = {
"id": max(task['id'] for task in data['tasks']) + 1 if data['tasks'] else 1,
"title": title,
"description": description,
"due_date": due_date,
"priority": priority,
"status": "pending"
}
# Add it to tasks list
data['tasks'].append(new_task)
# Write back to JSON file
with open(json_file_path, 'w') as f:
json.dump(data, f, indent=4)
@tool
def update_todo_task_status(task_id: int, new_status: str) -> None:
"""A tool to update status of a particular task, determined by `task_id`. To determine the task_id given by the user,
read the todo file and find out the particular task.
Args:
task_id: An integer representing the id of the task to update
new_status: A string representing new status of the given task
"""
data = read_todo_data()
# Find and update the task
found = False
for task in data['tasks']:
if task['id'] == task_id:
task['status'] = new_status
found = True
break
# If task was found, save it back
if found:
with open(json_file_path, 'w') as f:
json.dump(data, f, indent=4)
else:
print(f"Task with ID {task_id} not found.")
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 = HfApiModel(
max_tokens=2096,
temperature=0.5,
model_id='meta-llama/Llama-4-Scout-17B-16E-Instruct', # it is possible that this model may be overloaded '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)
with open("prompts.yaml", 'r') as stream:
prompt_templates = yaml.safe_load(stream)
agent = CodeAgent(
model=model,
tools=[final_answer, get_current_time_in_timezone, read_todo_data, print_out_todo_data, add_todo_task, update_todo_task_status], ## 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()