mohammadKa143's picture
Update app.py
bb94855 verified
raw
history blame
6.81 kB
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()