File size: 4,730 Bytes
64efe92
9b5b26a
 
 
c19d193
6aae614
9b5b26a
64efe92
9b5b26a
 
64efe92
 
 
 
9b5b26a
64efe92
 
 
 
 
 
 
9b5b26a
64efe92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b5b26a
 
 
64efe92
 
 
9b5b26a
 
64efe92
 
 
9b5b26a
 
 
 
 
 
 
8c01ffb
64efe92
6aae614
64efe92
 
ae7a494
64efe92
e121372
64efe92
 
 
 
13d500a
8c01ffb
64efe92
9b5b26a
8c01ffb
64efe92
861422e
 
9b5b26a
64efe92
8c01ffb
8fe992b
64efe92
 
8c01ffb
 
 
 
 
861422e
8fe992b
 
64efe92
 
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
from smolagents import CodeAgent, HfApiModel, DuckDuckGoSearchTool, VisitWebpageTool, load_tool, tool
import datetime
import requests
import pytz
import yaml
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI
import xml.etree.ElementTree as ET

@tool
def pull_ecb_eur_usd_rate(requested_date: str = None) -> str:
    """
    A tool that fetches the EUR-to-USD exchange rate from the European Central Bank for today.
    
    Args:
        requested_date: (Optional) A string in "YYYY-MM-DD" format. If provided and it is not equal to today's date,
                        the function returns an error.
                        
    Returns:
        A string indicating the exchange rate as of the ECB data's date, or an error message if:
          - the requested date is not today, or
          - the ECB data is not updated for today.
    """
    try:
        # Determine today's date in the ECB's (Central European) timezone.
        brussels_tz = pytz.timezone("Europe/Brussels")
        today = datetime.datetime.now(brussels_tz).date()

        # If a date is provided, check that it matches today's date.
        if requested_date:
            try:
                req_date = datetime.datetime.strptime(requested_date, "%Y-%m-%d").date()
            except Exception:
                return f"Error: The provided date '{requested_date}' is not in the correct format (YYYY-MM-DD)."
            if req_date != today:
                return f"Error: The requested date {req_date} is not available. Only today's data ({today}) is supported."

        # Fetch the ECB daily XML data.
        url = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"
        response = requests.get(url)
        if response.status_code != 200:
            return f"Error: Received status code {response.status_code} from ECB."

        xml_content = response.content
        tree = ET.ElementTree(ET.fromstring(xml_content))
        root = tree.getroot()

        # Define namespaces used in the ECB XML.
        ns = {
            'gesmes': 'http://www.gesmes.org/xml/2002-08-01',
            'def': 'http://www.ecb.int/vocabulary/2002-08-01/eurofxref'
        }

        # Locate the Cube element with the time attribute.
        time_cube = root.find('.//def:Cube/def:Cube', ns)
        if time_cube is not None:
            data_date = time_cube.get('time')
            # If ECB's data date is not today, return an error.
            if data_date != str(today):
                return f"Error: ECB data is not updated for today. Latest available data is for {data_date}."
            
            # Find the Cube element for USD.
            usd_cube = time_cube.find("def:Cube[@currency='USD']", ns)
            if usd_cube is not None:
                rate = usd_cube.get('rate')
                return f"As of {data_date}, EUR 1 is equivalent to {rate} USD."
        
        return "Error: USD rate not found in ECB data."
    except Exception as e:
        return f"Error fetching ECB 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').
    
    Returns:
        A string with the current local time in the specified timezone.
    """
    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)}"

# Tools for final answer and additional capabilities.
final_answer = FinalAnswerTool()
search_result = DuckDuckGoSearchTool()
visit_webpage = VisitWebpageTool()

# Initialize the model.
model = HfApiModel(
    max_tokens=2096,
    temperature=0.5,
    model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
    custom_role_conversions=None,
)

# Import image generation tool from Hub (if needed).
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)

# Load prompt templates from the YAML file.
with open("prompts.yaml", 'r') as stream:
    prompt_templates = yaml.safe_load(stream)
    
# Create the CodeAgent and register the tools (including the updated ECB rate tool).
agent = CodeAgent(
    model=model,
    tools=[final_answer, get_current_time_in_timezone, pull_ecb_eur_usd_rate],
    max_steps=10,
    verbosity_level=1,
    grammar=None,
    planning_interval=None,
    name=None,
    description=None,
    prompt_templates=prompt_templates
)

# Launch the Gradio UI for interacting with the agent.
GradioUI(agent).launch()