CuriousPeachSeeker's picture
Update app.py
d3d9de1 verified
Raw History Blame Contribute Delete
2.84 kB
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
import datetime
import os
import pytz
import yaml
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI
@tool
def my_custom_tool(arg1: str, arg2: int) -> str:
"""A tool that does something creative
Args:
arg1: the first argument
arg2: the second argument
"""
return f"Processing '{arg1}' with value {arg2}!"
@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:
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)}"
@tool
def generate_image(prompt: str) -> str:
"""Generate an image from a text prompt and display it
Args:
prompt: Description of the image to generate (e.g., 'a sunset over mountains')
"""
try:
# Generate the image
image = image_generation_tool(prompt)
# Create output directory if it doesn't exist
os.makedirs("generated_images", exist_ok=True)
# Save the image with timestamp
from datetime import datetime as dt
timestamp = dt.now().strftime("%Y%m%d_%H%M%S")
filename = f"generated_images/image_{timestamp}.png"
image.save(filename)
# Return the image path so Gradio can display it
return filename # Return just the filename/path
except Exception as e:
return f"Error generating image: {str(e)}"
# Initialize model - use HfApiModel
model = HfApiModel(
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
token=os.getenv("HF_TOKEN") # Set HF_TOKEN environment variable
)
# Load system prompt
with open("prompts.yaml", 'r') as stream:
prompt_templates = yaml.safe_load(stream)
# Load image generation tool
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
# Create agent with tools
final_answer = FinalAnswerTool()
search_tool = DuckDuckGoSearchTool()
agent = CodeAgent(
model=model,
tools=[
final_answer,
search_tool,
my_custom_tool,
get_current_time_in_timezone,
generate_image, # Use the new tool instead
image_generation_tool
],
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name=None,
description=None,
prompt_templates=prompt_templates
)
# Launch with image display enabled
GradioUI(agent).launch(show_error=True)