File size: 4,351 Bytes
d2a0808
 
 
 
deafbd7
d2a0808
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deafbd7
 
 
 
 
d2a0808
 
 
 
 
deafbd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2a0808
 
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
from smolagents import CodeAgent, tool, OpenAIServerModel, FinalAnswerTool
import datetime
import pytz
import yfinance as yf
import os
from Gradio_UI import GradioUI

# Fetch the API key from the environment variable (if needed)
API_KEY = os.getenv("KEY")

@tool
def get_currency_rate(currency_pair: str) -> str:
    """Fetches the current exchange rate for a given currency pair (e.g., 'USD-EUR').
    Args:
        currency_pair: The currency pair to query, formatted as 'BASE-CURRENCY'.
    """
    try:
        base, target = currency_pair.split("-")
        # Use yfinance to get the exchange rate
        ticker = f"{base}{target}=X"  # Format for yfinance (e.g., "USDEUR=X")
        data = yf.Ticker(ticker)
        rate = data.history(period="1d")["Close"].iloc[-1]
        return f"Current {currency_pair} rate: {rate}"
    except Exception as e:
        return f"Error fetching 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').
    """
    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)}"

# Set up the model
model = OpenAIServerModel(
    model_id="deepseek-chat",
    api_base="https://api.deepseek.com",
    api_key=API_KEY
)

# Load tools
final_answer = FinalAnswerTool()
currency_tool = get_currency_rate
time_tool = get_current_time_in_timezone

# Create the agent
agent = CodeAgent(
    model=model,
    tools=[currency_tool, time_tool, final_answer],  # Include your tools here
    max_steps=3,
    verbosity_level=1
)

# Define example usage instructions
example_usage = """
### Example Usage
1. **Currency Rate**: Ask for the exchange rate of a currency pair.
   - Example: "What is the current exchange rate for USD to JPY?"
   - Example: "Get the EUR to GBP rate."

2. **Current Time**: Ask for the current time in a specific timezone.
   - Example: "What is the current time in America/New_York?"
   - Example: "Get the time in Asia/Tokyo."
"""

# Extend the GradioUI class to include the example usage
class CustomGradioUI(GradioUI):
    def __init__(self, agent, description: str = "", **kwargs):
        super().__init__(agent, **kwargs)
        self.description = description

    def launch(self, **kwargs):
        import gradio as gr

        with gr.Blocks(fill_height=True) as demo:
            # Add the description as a Markdown component
            if self.description:
                gr.Markdown(self.description)

            # Add the existing chatbot and input components
            stored_messages = gr.State([])
            file_uploads_log = gr.State([])
            chatbot = gr.Chatbot(
                label="Agent",
                type="messages",
                avatar_images=(
                    None,
                    "https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/Alfred.png",
                ),
                resizeable=True,
                scale=1,
            )
            # If an upload folder is provided, enable the upload feature
            if self.file_upload_folder is not None:
                upload_file = gr.File(label="Upload a file")
                upload_status = gr.Textbox(label="Upload Status", interactive=False, visible=False)
                upload_file.change(
                    self.upload_file,
                    [upload_file, file_uploads_log],
                    [upload_status, file_uploads_log],
                )
            text_input = gr.Textbox(lines=1, label="Chat Message")
            text_input.submit(
                self.log_user_message,
                [text_input, file_uploads_log],
                [stored_messages, text_input],
            ).then(self.interact_with_agent, [stored_messages, chatbot], [chatbot])

        demo.launch(debug=True, share=True, **kwargs)

# Launch the Gradio UI with the example usage
CustomGradioUI(agent, description=example_usage).launch()