CoolFace
Apppublic

wphoenix/Crypto_Market_Data_Agent

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py175 linesDownload Raw Back to root
1from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool2import datetime3import requests4import pytz5import yaml6from tools.final_answer import FinalAnswerTool7#from requests import Request, Session8from requests.exceptions import ConnectionError, Timeout, TooManyRedirects9import json10from typing import Dict, Any, Optional, List11 12from Gradio_UI import GradioUI13 14verbose = True15if verbose: print("Running app.py")16 17#################################### TOOLS ###############################################18 19# Below is an example of a tool that does nothing. Amaze us with your creativity !20@tool21def my_custom_tool(arg1:str, arg2:int)-> str: #it's important to specify the return type22    #Keep this format for the description / args / args description but feel free to modify the tool23    """A tool that does nothing yet 24    Args:25        arg1: the first argument26        arg2: the second argument27    """28    return "What magic will you build ?"29 30@tool31def fetch_active_crypto(currency: str = 'USD', chunk_size: int = 100) -> Optional[List[Dict[str, Any]]]:32    """A tool that fetches and reverse sorts by market_cap all active crypto in currency.33    Args:34        currency: A string representing the currency the value is returned in (default: 'USD').35        chunk_size: The number of cryptocurrencies to process in each chunk (default: 100).36    Returns:37        Optional[List[Dict[str, Any]]]: A list of dictionaries containing the top cryptocurrencies by market cap,38                                        chunked into smaller pieces, or None if an error occurs.39    """40    url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'41    parameters = {42        'start': '1',43        'limit': '5000',44        'convert': currency45    }46    headers = {47        'Accepts': 'application/json',48        'X-CMC_PRO_API_KEY': 'e375c697-e504-464e-b800-2b8cf9c67765',49    }50 51    session = requests.Session()52    session.headers.update(headers)53 54    try:55        response = session.get(url, params=parameters)56        response.raise_for_status()  # Raise an exception for HTTP errors57        data = json.loads(response.text)58 59        # Extract and sort cryptocurrencies by market cap60        if 'data' in data:61            sorted_crypto = sorted(data['data'], key=lambda x: x['quote'][currency]['market_cap'], reverse=True)62            63            # Chunk the sorted data into smaller pieces64            chunks = [sorted_crypto[i:i + chunk_size] for i in range(0, len(sorted_crypto), chunk_size)]65            66            # Convert each chunk into a dictionary67            result = []68            for chunk in chunks:69                chunk_dict = {crypto['name']: crypto['quote'][currency] for crypto in chunk}70                result.append(chunk_dict)71            72            return result73        else:74            print("No data found in the response.")75            return None76 77    except (ConnectionError, Timeout, TooManyRedirects, requests.exceptions.HTTPError) as e:78        print(f"An error occurred: {e}")79        return None80    81 82@tool83def get_current_time_in_timezone(timezone: str) -> str:84    """A tool that fetches the current local time in a specified timezone.85    Args:86        timezone: A string representing a valid timezone (e.g., 'America/New_York').87    """88    try:89        # Create timezone object90        tz = pytz.timezone(timezone)91        # Get current time in that timezone92        local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")93        return f"The current local time in {timezone} is: {local_time}"94    except Exception as e:95        return f"Error fetching time for timezone '{timezone}': {str(e)}"96 97 98final_answer = FinalAnswerTool()99 100########################################## MODEL SELECTION ################################################101 102MODEL_IDS = [103    'Qwen/Qwen2.5-Coder-14B-Instruct',104    'Qwen/Qwen2.5-Coder-3B-Instruct',105    'Qwen/Qwen2.5-Coder-7B-Instruct',106    'Qwen/Qwen2.5-Coder-32B-Instruct',107    'Qwen/Qwen2.5-Coder-1.5B-Instruct'108    #'https://wxknx1kg971u7k1n.us-east-1.aws.endpoints.huggingface.cloud/',109    #'https://jc26mwg228mkj8dw.us-east-1.aws.endpoints.huggingface.cloud/', 110    # 'https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'111    #'meta-llama/Llama-3.2-1B-Instruct', ## Does a poor job of interpreting my questions and matching them to the tools112    # Add here wherever model is working for you113]114 115def is_model_overloaded(model_url):116    """Verify if the model is overloaded doing a test call."""117    try:118        response = requests.post(model_url, json={"inputs": "Test"})119        if verbose: 120            print(response.status_code)121        if response.status_code == 503:  # 503 Service Unavailable = Overloaded122            return True123        if response.status_code == 404:  # 404 Client Error: Not Found 124            return True125        if response.status_code == 424:  # 424 Client Error: Failed Dependency for url:126            return True127        return False128    except requests.RequestException:129        return True  # if there are an error is overloaded130 131def get_available_model():132    """Select the first model available from the list."""133    for model_url in MODEL_IDS:134        print("trying",model_url)135        if not is_model_overloaded(model_url):136            return model_url137    return MODEL_IDS[0]  # if all are failing, use the first model by dfault138 139if verbose: print("Checking available models.")140selected_model_id = get_available_model()141if verbose: print(f"Selected: {selected_model_id}")142 143model = HfApiModel(144    max_tokens=1048,145    temperature=0.5,146    #model_id='meta-llama/Llama-3.2-1B-Instruct',147    #model_id='Qwen/Qwen2.5-Coder-32B-Instruct',148    #model_id = 'Qwen/Qwen2.5-Coder-1.5B-Instruct',    149    model_id = selected_model_id, # model available selected from the list automatically150    custom_role_conversions=None,151)152 153 154################################## AGENT SETUP ################################################155 156# Import tool from Hub157image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)158 159with open("prompts.yaml", 'r') as stream:160    prompt_templates = yaml.safe_load(stream)161    162agent = CodeAgent(163    model=model,164    tools=[final_answer, image_generation_tool, get_current_time_in_timezone, fetch_active_crypto], ## add your tools here (don't remove final answer)165    max_steps=6,166    verbosity_level=1,167    grammar=None,168    planning_interval=None,169    name=None,170    description=None,171    prompt_templates=prompt_templates172)173 174 175GradioUI(agent).launch()