Spaces:
Sleeping
Sleeping
File size: 5,945 Bytes
fe023ea 9b5b26a c19d193 6aae614 8fe992b 9b5b26a 4f5daf5 9b5b26a 4f5daf5 9b5b26a 4f5daf5 9b5b26a 4f5daf5 560e38c 9b5b26a 8c01ffb 7f61a62 8c01ffb 6aae614 ae7a494 fe023ea bf6d34c 29ec968 fe328e0 13d500a 8c01ffb 9b5b26a 8c01ffb 861422e 9b5b26a 8c01ffb 8fe992b f600410 8c01ffb 861422e 8fe992b 9b5b26a 8c01ffb |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 |
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
@tool
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
@tool
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)}"
@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)}"
@tool
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() |