lazlog commited on
Commit
4fe6fd4
·
verified ·
1 Parent(s): 40d9ae7

add tools to find a velib

Browse files

The different tools can find the Vélib station and then obtain the number of Vélib available.

Files changed (1) hide show
  1. app.py +67 -53
app.py CHANGED
@@ -1,82 +1,97 @@
1
- from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
2
  import datetime
3
  import requests
4
  import pytz
5
  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
12
- def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
13
- #Keep this format for the description / args / args description but feel free to modify the tool
14
- """A tool that does nothing yet
15
- Args:
16
- arg1: the first argument
17
- arg2: the second argument
18
- """
19
- return "What magic will you build ?"
20
 
21
- @tool
22
- def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
23
- """A tool that converts a given amount from one currency to another using real-time exchange rates.
24
- Args:
25
- amount: The amount of money to convert.
26
- from_currency: The source currency code (e.g., 'USD', 'EUR').
27
- to_currency: The target currency code (e.g., 'JPY', 'GBP').
28
- """
29
- try:
30
- response = requests.get(f"https://api.exchangerate-api.com/v4/latest/{from_currency}")
31
- data = response.json()
32
- rate = data['rates'].get(to_currency)
33
-
34
- if rate:
35
- converted_amount = amount * rate
36
- return f"{amount} {from_currency} is approximately {converted_amount:.2f} {to_currency}."
37
- else:
38
- return f"Conversion rate from {from_currency} to {to_currency} not found."
39
- except Exception as e:
40
- return f"Error fetching exchange rates: {str(e)}"
 
 
41
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  @tool
43
- def get_current_time_in_timezone(timezone: str) -> str:
44
- """A tool that fetches the current local time in a specified timezone.
45
  Args:
46
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
47
  """
48
- try:
49
- # Create timezone object
50
- tz = pytz.timezone(timezone)
51
- # Get current time in that 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
- final_answer = FinalAnswerTool()
 
 
 
 
 
59
 
60
- # 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:
61
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
62
 
63
  model = HfApiModel(
64
- max_tokens=2096,
65
- temperature=0.5,
66
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
67
- custom_role_conversions=None,
68
  )
69
 
70
-
71
  # Import tool from Hub
72
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
73
 
74
  with open("prompts.yaml", 'r') as stream:
75
  prompt_templates = yaml.safe_load(stream)
76
-
77
  agent = CodeAgent(
78
  model=model,
79
- tools=[final_answer], ## add your tools here (don't remove final answer)
80
  max_steps=6,
81
  verbosity_level=1,
82
  grammar=None,
@@ -86,5 +101,4 @@ agent = CodeAgent(
86
  prompt_templates=prompt_templates
87
  )
88
 
89
-
90
  GradioUI(agent).launch()
 
1
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
6
  from tools.final_answer import FinalAnswerTool
7
+ from geopy.distance import geodesic # Pour le calcul des distances
8
 
9
  from Gradio_UI import GradioUI
10
 
11
+ # Fonction pour obtenir les coordonnées GPS d'une adresse
12
+ def geocode_address(address):
13
+ response = requests.get(f"https://api-adresse.data.gouv.fr/search/?q={address}")
14
+ data = response.json()
15
+ if not data['features']:
16
+ return None, None
17
+ coordinates = data['features'][0]['geometry']['coordinates']
18
+ return coordinates[1], coordinates[0] # Retourne latitude, longitude
 
 
19
 
20
+ # Fonction pour récupérer toutes les stations Vélib'
21
+ def get_stations():
22
+ response = requests.get("https://velib-metropole-opendata.smovengo.cloud/opendata/Velib_Metropole/station_information.json")
23
+ data = response.json()
24
+ return data['data']['stations']
25
+
26
+ # Trouver la station Vélib' la plus proche d'une adresse donnée
27
+ def find_nearest_station(address):
28
+ user_lat, user_lon = geocode_address(address)
29
+ if user_lat is None or user_lon is None:
30
+ return None
31
+
32
+ stations = get_stations()
33
+ min_distance = float('inf')
34
+ nearest_station = None
35
+
36
+ for station in stations:
37
+ station_coords = (station['lat'], station['lon'])
38
+ distance = geodesic((user_lat, user_lon), station_coords).meters
39
+ if distance < min_distance:
40
+ min_distance = distance
41
+ nearest_station = station
42
 
43
+ return nearest_station
44
+
45
+ # Fonction pour récupérer le statut d'une station
46
+ def get_station_status(station_id):
47
+ response = requests.get("https://velib-metropole-opendata.smovengo.cloud/opendata/Velib_Metropole/station_status.json")
48
+ data = response.json()
49
+ for station in data['data']['stations']:
50
+ if station['station_id'] == station_id:
51
+ return station
52
+ return None
53
+
54
+ # Outil final qui donne le nombre de vélos disponibles à une adresse donnée
55
  @tool
56
+ def get_bike_availability(address: str) -> str:
57
+ """A tool that fetches the number of available Velib' bikes at the nearest station to a given address.
58
  Args:
59
+ address: The address where the user wants to find a Velib' station.
60
  """
61
+ nearest_station = find_nearest_station(address)
62
+ if not nearest_station:
63
+ return "Aucune station Vélib' trouvée à proximité."
 
 
 
 
 
64
 
65
+ status = get_station_status(nearest_station['station_id'])
66
+ if not status:
67
+ return "Impossible de récupérer le statut de la station."
68
 
69
+ mechanical_bikes = status['num_bikes_available_types'][0].get('mechanical', 0)
70
+ ebikes = status['num_bikes_available_types'][1].get('ebike', 0)
71
+
72
+ return (f"🚲 Station la plus proche : {nearest_station['name']}\n"
73
+ f"🔧 Vélos mécaniques disponibles : {mechanical_bikes}\n"
74
+ f"⚡ Vélos électriques disponibles : {ebikes}")
75
 
76
+ # Ajout du tool à l'agent
77
+ final_answer = FinalAnswerTool()
78
 
79
  model = HfApiModel(
80
+ max_tokens=2096,
81
+ temperature=0.5,
82
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
83
+ custom_role_conversions=None,
84
  )
85
 
 
86
  # Import tool from Hub
87
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
88
 
89
  with open("prompts.yaml", 'r') as stream:
90
  prompt_templates = yaml.safe_load(stream)
91
+
92
  agent = CodeAgent(
93
  model=model,
94
+ tools=[final_answer, get_bike_availability], # Ajout du nouvel outil ici
95
  max_steps=6,
96
  verbosity_level=1,
97
  grammar=None,
 
101
  prompt_templates=prompt_templates
102
  )
103
 
 
104
  GradioUI(agent).launch()