samsonDzealot/First_agent_template
0
1from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool2import datetime3import requests4import pytz5import yaml6from tools.final_answer import FinalAnswerTool7from Gradio_UI import GradioUI8from bs4 import BeautifulSoup9 10@tool11def get_weather(city: str) -> str:12 """A tool that fetches the current weather for a given city.13 Args:14 city: A string representing the city name (e.g., 'New York').15 """16 api_key = "..." # Replace with your key17 url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"18 try:19 response = requests.get(url)20 data = response.json()21 if data["cod"] != 200:22 return f"Error: City '{city}' not found or API issue."23 temp = data["main"]["temp"]24 desc = data["weather"][0]["description"]25 return f"Current weather in {city}: {temp}°C, {desc}."26 except Exception as e:27 return f"Error fetching weather for '{city}': {str(e)}"28 29# Trending Hashtags Tool (Scraping getdaytrends.com)30@tool31def get_trending_hashtags(location: str = "usa") -> str:32 """A tool that fetches trending hashtags from getdaytrends.com for a given location.33 Args:34 location: A string representing the location (e.g., 'usa', 'uk'). Defaults to 'usa'.35 """36 try:37 url = f"https://getdaytrends.com/{location.lower()}/"38 response = requests.get(url)39 if response.status_code != 200:40 return f"Error: Couldn’t fetch trends for '{location}'."41 soup = BeautifulSoup(response.text, "html.parser")42 # Find trend items (adjust selector based on site - this is a guess, might need tweak)43 trends = [tag.text.strip() for tag in soup.select("td a[href*='twitter.com']")[:5]]44 if not trends:45 return f"Error: No trends found for '{location}' - site might’ve changed."46 return f"Top trending hashtags in {location}: {', '.join(trends)}"47 except Exception as e:48 return f"Error fetching trends for '{location}': {str(e)}"49 50@tool51def get_current_time_in_timezone(timezone: str) -> str:52 """A tool that fetches the current local time in a specified timezone.53 Args:54 timezone: A string representing a valid timezone (e.g., 'America/New_York').55 """56 try:57 # Create timezone object58 tz = pytz.timezone(timezone)59 # Get current time in that timezone60 local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")61 return f"The current local time in {timezone} is: {local_time}"62 except Exception as e:63 return f"Error fetching time for timezone '{timezone}': {str(e)}"64 65 66final_answer = FinalAnswerTool()67 68# 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:69# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' 70 71model = HfApiModel(72max_tokens=2096,73temperature=0.5,74model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded75custom_role_conversions=None,76)77 78 79# Import tool from Hub80image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)81 82with open("prompts.yaml", 'r') as stream:83 prompt_templates = yaml.safe_load(stream)84 85agent = CodeAgent(86 model=model,87 tools=[final_answer, get_weather, get_trending_hashtags, get_current_time_in_timezone], ## add your tools here (don't remove final answer)88 max_steps=6,89 verbosity_level=1,90 grammar=None,91 planning_interval=None,92 name=None,93 description=None,94 prompt_templates=prompt_templates95)96 97 98GradioUI(agent).launch()