Hi Everyone,
I’m at the end of Unit 1 Agents Course where you build your first agent. Can someone please help me fix my code for crypto token pricing? I’ve been stuck for a couple days attempting to fix running errors. The current problem now is in line 17: args for currency…I have used ‘usd’ & int in args, but I get errors with each one.
Here is code:
from smolagents import tool
import requests
import pandas as pd
Below is an example of a tool that does nothing. Amaze us with your creativity !
@tool
def my_custom_tool(arg1:str, arg2:int): str #it’s important to specify the return type
#Keep this format for the description / args / args description but feel free to modify the tool
“”"A tool that does nothing yet
Args:
arg1: the first argument
arg2: the second argument
“”"
# re@toolurn
@tool
Function to get current prices of specified cryptocurrencies
def get_crypto_prices(crypto_ids: str, currency=‘usd’):
“”"This is a tool to get current crypto token market prices in usd currency using the coingecko api.
Args:
args1: crypto_ids= Input for crypto_ids is a string
args2: currency= Output for currency is an integer
Responses:
You should return all valid requests with the crypto id, and its current price in usd denominations.
"""
url = f"https://api.coingecko.com/api/v3/simple/price?ids={','.join(crypto_ids)}&vs_currencies={currency}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
return pd.DataFrame(data).T # Transpose for better readability
else:
print("Failed to retrieve data")
return None
Specify the cryptocurrencies you want to check
cryptos = [‘bitcoin’, ‘ethereum’, ‘ripple’]
Get current prices
prices = get_crypto_prices(cryptos)
print(prices)
I would appreciate any insight to help me improve…Please, and Thank you!!!
1 Like
It seems possible that the data type of the argument passed to the API is incorrect.
Your error comes from two things: wrong type for currency
and several syntax issues. vs_currencies
in CoinGecko’s Simple Price API must be a string like "usd"
, not an int. The @tool
function must have proper type hints, a real docstring, and no stray text between @tool
and def
. (CoinGecko API) (Hugging Face)
Use this cleaned version:
from smolagents import tool
import requests
import pandas as pd
@tool
def my_custom_tool(arg1: str, arg2: int) -> str:
"""A placeholder tool that simply echoes its inputs.
Args:
arg1: The first argument.
arg2: The second argument.
Returns:
A short status string.
"""
return f"arg1={arg1}, arg2={arg2}"
@tool
def get_crypto_prices(crypto_ids: list[str], currency: str = "usd") -> dict:
"""Get current crypto prices using CoinGecko Simple Price.
Args:
crypto_ids: List of CoinGecko coin IDs, e.g. ["bitcoin","ethereum","ripple"].
currency: Fiat currency code, e.g. "usd".
Returns:
Dict mapping coin_id -> price in the requested currency.
"""
if not crypto_ids:
return {"error": "crypto_ids must be a non-empty list"}
url = "https://api.coingecko.com/api/v3/simple/price"
params = {"ids": ",".join(crypto_ids), "vs_currencies": currency.lower()}
try:
r = requests.get(url, params=params, timeout=10)
r.raise_for_status()
except Exception as e:
return {"error": f"request failed: {e}"}
data = r.json() # shape: {"bitcoin":{"usd":12345.6}, ...}
# flatten to { "bitcoin": 12345.6, ... }
return {coin: payload.get(currency.lower()) for coin, payload in data.items()}
# Example usage outside the agent:
cryptos = ["bitcoin", "ethereum", "ripple"]
prices = get_crypto_prices(cryptos, currency="usd")
print(prices)
# Optional: nice tabular view for humans
df = pd.DataFrame.from_dict(prices, orient="index", columns=["usd"])
print(df)
Why this fixes it:
currency
is typed as str
with default "usd"
, matching CoinGecko’s API. (CoinGecko API)
crypto_ids
is a list[str]
since you join
it for the query. (CoinGecko API)
- Proper
@tool
usage with type hints and a real docstring, as shown in the course docs. (Hugging Face)
- Removed smart quotes and stray text that caused syntax errors.
Notes:
- Use valid CoinGecko coin IDs (e.g.,
"bitcoin"
, "ethereum"
, "ripple"
). (CoinGecko API)
- If you ever need token prices by contract address instead, use the token-address endpoint. (CoinGecko API)
- Expect caching and rate limits; don’t call this in tight loops. (CoinGecko)
References and examples:
Thank You, very much!!! I was on coingecko api page studying, and attempting to re-work the api calling format…but your valuable input will help me get pass initial running time errors.
Thanks A Lot!!!
1 Like