Spaces:
Sleeping
Sleeping
| 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 | |
| import requests | |
| def convert_currency(amount: float, from_currency: str, to_currency: str) -> str: | |
| """A tool that converts one currency to another based on real-time exchange rates. | |
| Args: | |
| amount: The amount of money to convert. | |
| from_currency: The currency code of the input currency (e.g., 'USD'). | |
| to_currency: The currency code of the target currency (e.g., 'EUR'). | |
| Returns: | |
| A string indicating the converted amount. | |
| """ | |
| try: | |
| # Fetch real-time exchange rates from a free API | |
| url = f"https://api.exchangerate-api.com/v4/latest/{from_currency}" | |
| response = requests.get(url).json() | |
| if 'error' in response: | |
| return f"Error fetching exchange rates for {from_currency}." | |
| exchange_rate = response['rates'].get(to_currency) | |
| if exchange_rate: | |
| converted_amount = amount * exchange_rate | |
| return f"{amount} {from_currency} = {converted_amount:.2f} {to_currency}" | |
| else: | |
| return f"Currency conversion from {from_currency} to {to_currency} not supported." | |
| except Exception as e: | |
| return f"Error converting currency: {str(e)}" | |
| import requests | |
| def web_search_duckduckgo(query: str) -> str: | |
| """A tool that performs a web search using the DuckDuckGo Instant Answer API. | |
| Args: | |
| query: The search term or query to search for. | |
| Returns: | |
| A summary of the search results from DuckDuckGo. | |
| """ | |
| try: | |
| # DuckDuckGo Instant Answer API | |
| url = f"https://api.duckduckgo.com/?q={query}&format=json" | |
| response = requests.get(url).json() | |
| # Check if there is an abstract (summary) to return | |
| if 'AbstractText' in response and response['AbstractText']: | |
| return response['AbstractText'] | |
| elif 'RelatedTopics' in response and len(response['RelatedTopics']) > 0: | |
| results = response['RelatedTopics'][:3] # Show top 3 results | |
| search_results = [] | |
| for idx, result in enumerate(results): | |
| title = result.get("Text", "No title") | |
| url = result.get("FirstURL", "No link") | |
| search_results.append(f"Result {idx+1}: {title}\nLink: {url}") | |
| return "\n".join(search_results) | |
| else: | |
| return "No relevant search results found." | |
| except Exception as e: | |
| return f"Error fetching search results: {str(e)}" | |
| 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)}" | |
| def get_weather(city: str) -> str: | |
| """A tool that fetches the current weather for a given city, without requiring an API key. | |
| Uses the free Open-Meteo API. | |
| Args: | |
| city: The name of the city to get weather for. | |
| Returns: | |
| A description of the current weather. | |
| """ | |
| try: | |
| # 1) Geocode city name → latitude/longitude | |
| geo_url = f"https://geocoding-api.open-meteo.com/v1/search?name={city}&count=1" | |
| geo_response = requests.get(geo_url).json() | |
| if "results" not in geo_response or len(geo_response["results"]) == 0: | |
| return f"Could not find location for: {city}" | |
| latitude = geo_response["results"][0]["latitude"] | |
| longitude = geo_response["results"][0]["longitude"] | |
| resolved_name = geo_response["results"][0]["name"] | |
| # 2) Fetch current weather from Open-Meteo | |
| weather_url = ( | |
| f"https://api.open-meteo.com/v1/forecast?" | |
| f"latitude={latitude}&longitude={longitude}¤t_weather=true" | |
| ) | |
| weather_response = requests.get(weather_url).json() | |
| if "current_weather" not in weather_response: | |
| return f"No current weather data available for {resolved_name}" | |
| weather = weather_response["current_weather"] | |
| temp = weather["temperature"] | |
| wind = weather["windspeed"] | |
| code = weather["weathercode"] | |
| return ( | |
| f"Weather in {resolved_name}:\n" | |
| f"- Temperature: {temp}°C\n" | |
| f"- Wind speed: {wind} km/h\n" | |
| f"- Weather code: {code}" | |
| ) | |
| except Exception as e: | |
| return f"Error fetching weather: {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='Qwen/Qwen2.5-Coder-32B-Instruct',# 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=[final_answer], ## 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() |