Spaces:
Sleeping
Sleeping
| from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool | |
| import datetime | |
| import requests | |
| import pytz | |
| import yaml | |
| import json | |
| from tools.final_answer import FinalAnswerTool | |
| from Gradio_UI import GradioUI | |
| # Web Search Tool | |
| def web_search(query: str) -> str: | |
| """Search the web using DuckDuckGo for current information. | |
| Args: | |
| query: The search query string | |
| """ | |
| try: | |
| search_tool = DuckDuckGoSearchTool() | |
| results = search_tool(query) | |
| return results | |
| except Exception as e: | |
| return f"Error performing web search: {str(e)}" | |
| # Time and Date Tool | |
| def get_current_time_in_timezone(timezone: str) -> str: | |
| """Get the current local time in a specified timezone. | |
| Args: | |
| timezone: A valid timezone string (e.g., 'America/New_York', 'Europe/London', 'Asia/Tokyo') | |
| """ | |
| try: | |
| tz = pytz.timezone(timezone) | |
| local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S %Z") | |
| return f"The current local time in {timezone} is: {local_time}" | |
| except Exception as e: | |
| return f"Error: Invalid timezone '{timezone}'. {str(e)}" | |
| # Calculator Tool | |
| def calculate(expression: str) -> str: | |
| """Evaluate a mathematical expression safely. | |
| Args: | |
| expression: A mathematical expression as a string (e.g., '2 + 2', '10 * 5 + 3') | |
| """ | |
| try: | |
| # Safe evaluation using only numbers and basic operators | |
| allowed_chars = set('0123456789+-*/(). ') | |
| if not all(c in allowed_chars for c in expression): | |
| return "Error: Expression contains invalid characters" | |
| result = eval(expression, {"__builtins__": {}}, {}) | |
| return f"Result: {result}" | |
| except Exception as e: | |
| return f"Error calculating expression: {str(e)}" | |
| # Weather Tool | |
| def get_weather(city: str) -> str: | |
| """Get current weather information for a city using wttr.in service. | |
| Args: | |
| city: Name of the city to get weather for | |
| """ | |
| try: | |
| url = f"https://wttr.in/{city}?format=j1" | |
| response = requests.get(url, timeout=10) | |
| if response.status_code == 200: | |
| data = response.json() | |
| current = data['current_condition'][0] | |
| temp_c = current['temp_C'] | |
| temp_f = current['temp_F'] | |
| weather_desc = current['weatherDesc'][0]['value'] | |
| humidity = current['humidity'] | |
| wind_speed = current['windspeedKmph'] | |
| return f"Weather in {city}: {weather_desc}, Temperature: {temp_c}°C ({temp_f}°F), Humidity: {humidity}%, Wind Speed: {wind_speed} km/h" | |
| else: | |
| return f"Could not fetch weather for {city}" | |
| except Exception as e: | |
| return f"Error fetching weather: {str(e)}" | |
| # File Reader Tool | |
| def read_file(filepath: str) -> str: | |
| """Read and return the contents of a text file. | |
| Args: | |
| filepath: Path to the file to read | |
| """ | |
| try: | |
| with open(filepath, 'r', encoding='utf-8') as f: | |
| content = f.read() | |
| return f"File content:\n{content}" | |
| except Exception as e: | |
| return f"Error reading file: {str(e)}" | |
| # File Writer Tool | |
| def write_file(filepath: str, content: str) -> str: | |
| """Write content to a text file. | |
| Args: | |
| filepath: Path where the file should be written | |
| content: Content to write to the file | |
| """ | |
| try: | |
| with open(filepath, 'w', encoding='utf-8') as f: | |
| f.write(content) | |
| return f"Successfully wrote to {filepath}" | |
| except Exception as e: | |
| return f"Error writing file: {str(e)}" | |
| # Currency Converter Tool | |
| def convert_currency(amount: float, from_currency: str, to_currency: str) -> str: | |
| """Convert an amount from one currency to another using live exchange rates. | |
| Args: | |
| amount: The amount to convert | |
| from_currency: The source currency code (e.g., 'USD', 'EUR', 'GBP') | |
| to_currency: The target currency code (e.g., 'USD', 'EUR', 'GBP') | |
| """ | |
| try: | |
| url = f"https://api.exchangerate-api.com/v4/latest/{from_currency.upper()}" | |
| response = requests.get(url, timeout=10) | |
| if response.status_code == 200: | |
| data = response.json() | |
| rate = data['rates'].get(to_currency.upper()) | |
| if rate: | |
| converted = amount * rate | |
| return f"{amount} {from_currency.upper()} = {converted:.2f} {to_currency.upper()}" | |
| else: | |
| return f"Currency code '{to_currency}' not found" | |
| else: | |
| return "Error fetching exchange rates" | |
| except Exception as e: | |
| return f"Error converting currency: {str(e)}" | |
| # Wikipedia Summary Tool | |
| def get_wikipedia_summary(topic: str) -> str: | |
| """Get a brief summary from Wikipedia about a topic. | |
| Args: | |
| topic: The topic to search for on Wikipedia | |
| """ | |
| try: | |
| url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{topic.replace(' ', '_')}" | |
| response = requests.get(url, timeout=10) | |
| if response.status_code == 200: | |
| data = response.json() | |
| return f"Wikipedia Summary: {data.get('extract', 'No summary available')}" | |
| else: | |
| return f"Could not find Wikipedia article for '{topic}'" | |
| except Exception as e: | |
| return f"Error fetching Wikipedia summary: {str(e)}" | |
| # List Available Timezones Tool | |
| def list_common_timezones(region: str = "all") -> str: | |
| """List common timezones, optionally filtered by region. | |
| Args: | |
| region: Region to filter by (e.g., 'America', 'Europe', 'Asia', 'all') | |
| """ | |
| try: | |
| if region.lower() == "all": | |
| timezones = pytz.common_timezones[:20] # First 20 for brevity | |
| return f"Common timezones (first 20): {', '.join(timezones)}" | |
| else: | |
| filtered = [tz for tz in pytz.common_timezones if tz.startswith(region)] | |
| return f"Timezones in {region}: {', '.join(filtered[:30])}" | |
| except Exception as e: | |
| return f"Error listing timezones: {str(e)}" | |
| final_answer = FinalAnswerTool() | |
| model = HfApiModel( | |
| max_tokens=2096, | |
| temperature=0.5, | |
| model_id='Qwen/Qwen2.5-Coder-32B-Instruct', | |
| custom_role_conversions=None, | |
| ) | |
| # Load image generation 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=[ | |
| final_answer, | |
| web_search, | |
| get_current_time_in_timezone, | |
| calculate, | |
| get_weather, | |
| read_file, | |
| write_file, | |
| convert_currency, | |
| get_wikipedia_summary, | |
| list_common_timezones, | |
| image_generation_tool, | |
| ], | |
| max_steps=6, | |
| verbosity_level=1, | |
| grammar=None, | |
| planning_interval=None, | |
| name=None, | |
| description=None, | |
| prompt_templates=prompt_templates | |
| ) | |
| GradioUI(agent).launch() |