CoolFace
Apppublic

aaa77777aaa/First_agent_template

sourceHugging Faceupdated 8mo agoView on Hugging Face
0likes
app.py152 linesDownload Raw Back to root
1from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool2import datetime3import requests4import pytz5import yaml6from tools.final_answer import FinalAnswerTool7 8from Gradio_UI import GradioUI9 10@tool11def convert_units(value: float, from_unit: str, to_unit: str) -> float:12    """13    Convertit des unités courantes (distance, masse, volume, température, vitesse).14 15    Args:16        value: Valeur à convertir.17        from_unit: Unité source (ex: "km", "m", "mi", "kg", "lb", "l", "ml", "c", "f", "km/h", "mph").18        to_unit: Unité cible (mêmes formats).19 20    Returns:21        La valeur convertie (float).22 23    Raises:24        ValueError: Si la conversion demandée n'est pas supportée.25    """26    fu = from_unit.strip().lower().replace(" ", "")27    tu = to_unit.strip().lower().replace(" ", "")28 29    # Normalisation d'alias courants30    aliases = {31        "°c": "c", "celsius": "c",32        "°f": "f", "fahrenheit": "f",33        "kmh": "km/h", "kph": "km/h",34        "ms": "m/s",35        "liter": "l", "litre": "l", "liters": "l", "litres": "l",36        "milliliter": "ml", "millilitre": "ml", "milliliters": "ml", "millilitres": "ml",37        "lbs": "lb",38        "meters": "m", "metres": "m",39    }40    fu = aliases.get(fu, fu)41    tu = aliases.get(tu, tu)42 43    # Température (non-linéaire)44    if fu == "c" and tu == "f":45        return (value * 9.0/5.0) + 32.046    if fu == "f" and tu == "c":47        return (value - 32.0) * 5.0/9.048    if fu == tu:49        return float(value)50 51    # Conversions linéaires via unité pivot52    # Distance pivot = m53    distance_to_m = {54        "mm": 0.001,55        "cm": 0.01,56        "m": 1.0,57        "km": 1000.0,58        "in": 0.0254,59        "ft": 0.3048,60        "yd": 0.9144,61        "mi": 1609.344,62    }63 64    # Masse pivot = kg65    mass_to_kg = {66        "g": 0.001,67        "kg": 1.0,68        "t": 1000.0,     # tonne métrique69        "oz": 0.028349523125,70        "lb": 0.45359237,71    }72 73    # Volume pivot = l74    volume_to_l = {75        "ml": 0.001,76        "cl": 0.01,77        "l": 1.0,78        "m3": 1000.0,79        "gal": 3.785411784,  # gallon US80    }81 82    # Vitesse pivot = m/s83    speed_to_ms = {84        "m/s": 1.0,85        "km/h": 1000.0/3600.0,86        "mph": 1609.344/3600.0,87        "kt": 1852.0/3600.0,  # knot88    }89 90    def linear_convert(value: float, fu: str, tu: str, table: dict) -> float | None:91        if fu in table and tu in table:92            pivot = value * table[fu]       # vers pivot93            return pivot / table[tu]        # pivot vers cible94        return None95 96    for table in (distance_to_m, mass_to_kg, volume_to_l, speed_to_ms):97        out = linear_convert(value, fu, tu, table)98        if out is not None:99            return float(out)100 101    raise ValueError(f"Conversion non supportée: '{from_unit}' -> '{to_unit}'")102 103 104@tool105def get_current_time_in_timezone(timezone: str) -> str:106    """A tool that fetches the current local time in a specified timezone.107    Args:108        timezone: A string representing a valid timezone (e.g., 'America/New_York').109    """110    try:111        # Create timezone object112        tz = pytz.timezone(timezone)113        # Get current time in that timezone114        local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")115        return f"The current local time in {timezone} is: {local_time}"116    except Exception as e:117        return f"Error fetching time for timezone '{timezone}': {str(e)}"118 119 120final_answer = FinalAnswerTool()121 122# 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:123# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' 124 125model = HfApiModel(126max_tokens=2096,127temperature=0.5,128model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded129custom_role_conversions=None,130)131 132 133# Import tool from Hub134image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)135 136with open("prompts.yaml", 'r') as stream:137    prompt_templates = yaml.safe_load(stream)138    139agent = CodeAgent(140    model=model,141    tools=[final_answer, convert_units, get_current_time_in_timezone], ## add your tools here (don't remove final answer)142    max_steps=6,143    verbosity_level=1,144    grammar=None,145    planning_interval=None,146    name=None,147    description=None,148    prompt_templates=prompt_templates149)150 151 152GradioUI(agent).launch()