Spaces:
Sleeping
Sleeping
File size: 4,679 Bytes
c4c003b |
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 |
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
# Tool: Fetch current time in a given timezone
@tool
def get_current_time_in_timezone(timezone: str) -> str:
"""
Fetches the current local time in a specified timezone.
Args:
timezone (str): The timezone string (e.g., 'America/New_York').
Returns:
str: The current local time in the specified timezone.
"""
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)}"
# Tool: Fetch real-time weather for a given location
@tool
def get_weather(city: str) -> str:
"""
Fetches the current weather for a given city.
Args:
city (str): The name of the city.
Returns:
str: Weather description and temperature.
"""
api_url = f"https://wttr.in/{city}?format=%C+%t"
response = requests.get(api_url)
if response.status_code == 200:
return response.text
return "Unable to retrieve weather information."
# Tool: Fetch currency exchange rate
@tool
def get_exchange_rate(base_currency: str, target_currency: str) -> str:
"""
Fetches the exchange rate between two currencies.
Args:
base_currency (str): The currency to convert from.
target_currency (str): The currency to convert to.
Returns:
str: Exchange rate information.
"""
url = f"https://api.exchangerate-api.com/v4/latest/{base_currency}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
rate = data['rates'].get(target_currency, "N/A")
return f"1 {base_currency} = {rate} {target_currency}"
return "Exchange rate information not available."
# Tool: Fetch Wikipedia summary
@tool
def get_wikipedia_summary(query: str) -> str:
"""
Fetches a short summary from Wikipedia.
Args:
query (str): The topic to search on Wikipedia.
Returns:
str: Summary of the topic.
"""
url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{query}"
response = requests.get(url)
if response.status_code == 200:
return response.json().get("extract", "No summary available.")
return "Wikipedia summary not found."
# Tool: Fetch latest news headlines
@tool
def get_latest_news() -> str:
"""
Fetches the latest news headlines.
Returns:
str: Top 5 latest news headlines.
"""
url = "https://newsapi.org/v2/top-headlines?country=us&apiKey=YOUR_NEWSAPI_KEY"
response = requests.get(url)
if response.status_code == 200:
articles = response.json().get("articles", [])[:5]
return "\n".join([f"{i+1}. {article['title']}" for i, article in enumerate(articles)])
return "Unable to retrieve news."
# Tool: Fetch stock price for a given company symbol
@tool
def get_stock_price(symbol: str) -> str:
"""
Fetches the latest stock price for a given company symbol.
Args:
symbol (str): The stock ticker symbol.
Returns:
str: The latest stock price.
"""
url = f"https://finnhub.io/api/v1/quote?symbol={symbol}&token=YOUR_FINNHUB_API_KEY"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
return f"Stock price of {symbol}: ${data.get('c', 'N/A')}"
return "Stock information not available."
final_answer = FinalAnswerTool()
# Hugging Face model setup
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 Hugging Face
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)
# Creating the AI agent
agent = CodeAgent(
model=model,
tools=[
final_answer,
get_current_time_in_timezone,
get_weather,
get_exchange_rate,
get_wikipedia_summary,
get_latest_news,
get_stock_price,
image_generation_tool,
],
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name=None,
description=None,
prompt_templates=prompt_templates
)
# Launch Gradio UI for interaction
GradioUI(agent).launch()
|