DemoAgent / app.py
sabonzo's picture
Update app.py
9b679a6 verified
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool, OpenAIServerModel
import datetime
import requests
import pytz
import base64
import yaml
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI
from typing import Dict, List
from bs4 import BeautifulSoup
import os
apikey = os.getenv("OPENAI_API_KEY")
@tool
def get_exchange_rate(base_currency: str, target_currency: str) -> float:
"""A tool that fetches the current exchange rate between two currencies.
Args:
base_currency: The currency you want to convert from (e.g., 'USD').
target_currency: The currency you want to convert to (e.g., 'EUR').
"""
try:
url = f"https://api.exchangerate-api.com/v4/latest/{base_currency}"
response = requests.get(url)
data = response.json()
if response.status_code == 200 and target_currency in data['rates']:
rate = data['rates'][target_currency]
return float(rate)
else:
return 0.0
except Exception as e:
return 0.0
@tool
def get_spot_price(crypto:str, fiat:str) -> float:
"""
Retrieve the current spot price for a specified cryptocurrency in a given fiat currency using Coinbase's API. This function is designed as a tool for an AI agent to fetch real-time cryptocurrency prices.
Args:
crypto: The cryptocurrency symbol (e.g., "BTC", "ETH"). Defaults to "BTC".
fiat: The fiat currency symbol (e.g., "USD", "EUR"). Defaults to "USD".
Returns:
float: The spot price as returned by the API.
"""
url = f"https://api.coinbase.com/v2/prices/{crypto}-{fiat}/spot"
response = requests.get(url)
response.raise_for_status() # raises an exception for 4XX/5XX errors
data = response.json()
return float(data["data"]["amount"])
@tool
def get_exchange_rates(currency: str = "BTC") -> Dict[str, str]:
"""
Retrieves current exchange rates for a given currency from Coinbase.
Args:
currency: The base currency code (e.g., "BTC", "ETH", "USD"). Defaults to "BTC".
Returns:
A dictionary containing exchange rates with currency codes as keys and their corresponding rates as values.
"""
url = f"https://api.coinbase.com/v2/exchange-rates?currency={currency}"
response = requests.get(url)
response.raise_for_status()
return response.json()["data"]["rates"]
@tool
def get_supported_currencies() -> List[Dict[str, str]]:
"""
Retrieves a list of all supported currencies from Coinbase.
Args:
None
Returns:
A list of dictionaries, where each dictionary contains a currency code and its corresponding name.
"""
url = "https://api.coinbase.com/v2/currencies"
response = requests.get(url)
response.raise_for_status()
return response.json()["data"]
final_answer = FinalAnswerTool()
"""
model = HfApiModel(
max_tokens=2096,
temperature=0.5,
model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud', #meta-llama/Meta-Llama-3-8B-Instruct
custom_role_conversions=None,
)
"""
model = OpenAIServerModel(
max_tokens=2096,
temperature=0.5,
model_id="gpt-4o-mini",
api_key= apikey,
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, get_exchange_rate, get_spot_price, get_supported_currencies, get_exchange_rates],
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name=None,
description=None,
prompt_templates=prompt_templates
)
GradioUI(agent).launch()