File size: 6,805 Bytes
3adc52b
1a13ee2
 
 
 
 
3adc52b
 
9132eff
0d4c240
 
9132eff
 
 
 
 
 
 
bb94855
9132eff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d4c240
632b5c9
 
 
 
 
 
 
 
 
 
0d4c240
 
3c5d7bd
0d4c240
 
1a13ee2
0d4c240
 
 
 
 
 
 
6c32517
0d4c240
 
 
 
1a13ee2
 
47fa873
 
632b5c9
47fa873
 
 
 
 
 
 
 
 
 
1a13ee2
 
 
632b5c9
 
1a13ee2
3adc52b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a13ee2
 
ed91cef
 
632b5c9
 
1a13ee2
632b5c9
 
 
1a13ee2
3adc52b
9132eff
47fa873
632b5c9
47fa873
 
 
 
 
1a13ee2
 
8fe992b
3adc52b
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
from smolagents import CodeAgent,DuckDuckGoSearchTool, LiteLLMModel,load_tool,tool
import datetime
import requests
import pytz
import yaml
from tools.final_answer import FinalAnswerTool
import os
from Gradio_UI import GradioUI

from duckduckgo_search import DDGS

import pywhatkit
import datetime
import time



@tool
def send_whatsapp_message(phone_number: str = '+963934324595', message: str = '', hour: int = None, minute: int = None):
    """
    Sends a WhatsApp message using pywhatkit by automating WhatsApp Web.

    This function schedules a WhatsApp message to be sent at a specific time,
    or approximately one minute from now if no time is specified. It works by 
    opening WhatsApp Web in your default browser and simulating the sending
    process.

    Args:
        phone_number (str): The recipient's phone number. 
                            MUST include the country code with a '+', 
                            e.g., "+12345678901".
        message (str): The text message you want to send.
        hour (int, optional): The hour (in 24-hour format, 0-23) to send 
                              the message. Defaults to None.
        minute (int, optional): The minute (0-59) to send the message. 
                                Defaults to None. If hour or minute is None,
                                the message will be scheduled for ~1 minute 
                                from the current time.

    Returns:
        bool: True if the message scheduling was attempted successfully by 
              pywhatkit, False if an error occurred.

    --- IMPORTANT NOTES ---
    - You MUST be logged into WhatsApp Web on the browser pywhatkit opens.
    - This function will open a new browser tab/window.
    - Sending is NOT instant; it happens *at* or slightly *after* the scheduled time.
    - This method relies on web automation and can be unreliable if WhatsApp Web changes.
    - Heavy automation might violate WhatsApp's Terms of Service. Use responsibly.
    """
    try:
        send_h, send_m = 0, 0

        if hour is None or minute is None:
            # If no specific time is given, calculate 1 minute from now
            now = datetime.datetime.now()
            send_h = now.hour
            send_m = now.minute + 1

            # Handle minute and hour overflow
            if send_m >= 60:
                send_m -= 60
                send_h += 1
                if send_h >= 24:
                    send_h = 0
            print(f"No time specified. Scheduling for ~1 minute from now: {send_h:02d}:{send_m:02d}")
        else:
            # Use the provided time
            send_h = hour
            send_m = minute
            print(f"Scheduling for specified time: {send_h:02d}:{send_m:02d}")

        print(f"Attempting to schedule for: {phone_number}")
        print(f"Message: {message}")

        # Use pywhatkit to schedule the message
        pywhatkit.sendwhatmsg(
            phone_no=phone_number,
            message=message,
            time_hour=send_h,
            time_min=send_m,
            wait_time=15,  # Seconds for WhatsApp Web to load & send before closing tab
            tab_close=True, # Close the tab after sending
            close_time=3    # Seconds to wait *after* sending before closing
        )

        print("pywhatkit has successfully initiated the scheduling process.")
        return True

    except Exception as e:
        print(f"An error occurred while trying to send WhatsApp message: {e}")
        print("Things to check:")
        print("  - Is pywhatkit installed (`pip install pywhatkit`)?")
        print("  - Are you logged into WhatsApp Web in your default browser?")
        print("  - Is the phone number format correct (e.g., '+12345678901')?")
        return False





@tool
def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
    #Keep this format for the description / args / args description but feel free to modify the tool
    """A tool that does nothing yet 
    Args:
        arg1: the first argument
        arg2: the second argument
    """
    return "What magic will you build ?"
    
@tool
def search_duckduckgo(topic : str)-> list:
  """
  Searches DuckDuckGo for a given topic and returns a list of results.

  Args:
    topic: The topic to search for.

  Returns:
    A list of dictionaries, where each dictionary represents a search result
    and contains keys like 'title', 'href', and 'body'.
  """
  results = DDGS().text(topic, max_results=3)
  return results


    
@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)}"


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' 

os.environ["GOOGLE_API_KEY"] = "AIzaSyBcJrlnDDdWtjUDiLrisSOPuaAGizCLKO4"
gemini_api_key = os.environ.get("GOOGLE_API_KEY")

try:
    # LiteLLM uses 'gemini/' prefix for Google AI Studio models
    gemini_model = LiteLLMModel(
        model_id="gemini/gemini-1.5-flash-latest",
        api_key=gemini_api_key,
        temperature = 0.5,
        max_tokens = 2096,
        custom_role_conversions=None
    )
    print("Successfully initialized LiteLLMModel for Gemini 1.5 Flash.")

except Exception as e:
    print(f"Failed to initialize LiteLLMModel: {e}")
    gemini_model = None
    
# model = HfApiModel(
# max_tokens=2096,
# temperature=0.5,
# model_id='google/gemma-2b-it',# it is possible that this model may be overloaded
# custom_role_conversions=None,
# )


search_tool = DuckDuckGoSearchTool()

# 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=gemini_model,
    tools=[final_answer,get_current_time_in_timezone,search_duckduckgo,send_whatsapp_message], ## 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()