Spaces:
Sleeping
Sleeping
File size: 8,471 Bytes
9b5b26a c19d193 6aae614 0596b96 8fe992b 9b5b26a 5df72d6 9b5b26a c8e174e 9b5b26a c8e174e 9b5b26a c8e174e 9b5b26a 8c01ffb b34abe5 15e8e1d b34abe5 8c01ffb 8361543 0596b96 8361543 0596b96 8361543 0596b96 8361543 0596b96 8361543 0596b96 8361543 0596b96 8361543 0596b96 303f84b 0596b96 6aae614 ae7a494 e121372 94ae4bd 3fdc299 94ae4bd 13d500a 8c01ffb 9b5b26a 8c01ffb 861422e 9b5b26a 8c01ffb 8fe992b b34abe5 0596b96 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 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
import datetime
import requests
import pytz
import yaml
from tools.final_answer import FinalAnswerTool
import yfinance as yf
from Gradio_UI import GradioUI
# Below is an example of a tool that does nothing. Amaze us with your creativity !
@tool
def math_operation(arg1: float, arg2: float, operation: str) -> float:
"""A tool that performs basic arithmetic operations.
Args:
arg1: The first number.
arg2: The second number.
operation: The operation to perform ('add', 'subtract', 'multiply', 'divide').
Returns:
The result of the operation.
"""
match operation:
case "add":
return arg1 + arg2
case "subtract":
return arg1 - arg2
case "multiply":
return arg1 * arg2
case "divide":
return arg1 / arg2 if arg2 != 0 else float("inf") # Evita divisão por zero
case _:
raise ValueError("Invalid operation. Use 'add', 'subtract', 'multiply', or 'divide'.")
@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 internet_search(query: str) -> str:
"""
A tool to search the internet using DuckDuckGo.
Args:
query: The search query.
Returns:
The top search result.
"""
seach = DuckDuckGoSearchTool()
results = seach.forward(query)
return results if results else "No results found."
@tool
def get_stock_info(ticker: str) -> str:
"""
Fetches general information about a given stock.
Args:
ticker: The stock symbol (e.g., "AAPL" for Apple, "MSFT" for Microsoft).
Returns:
A summary of the stock information.
"""
try:
stock = yf.Ticker(ticker)
info = stock.info
return (f"Company: {info.get('longName', 'N/A')}\n"
f"Sector: {info.get('sector', 'N/A')}\n"
f"Industry: {info.get('industry', 'N/A')}\n"
f"Country: {info.get('country', 'N/A')}\n"
f"Market Cap: {info.get('marketCap', 'N/A')}\n"
f"PE Ratio: {info.get('trailingPE', 'N/A')}")
except Exception as e:
return f"Error fetching stock information: {str(e)}"
@tool
def get_stock_price(ticker: str) -> str:
"""
Fetches the current stock price.
Args:
ticker: The stock symbol (e.g., "AAPL", "MSFT").
Returns:
The latest stock price.
"""
try:
stock = yf.Ticker(ticker)
price = stock.history(period="1d")["Close"].iloc[-1]
return f"The latest closing price for {ticker} is ${price:.2f}."
except Exception as e:
return f"Error fetching stock price: {str(e)}"
@tool
def compare_stocks(ticker1: str, ticker2: str, period: str = "1y") -> str:
"""
Compares the performance of two stocks over a given period.
Args:
ticker1: The first stock symbol.
ticker2: The second stock symbol.
period: The time period for comparison (e.g., "1mo", "6mo", "1y").
Returns:
A summary of their percentage change over the period.
"""
try:
stock1 = yf.Ticker(ticker1).history(period=period)["Close"]
stock2 = yf.Ticker(ticker2).history(period=period)["Close"]
if stock1.empty or stock2.empty:
return "Insufficient data for comparison."
change1 = ((stock1.iloc[-1] - stock1.iloc[0]) / stock1.iloc[0]) * 100
change2 = ((stock2.iloc[-1] - stock2.iloc[0]) / stock2.iloc[0]) * 100
return (f"{ticker1}: {change1:.2f}% over {period}\n"
f"{ticker2}: {change2:.2f}% over {period}")
except Exception as e:
return f"Error comparing stocks: {str(e)}"
@tool
def get_index_price(index: str) -> str:
"""
Fetches the current price of a stock market index.
Args:
index: The index ticker (e.g., "^GSPC" for S&P 500, "^DJI" for Dow Jones, "^IXIC" for Nasdaq).
Returns:
The latest closing price of the index.
"""
try:
ticker = yf.Ticker(index)
price = ticker.history(period="1d")["Close"].iloc[-1]
return f"The latest closing price for {index} is {price:.2f}."
except Exception as e:
return f"Error fetching index price: {str(e)}"
@tool
def get_interest_rates() -> str:
"""
Fetches the latest Selic, CDI, and IPCA rates.
Returns:
The latest values for Brazil's key interest rates.
"""
import requests
try:
response = requests.get("https://api.bcb.gov.br/dados/serie/bcdata.sgs.11/dados/ultimos/1?formato=json") # SELIC
selic = response.json()[0]['valor']
response = requests.get("https://api.bcb.gov.br/dados/serie/bcdata.sgs.12/dados/ultimos/1?formato=json") # CDI
cdi = response.json()[0]['valor']
response = requests.get("https://api.bcb.gov.br/dados/serie/bcdata.sgs.433/dados/ultimos/1?formato=json") # IPCA
ipca = response.json()[0]['valor']
return (f"Selic atual: {selic}% ao ano\n"
f"CDI atual: {cdi}% ao ano\n"
f"IPCA acumulado: {ipca}%")
except Exception as e:
return f"Erro ao buscar taxas de juros: {str(e)}"
@tool
def compare_fixed_income(amount: float, period: int, cdi_percentage: float) -> str:
"""
Compares the return of a CDB vs. savings over a given period.
Args:
amount: The initial investment amount.
period: The investment duration in months.
cdi_percentage: The CDB return as a percentage of the CDI.
Returns:
The final amount in CDB vs. savings.
"""
import requests
try:
# Buscar CDI atual
response = requests.get("https://api.bcb.gov.br/dados/serie/bcdata.sgs.12/dados/ultimos/1?formato=json")
cdi = float(response.json()[0]['valor']) / 100
# Poupança rende 70% da Selic quando Selic > 8.5%
response = requests.get("https://api.bcb.gov.br/dados/serie/bcdata.sgs.11/dados/ultimos/1?formato=json")
selic = float(response.json()[0]['valor']) / 100
poupanca_rendimento = 0.7 * selic if selic > 0.085 else 0.005
# Calcular rendimentos
cdb_final = amount * ((1 + (cdi * cdi_percentage / 100)) ** (period / 12))
poupanca_final = amount * ((1 + poupanca_rendimento) ** (period / 12))
return (f"Após {period} meses:\n"
f"CDB ({cdi_percentage}% do CDI): R$ {cdb_final:.2f}\n"
f"Poupança: R$ {poupanca_final:.2f}")
except Exception as e:
return f"Erro ao calcular rendimentos: {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
model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud',
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, image_generation_tool, ## add your tools here (don't remove final answer)
get_current_time_in_timezone,math_operation,
internet_search, get_stock_info,
get_stock_price, compare_stocks,
get_index_price],
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name=None,
description=None,
prompt_templates=prompt_templates
)
GradioUI(agent).launch() |