CoolFace
Apppublic

abbiodvlp/First_agent_template

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py136 linesDownload Raw Back to root
1from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool2import datetime3import requests4import pytz5import yaml6from tools.final_answer import FinalAnswerTool7from tools.web_search import DuckDuckGoSearchTool8from tools.visit_webpage import VisitWebpageTool9 10from Gradio_UI import GradioUI11 12# Below is an example of a tool that does nothing. Amaze us with your creativity !13@tool14def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type15    #Keep this format for the description / args / args description but feel free to modify the tool16    """A tool that does nothing yet 17    Args:18        arg1: the first argument19        arg2: the second argument20    """21    return "What magic will you build ?"22 23@tool24def get_current_time_in_timezone(timezone: str) -> str:25    """A tool that fetches the current local time in a specified timezone.26    Args:27        timezone: A string representing a valid timezone (e.g., 'America/New_York').28    """29    try:30        # Create timezone object31        tz = pytz.timezone(timezone)32        # Get current time in that timezone33        local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")34        return f"The current local time in {timezone} is: {local_time}"35    except Exception as e:36        return f"Error fetching time for timezone '{timezone}': {str(e)}"37 38 39###### Test0 ######40@tool41def get_current_weather(city: str) -> str:42    """A tool that fetches current weather data for a specified city.43    Args:44        city: City name (e.g., 'Tokyo' or 'São Paulo')45    """46    try:47        # https://www.weatherapi.com48        api_key = "71358020396e429d8c6190027251902"49        base_url = "http://api.weatherapi.com/v1/current.json"50        51        # Make API request52        response = requests.get(53            f"{base_url}?key={api_key}&q={city}&aqi=no"54        )55        data = response.json()56        57        if response.status_code == 200:58            current = data["current"]59            return (60                f"Weather in {data['location']['name']}, {data['location']['country']}:\n"61                f"Temperature: {current['temp_c']}°C (Feels like {current['feelslike_c']}°C)\n"62                f"Humidity: {current['humidity']}%\n"63                f"Conditions: {current['condition']['text']}\n"64                f"Wind: {current['wind_kph']} km/h"65            )66        else:67            return f"Error: {data.get('error', {}).get('message', 'Unknown error')}"68            69    except Exception as e:70        return f"Weather check failed: {str(e)}"71 72 73final_answer = FinalAnswerTool()74visit_webpage = VisitWebpageTool()75web_search = DuckDuckGoSearchTool()76 77 78# 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:79# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' 80 81model = HfApiModel(82max_tokens=2096,83temperature=0.5,84model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded85custom_role_conversions=None,86)87 88 89 90 91#model = LiteLLMModel(92#  model_id="gemini/gemini-2.0-flash-exp",93#  max_tokens=2096,94#  temperature=0.6,95#  api_key=os.getenv("LITELLM_API_KEY")96#)97 98# ollama99# model = LiteLLMModel(100#   model_id="ollama_chat/deepseek-r1:7b",101#   max_tokens=2096,102#   temperature=0.6,103#   api_base="http://localhost:11434",104#   num_ctx=8192105# )106 107# transformer108# model = TransformersModel(109#   model_id="deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B",110#   device_map="auto",111#   torch_dtype="auto",112#   max_new_tokens=2096,113#   temperature=0.6,114# )115 116# Import tool from Hub117image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)118 119with open("prompts.yaml", 'r') as stream:120    prompt_templates = yaml.safe_load(stream)121    122agent = CodeAgent(123    model=model,124    tools=[final_answer, visit_webpage, web_search, get_current_time_in_timezone, get_current_weather], ## add your tools here (don't remove final answer)125    max_steps=6,126    verbosity_level=1,127    grammar=None,128    planning_interval=None,129    name=None,130    description=None,131    prompt_templates=prompt_templates132)133 134 135GradioUI(agent).launch()136