DenverJones commited on
Commit
b2d2226
·
verified ·
1 Parent(s): 3193a06

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -63
app.py CHANGED
@@ -10,66 +10,42 @@ from Gradio_UI import GradioUI
10
  # ✅ Initialize the Hugging Face Inference Client
11
  client = InferenceClient()
12
 
13
- # ✅ Custom Tool: Image Generation
14
  @tool
15
- def generate_image(description: str) -> str:
16
  """
17
- Generates an image based on a given text description.
18
-
19
  Args:
20
- description (str): A textual prompt describing the image to be generated.
21
-
 
22
  Returns:
23
- str: A URL pointing to the generated image or an error message if the generation fails.
24
  """
25
  try:
26
- model_id = "stabilityai/stable-diffusion-xl-base-1.0"
27
- result = client.text_to_image(model=model_id, prompt=description)
28
-
29
- # Ensure the result is valid and contains a URL
30
- if isinstance(result, dict) and 'url' in result:
31
- return f"Here is your generated image: {result['url']}"
32
- return "Error: Image generation failed. No URL returned."
33
-
34
- except Exception as e:
35
- return f"Error generating image: {str(e)}"
36
-
37
-
38
- # ✅ Custom Tool: Fetch Current Time in a Given Timezone
39
- @tool
40
- def get_current_time_in_timezone(timezone: str) -> str:
41
- """
42
- Fetches the current local time in a specified timezone.
43
-
44
- Args:
45
- timezone (str): A valid timezone string (e.g., 'America/New_York').
46
 
47
- Returns:
48
- str: The current time in the given timezone or an error message.
49
- """
50
- try:
51
- tz = pytz.timezone(timezone)
52
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
53
- return f"The current local time in {timezone} is: {local_time}"
54
  except Exception as e:
55
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
56
-
57
-
58
- # ✅ Dummy Tool (Modify as Needed)
59
- @tool
60
- def my_custom_tool(arg1: str, arg2: int) -> str:
61
- """
62
- A tool that currently does nothing. Modify to create something useful.
63
-
64
- Args:
65
- arg1 (str): The first argument.
66
- arg2 (int): The second argument.
67
-
68
- Returns:
69
- str: A placeholder response.
70
- """
71
- return "What magic will you build?"
72
-
73
 
74
  # ✅ Load the Final Answer Tool
75
  final_answer = FinalAnswerTool()
@@ -82,25 +58,18 @@ model = HfApiModel(
82
  custom_role_conversions=None,
83
  )
84
 
85
- # ✅ Load Image Generation Tool from the Hub
86
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
87
-
88
- # ✅ Load Prompt Templates
89
- with open("prompts.yaml", 'r') as stream:
90
- prompt_templates = yaml.safe_load(stream)
91
-
92
  # ✅ Create the AI Agent with Tools
93
  agent = CodeAgent(
94
  model=model,
95
- tools=[final_answer, generate_image, get_current_time_in_timezone, my_custom_tool], # Added tools here
96
  max_steps=6,
97
  verbosity_level=1,
98
  grammar=None,
99
  planning_interval=None,
100
- name=None,
101
- description=None,
102
- prompt_templates=prompt_templates
103
  )
104
 
105
  # ✅ Launch the Gradio UI
106
  GradioUI(agent).launch()
 
 
10
  # ✅ Initialize the Hugging Face Inference Client
11
  client = InferenceClient()
12
 
13
+ # ✅ Custom Tool: Snowfall Forecast Lookup
14
  @tool
15
+ def get_snowfall_forecast(city: str, date: str) -> str:
16
  """
17
+ Fetches the expected snowfall in a given city on a specified date.
18
+
19
  Args:
20
+ city (str): The name of the city (e.g., 'Denver').
21
+ date (str): The date in YYYY-MM-DD format.
22
+
23
  Returns:
24
+ str: The expected snowfall in centimeters or an error message.
25
  """
26
  try:
27
+ # Geocode the city to get latitude & longitude
28
+ geo_url = f"https://geocoding-api.open-meteo.com/v1/search?name={city}&count=1&format=json"
29
+ geo_response = requests.get(geo_url).json()
30
+
31
+ if "results" not in geo_response or not geo_response["results"]:
32
+ return f"Error: Unable to find location for '{city}'."
33
+
34
+ latitude = geo_response["results"][0]["latitude"]
35
+ longitude = geo_response["results"][0]["longitude"]
36
+
37
+ # Fetch snowfall forecast
38
+ weather_url = f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&daily=snowfall_sum&timezone=auto&start_date={date}&end_date={date}"
39
+ weather_response = requests.get(weather_url).json()
40
+
41
+ if "daily" in weather_response and "snowfall_sum" in weather_response["daily"]:
42
+ snowfall = weather_response["daily"]["snowfall_sum"][0]
43
+ return f"Expected snowfall in {city} on {date}: {snowfall} cm."
44
+
45
+ return f"No snowfall data available for {city} on {date}."
 
46
 
 
 
 
 
 
 
 
47
  except Exception as e:
48
+ return f"Error fetching snowfall forecast: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
  # ✅ Load the Final Answer Tool
51
  final_answer = FinalAnswerTool()
 
58
  custom_role_conversions=None,
59
  )
60
 
 
 
 
 
 
 
 
61
  # ✅ Create the AI Agent with Tools
62
  agent = CodeAgent(
63
  model=model,
64
+ tools=[final_answer, get_snowfall_forecast], # Added snowfall forecast tool
65
  max_steps=6,
66
  verbosity_level=1,
67
  grammar=None,
68
  planning_interval=None,
69
+ name="WeatherBot",
70
+ description="An AI agent that fetches snowfall forecasts for any city on a given date.",
 
71
  )
72
 
73
  # ✅ Launch the Gradio UI
74
  GradioUI(agent).launch()
75
+