File size: 5,067 Bytes
6b7f14c
9b5b26a
 
 
c19d193
6b7f14c
7a7472f
6aae614
9b5b26a
 
6b7f14c
 
7a7472f
6b7f14c
 
 
9b5b26a
6b7f14c
 
9b5b26a
6b7f14c
9b5b26a
6b7f14c
 
 
 
 
 
 
 
 
9b5b26a
 
 
 
 
 
 
 
 
 
 
 
 
8c01ffb
7a7472f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6aae614
6b7f14c
ae7a494
6b7f14c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae7a494
e121372
6b7f14c
 
 
 
 
13d500a
8c01ffb
 
8fe992b
7a7472f
8c01ffb
 
 
 
 
 
6b7f14c
8fe992b
6b7f14c
8c01ffb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
from smolagents import CodeAgent, HfApiModel, load_tool, tool
import datetime
import requests
import pytz
import yaml
import os
from PIL import Image, ImageDraw, ImageFont
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI

# Ensure the latest smolagents version: `pip install --upgrade smolagents`
# Ensure prompts.yaml matches the provided structure with system_prompt, final_answer, planning, and managed_agent
# Ensure Pillow is installed: `pip install Pillow`
# Set your Hugging Face API token as an environment variable if required
HF_TOKEN = os.environ.get("HF_TOKEN")

@tool
def get_motivational_quote(category: str = "inspirational") -> str:
    """A tool that fetches a random motivational quote from the Quotable API.
    Args:
        category: A string representing the quote category (e.g., 'inspirational', 'life'). Defaults to 'inspirational'.
    """
    try:
        response = requests.get(f"https://api.quotable.io/random?tags={category}")
        response.raise_for_status()
        data = response.json()
        quote = data['content']
        author = data['author']
        return f"\"{quote}\" - {author}"
    except Exception as e:
        return f"Error fetching quote: {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:
        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 overlay_quote_on_image(image: object, quote: str) -> str:
    """A tool that overlays a motivational quote on an image and saves it to a file.
    Args:
        image: An AgentImage object from text-to-image tool.
        quote: A string containing the quote to overlay.
    Returns:
        A string representing the file path of the saved image.
    """
    try:
        # Convert AgentImage to PIL Image (assuming AgentImage has a to_pil() method or similar)
        pil_image = image.to_pil() if hasattr(image, 'to_pil') else Image.open(image)
        draw = ImageDraw.Draw(pil_image)
        
        # Load a default font (or specify a path to a .ttf file if available)
        try:
            font = ImageFont.truetype("arial.ttf", 40)
        except:
            font = ImageFont.load_default()
        
        # Calculate text size and position
        text = quote
        text_width, text_height = draw.textsize(text, font=font)
        image_width, image_height = pil_image.size
        text_position = ((image_width - text_width) // 2, image_height - text_height - 50)
        
        # Draw text with a black outline and white fill
        draw.text(text_position, text, font=font, fill="white", stroke_width=2, stroke_fill="black")
        
        # Save the image to a file
        output_path = "/tmp/output_image_with_quote.png"
        pil_image.save(output_path)
        return output_path
    except Exception as e:
        return f"Error overlaying quote on image: {str(e)}"

final_answer = FinalAnswerTool()
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)

# Restructure prompt_templates to match CodeAgent expectations
restructured_templates = {
    "system_prompt": prompt_templates.get("system_prompt", ""),
    "final_answer": prompt_templates.get("final_answer", ""),
    "planning": {
        "initial_facts": prompt_templates.get("planning", {}).get("initial_facts", ""),
        "initial_plan": prompt_templates.get("planning", {}).get("initial_plan", ""),
        "update_facts_pre_messages": prompt_templates.get("planning", {}).get("update_facts_pre_messages", ""),
        "update_facts_post_messages": prompt_templates.get("planning", {}).get("update_facts_post_messages", ""),
        "update_plan_pre_messages": prompt_templates.get("planning", {}).get("update_plan_pre_messages", ""),
        "update_plan_post_messages": prompt_templates.get("planning", {}).get("update_plan_post_messages", "")
    },
    "managed_agent": {
        "task": prompt_templates.get("managed_agent", {}).get("task", ""),
        "report": prompt_templates.get("managed_agent", {}).get("report", "")
    }
}

model = HfApiModel(
    model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
    token=HF_TOKEN,
    max_tokens=2096,
    temperature=0.5,
    custom_role_conversions=None
)

agent = CodeAgent(
    model=model,
    tools=[get_motivational_quote, get_current_time_in_timezone, image_generation_tool, overlay_quote_on_image, final_answer],
    max_steps=6,
    verbosity_level=1,
    grammar=None,
    planning_interval=None,
    name=None,
    description=None,
    prompt_templates=restructured_templates
)

GradioUI(agent).launch()