Spaces:
Runtime error
Runtime error
Update app.py
Browse files9 unmodified lines1011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374756 unmodified lines8283848586878889909192939495969798991001011021031041051069 unmodified lines# ✅ Initialize the Hugging Face Inference Clientclient = InferenceClient()# ✅ Custom Tool: Image Generation@tooldef generate_image(description: str) -> str:"""Generates an image based on a given text description.Args:description (str): A textual prompt describing the image to be generated.Returns:str: A URL pointing to the generated image or an error message if the generation fails."""try:model_id = "stabilityai/stable-diffusion-xl-base-1.0"result = client.text_to_image(model=model_id, prompt=description)# Ensure the result is valid and contains a URLif isinstance(result, dict) and 'url' in result:return f"Here is your generated image: {result['url']}"return "Error: Image generation failed. No URL returned."except Exception as e:return f"Error generating image: {str(e)}"# ✅ Custom Tool: Fetch Current Time in a Given Timezone@tooldef get_current_time_in_timezone(timezone: str) -> str:"""Fetches the current local time in a specified timezone.Args:timezone (str): A valid timezone string (e.g., 'America/New_York').Returns:str: The current time in the given timezone or an error message."""try:tz = pytz.timezone(timezone)local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")return f"The current local time in {timezone} is: {local_time}"except Exception as e:return f"Error fetching time for timezone '{timezone}': {str(e)}"# ✅ Dummy Tool (Modify as Needed)@tooldef my_custom_tool(arg1: str, arg2: int) -> str:"""A tool that currently does nothing. Modify to create something useful.Args:arg1 (str): The first argument.arg2 (int): The second argument.Returns:str: A placeholder response."""return "What magic will you build?"# ✅ Load the Final Answer Toolfinal_answer = FinalAnswerTool()6 unmodified linescustom_role_conversions=None,)# ✅ Load Image Generation Tool from the Hubimage_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)# ✅ Load Prompt Templateswith open("prompts.yaml", 'r') as stream:prompt_templates = yaml.safe_load(stream)# ✅ Create the AI Agent with Toolsagent = CodeAgent(model=model,tools=[final_answer, generate_image, get_current_time_in_timezone, my_custom_tool], # Added tools heremax_steps=6,verbosity_level=1,grammar=None,planning_interval=None,name=None,description=None,prompt_templates=prompt_templates)# ✅ Launch the Gradio UIGradioUI(agent).launch()9 unmodified lines1011121314151617181920212223242526272829303132333435363738394041424344454647484950516 unmodified lines5859606162636465666768697071727374759 unmodified lines# ✅ Initialize the Hugging Face Inference Clientclient = InferenceClient()# ✅ Custom Tool: Snowfall Forecast Lookup@tooldef get_snowfall_forecast(city: str, date: str) -> str:"""Fetches the expected snowfall in a given city on a specified date.Args:city (str): The name of the city (e.g., 'Denver').date (str): The date in YYYY-MM-DD format.Returns:str: The expected snowfall in centimeters or an error message."""try:# Geocode the city to get latitude & longitudegeo_url = f"https://geocoding-api.open-meteo.com/v1/search?name={city}&count=1&format=json"geo_response = requests.get(geo_url).json()if "results" not in geo_response or not geo_response["results"]:return f"Error: Unable to find location for '{city}'."latitude = geo_response["results"][0]["latitude"]longitude = geo_response["results"][0]["longitude"]# Fetch snowfall forecastweather_url = f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&daily=snowfall_sum&timezone=auto&start_date={date}&end_date={date}"weather_response = requests.get(weather_url).json()if "daily" in weather_response and "snowfall_sum" in weather_response["daily"]:snowfall = weather_response["daily"]["snowfall_sum"][0]return f"Expected snowfall in {city} on {date}: {snowfall} cm."return f"No snowfall data available for {city} on {date}."except Exception as e:return f"Error fetching snowfall forecast: {str(e)}"# ✅ Load the Final Answer Toolfinal_answer = FinalAnswerTool()6 unmodified linescustom_role_conversions=None,)# ✅ Create the AI Agent with Toolsagent = CodeAgent(model=model,tools=[final_answer, get_snowfall_forecast], # Added snowfall forecast toolmax_steps=6,verbosity_level=1,grammar=None,planning_interval=None,name="WeatherBot",description="An AI agent that fetches snowfall forecasts for any city on a given date.",)# ✅ Launch the Gradio UIGradioUI(agent).launch()
app.py+32-63