from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool import datetime import requests import pytz import yaml from tools.final_answer import FinalAnswerTool import os import requests from dotenv import load_dotenv from geopy.geocoders import Nominatim from datetime import datetime MOVIE_LIMIT = 10 from Gradio_UI import GradioUI def get_geolocation_from_zipcode(zipcode: any) -> str: """A helper method to get geolocation from zipcode Args: zipcode: zipcode """ geolocator = Nominatim(user_agent='geocoding_app') location = geolocator.geocode(zipcode) if location: return location.latitude, location.longitude else: return None, None @tool def get_movies_by_zipcode(zipcode: any) -> str: """A tool that get a list of movies near a zipcode Args: zipcode: zipcode """ load_dotenv() api_key = os.getenv('MOVIE_GLU_API_KEY') auth_key = os.getenv('MOVIE_GLU_AUTH_KEY') MOVIE_GLU_BASE_URL = 'https://api-gate2.movieglu.com/filmsNowShowing/?n=' # print(f'api_key: {api_key}') # print(f'auth_key: {auth_key}') latitude, longitude = get_geolocation_from_zipcode(zipcode) current_date = datetime.now() # print(current_date.isoformat()) headers = { 'client': 'HOVL', 'x-api-key': api_key, 'authorization': auth_key, 'territory': 'US', 'api-version': 'v201', 'geolocation': f'{latitude};{longitude}', 'device-datetime': current_date.isoformat() } try: url = f'{MOVIE_GLU_BASE_URL}{zipcode}' response = requests.get(url, headers=headers) # print(f'response: {response.json()}') response.raise_for_status() json_response = response.json() movie_listings = '***********************************' count = 0 for movies in json_response['films'][:MOVIE_LIMIT]: if count == 0: movie_listings += f'***********************************\n' movie_listings += f"Movie name: {movies['film_name']}\nMovie rating: {movies['age_rating'][0]['rating']}\nMovie description: {movies['synopsis_long']}\n" movie_listings += f'***********************************\n' count += 1 return movie_listings except requests.exceptions.HTTPError as http_err: return f'HTTP error occurred while fetching movie listing for zipcode {zipcode}: {http_err}' except Exception as err: return f'Error fetching movie listing for zipcode: {zipcode}: {err}' # Below is an example of a tool that does nothing. Amaze us with your creativity ! @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 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' model = HfApiModel( max_tokens=2096, temperature=0.5, model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud',# it is possible that this model may be overloaded custom_role_conversions=None, ) # 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=model, tools=[get_movies_by_zipcode, final_answer, image_generation_tool], ## 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()