Sudip Datta commited on
Commit
043de0c
·
1 Parent(s): ae7a494

init commit

Browse files
Files changed (3) hide show
  1. app.py +17 -2
  2. tools/star_in_my_sky.py +96 -0
  3. tools/visit_webpage.py +0 -45
app.py CHANGED
@@ -6,6 +6,8 @@ import yaml
6
  from tools.final_answer import FinalAnswerTool
7
 
8
  from Gradio_UI import GradioUI
 
 
9
 
10
  # Below is an example of a tool that does nothing. Amaze us with your creativity !
11
  @tool
@@ -18,6 +20,19 @@ def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return
18
  """
19
  return "What magic will you build ?"
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  @tool
22
  def get_current_time_in_timezone(timezone: str) -> str:
23
  """A tool that fetches the current local time in a specified timezone.
@@ -48,14 +63,14 @@ custom_role_conversions=None,
48
 
49
 
50
  # Import tool from Hub
51
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
52
 
53
  with open("prompts.yaml", 'r') as stream:
54
  prompt_templates = yaml.safe_load(stream)
55
 
56
  agent = CodeAgent(
57
  model=model,
58
- tools=[final_answer], ## add your tools here (don't remove final answer)
59
  max_steps=6,
60
  verbosity_level=1,
61
  grammar=None,
 
6
  from tools.final_answer import FinalAnswerTool
7
 
8
  from Gradio_UI import GradioUI
9
+ from tools.star_in_my_sky import get_star_visibility
10
+
11
 
12
  # Below is an example of a tool that does nothing. Amaze us with your creativity !
13
  @tool
 
20
  """
21
  return "What magic will you build ?"
22
 
23
+ @tool
24
+ def is_star_in_my_sky(star_name: str, location_name: str) -> str:
25
+ """A tool that checks if a star is currently visible in the sky at a given location.
26
+ Args:
27
+ star_name: The name of the star to check.
28
+ location_name: The location to check. e.g. London, UK
29
+ """
30
+ try:
31
+ resp = get_star_visibility(star_name, location_name)
32
+ except Exception as e:
33
+ return f"Error: {str(e)}"
34
+ return resp
35
+
36
  @tool
37
  def get_current_time_in_timezone(timezone: str) -> str:
38
  """A tool that fetches the current local time in a specified timezone.
 
63
 
64
 
65
  # Import tool from Hub
66
+ # image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
67
 
68
  with open("prompts.yaml", 'r') as stream:
69
  prompt_templates = yaml.safe_load(stream)
70
 
71
  agent = CodeAgent(
72
  model=model,
73
+ tools=[final_answer, is_star_in_my_sky], ## add your tools here (don't remove final answer)
74
  max_steps=6,
75
  verbosity_level=1,
76
  grammar=None,
tools/star_in_my_sky.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from astroquery.simbad import Simbad
2
+ from astropy.coordinates import SkyCoord
3
+ from astropy import units as u
4
+
5
+ from geopy.geocoders import Nominatim
6
+
7
+ from skyfield.api import load, Topos, Star
8
+ from smolagents import Tool
9
+
10
+ # Make sure RA/DEC fields are included in SIMBAD query
11
+ Simbad.add_votable_fields("ra", "dec")
12
+
13
+ class StarInMySkyTool(Tool):
14
+ name = "star_in_my_sky"
15
+ description = (
16
+ "Checks if a star is currently visible in the sky at a given location."
17
+ "This tool expects two arguments: the name of the star and the location in English."
18
+ )
19
+ inputs = {
20
+ "star_name": {"type": "string", "description": "The name of the star to check."},
21
+ "location_name": {"type": "string", "description": "The location to check. e.g. London, UK"},
22
+ }
23
+ output_type = "string"
24
+
25
+ def forward(self, star_name: str, location_name: str) -> str:
26
+ try:
27
+ resp = get_star_visibility(star_name, location_name)
28
+ except Exception as e:
29
+ return f"Error: {str(e)}"
30
+ return resp
31
+
32
+ def get_coordinates_from_location(location_name):
33
+ """Use geopy to convert a place name into latitude/longitude."""
34
+ geolocator = Nominatim(user_agent="astrogeo")
35
+ location = geolocator.geocode(location_name)
36
+ if not location:
37
+ raise ValueError(f"Could not geocode location: {location_name}")
38
+ return location.latitude, location.longitude
39
+
40
+
41
+ def get_star_visibility(star_name, location_name):
42
+ """
43
+ 1. Convert a location name to lat/long.
44
+ 2. Query SIMBAD for star's RA/Dec.
45
+ 3. Compute altitude/azimuth via Skyfield.
46
+ 4. Print whether the star is above or below the horizon.
47
+ """
48
+ # 1. Get lat/long from location name
49
+ latitude, longitude = get_coordinates_from_location(location_name)
50
+ print(f"Location '{location_name}': lat={latitude:.4f}, lon={longitude:.4f}")
51
+
52
+ # 2. Query SIMBAD for the star's RA/DEC
53
+ result_table = Simbad.query_object(star_name)
54
+ if result_table is None:
55
+ print(f"Could not find star '{star_name}' in SIMBAD.")
56
+ return
57
+
58
+ if "ra" not in result_table.colnames or "dec" not in result_table.colnames:
59
+ print("The 'ra'/'dec' columns are missing in SIMBAD’s response!")
60
+ return
61
+
62
+ ra_str = result_table["ra"][0] # e.g. '06 45 08.92'
63
+ dec_str = result_table["dec"][0] # e.g. '-16 42 58.0'
64
+
65
+ # Convert RA/DEC to numeric values using Astropy
66
+ skycoord = SkyCoord(ra_str, dec_str, unit=(u.hourangle, u.deg))
67
+
68
+ # 3. Create a Skyfield Star object
69
+ star = Star(ra_hours=skycoord.ra.hour, dec_degrees=skycoord.dec.degree)
70
+
71
+ # 4. Load ephemeris, define observer, compute alt/az for now
72
+ ts = load.timescale()
73
+ t = ts.now()
74
+
75
+ planets = load("de421.bsp")
76
+ earth = planets["earth"]
77
+ observer = Topos(latitude_degrees=latitude, longitude_degrees=longitude)
78
+
79
+ # Calculate altitude, azimuth
80
+ alt, az, distance = (earth + observer).at(t).observe(star).apparent().altaz()
81
+
82
+ resp = ""
83
+ # 5. Print results
84
+ if alt.degrees > 0:
85
+ resp = f"""
86
+ Star '{star_name}' is above the horizon at {location_name} (NOW).
87
+ Altitude: {alt.degrees:.2f}°, Azimuth: {az.degrees:.2f}°
88
+ """
89
+ else:
90
+ resp = f"\nStar '{star_name}' is below the horizon at {location_name} (NOW)."
91
+ return resp
92
+
93
+
94
+ if __name__ == "__main__":
95
+ # Example: London
96
+ get_star_visibility("Sirius", "London, UK")
tools/visit_webpage.py DELETED
@@ -1,45 +0,0 @@
1
- from typing import Any, Optional
2
- from smolagents.tools import Tool
3
- import requests
4
- import markdownify
5
- import smolagents
6
-
7
- class VisitWebpageTool(Tool):
8
- name = "visit_webpage"
9
- description = "Visits a webpage at the given url and reads its content as a markdown string. Use this to browse webpages."
10
- inputs = {'url': {'type': 'string', 'description': 'The url of the webpage to visit.'}}
11
- output_type = "string"
12
-
13
- def forward(self, url: str) -> str:
14
- try:
15
- import requests
16
- from markdownify import markdownify
17
- from requests.exceptions import RequestException
18
-
19
- from smolagents.utils import truncate_content
20
- except ImportError as e:
21
- raise ImportError(
22
- "You must install packages `markdownify` and `requests` to run this tool: for instance run `pip install markdownify requests`."
23
- ) from e
24
- try:
25
- # Send a GET request to the URL with a 20-second timeout
26
- response = requests.get(url, timeout=20)
27
- response.raise_for_status() # Raise an exception for bad status codes
28
-
29
- # Convert the HTML content to Markdown
30
- markdown_content = markdownify(response.text).strip()
31
-
32
- # Remove multiple line breaks
33
- markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)
34
-
35
- return truncate_content(markdown_content, 10000)
36
-
37
- except requests.exceptions.Timeout:
38
- return "The request timed out. Please try again later or check the URL."
39
- except RequestException as e:
40
- return f"Error fetching the webpage: {str(e)}"
41
- except Exception as e:
42
- return f"An unexpected error occurred: {str(e)}"
43
-
44
- def __init__(self, *args, **kwargs):
45
- self.is_initialized = False