from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool import datetime import requests import pytz import yaml from tools.final_answer import FinalAnswerTool from Gradio_UI import GradioUI # Search Tool using DuckDuckGo search_tool = DuckDuckGoSearchTool() # Text Summarization Tool @tool def summarize_text(text: str) -> str: """Summarizes a given text into a concise version. Args: text: The text to be summarized. """ try: api_url = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn" headers = {"Authorization": "Bearer YOUR_HUGGINGFACE_API_KEY"} response = requests.post(api_url, headers=headers, json={"inputs": text}) summary = response.json()[0]['summary_text'] return summary except Exception as e: return f"Error in summarization: {str(e)}" # Weather Information Tool @tool def get_weather(city: str) -> str: """Fetches current weather information for a given city. Args: city: Name of the city. """ try: api_key = "YOUR_OPENWEATHERMAP_API_KEY" url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric" response = requests.get(url).json() temp = response["main"]["temp"] weather_desc = response["weather"][0]["description"] return f"The current temperature in {city} is {temp}°C with {weather_desc}." except Exception as e: return f"Error fetching weather data: {str(e)}" # Currency Conversion Tool @tool def convert_currency(amount: float, from_currency: str, to_currency: str) -> str: """Converts currency based on real-time exchange rates. Args: amount: The amount to be converted. from_currency: The source currency (e.g., 'USD'). to_currency: The target currency (e.g., 'EUR'). """ try: api_url = f"https://api.exchangerate-api.com/v4/latest/{from_currency}" response = requests.get(api_url).json() rate = response["rates"].get(to_currency, None) if rate: converted_amount = amount * rate return f"{amount} {from_currency} is approximately {converted_amount:.2f} {to_currency}." else: return f"Conversion rate for {to_currency} not found." except Exception as e: return f"Error in currency conversion: {str(e)}" # Fun Fact Generator Tool @tool def get_fun_fact() -> str: """Fetches a random fun fact.""" try: response = requests.get("https://uselessfacts.jsph.pl/random.json?language=en").json() return response["text"] except Exception as e: return f"Error fetching fun fact: {str(e)}" # Text Sentiment Analyzer @tool def analyze_sentiment(text: str) -> str: """Analyzes the sentiment of a given text (positive, neutral, or negative). Args: text: The text to be analyzed. """ try: api_url = "https://api-inference.huggingface.co/models/cardiffnlp/twitter-roberta-base-sentiment" headers = {"Authorization": "Bearer YOUR_HUGGINGFACE_API_KEY"} response = requests.post(api_url, headers=headers, json={"inputs": text}) sentiment = response.json()[0][0]['label'] return f"The sentiment of the given text is: {sentiment}" except Exception as e: return f"Error in sentiment analysis: {str(e)}" # Time Zone Tool @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: tz = pytz.timezone(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() model = HfApiModel( max_tokens=2096, temperature=0.5, model_id='https://wxknx1kg971u7k1n.us-east-1.aws.endpoints.huggingface.cloud', custom_role_conversions=None, ) # Import tool from Hugging Face 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) # Define Agent with All Tools agent = CodeAgent( model=model, tools=[final_answer, search_tool, image_generation_tool, summarize_text, get_weather, convert_currency, get_fun_fact, analyze_sentiment, get_current_time_in_timezone], max_steps=6, verbosity_level=1, grammar=None, planning_interval=None, name=None, description=None, prompt_templates=prompt_templates ) GradioUI(agent).launch()