paulofroes commited on
Commit
e2d8145
·
verified ·
1 Parent(s): 818e7df

Removing class structure

Browse files
Files changed (1) hide show
  1. tools/cheapest_flight.py +79 -109
tools/cheapest_flight.py CHANGED
@@ -1,109 +1,79 @@
1
- import http.client
2
- import pandas as pd
3
- import numpy as np
4
- import json
5
- from smolagents.tools import Tool
6
-
7
- class GetCheapestFlightTool(Tool):
8
-
9
- name = "cheapest_flight_tool"
10
- description = "Return the cheapest flight"
11
- inputs = {
12
- 'departureId': {'type': 'string', 'description': 'The ID in which the airport of the departure location is.'},
13
- 'arrivalId': {'type': 'string', 'description': 'The ID in which the airport of the arrival location is.'},
14
- 'departureDate': {'type': 'string', 'description': 'the date to look for the cheapest flight.'}, }
15
- output_type = "dict"
16
-
17
- def get_flight(departureId, arrivalId, departureDate):
18
-
19
- conn = http.client.HTTPSConnection("booking-com15.p.rapidapi.com")
20
-
21
- headers = {
22
- 'x-rapidapi-key': "RAPIDAPI_KEY", #Replace with your own RapidAPI key
23
- 'x-rapidapi-host': "booking-com15.p.rapidapi.com"
24
- }
25
-
26
- conn.request("GET", f"/api/v1/flights/searchFlights?fromId={departureId}.AIRPORT&toId={arrivalId}.AIRPORT&departDate={departureDate}&currency_code=BRL", headers=headers)
27
-
28
- res = conn.getresponse()
29
- data = res.read()
30
- json_data = json.loads(data.decode("utf-8"))
31
-
32
- try:
33
- # Get all flight offers with validation
34
- if not json_data or 'data' not in json_data or 'flightOffers' not in json_data['data']:
35
- return None
36
- flight_offers = json_data['data']['flightOffers']
37
-
38
- if not flight_offers:
39
- return None
40
-
41
- # Initialize variables to track cheapest flight
42
- cheapest_price = float('inf')
43
- cheapest_flight = None
44
-
45
- # Loop through each flight offer
46
- for offer in flight_offers:
47
- try:
48
- # Validate price breakdown structure
49
- if ('priceBreakdown' not in offer or
50
- 'total' not in offer['priceBreakdown'] or
51
- 'units' not in offer['priceBreakdown']['total']):
52
- print('a estrutura está correta')
53
- continue
54
-
55
- # Get total price in units
56
- price = float(offer['priceBreakdown']['total']['units'])
57
-
58
- # Add nanos (decimal part) if present
59
- if 'nanos' in offer['priceBreakdown']['total']:
60
- price += float(offer['priceBreakdown']['total']['nanos']) / 1000000000
61
-
62
- # Update cheapest if current price is lower
63
- if price < cheapest_price:
64
- cheapest_price = price
65
- cheapest_flight = offer
66
-
67
- except (ValueError, TypeError):
68
- continue
69
-
70
- # Extract relevant info from cheapest flight
71
- if cheapest_flight:
72
- try:
73
- result = {
74
- 'price': f"{cheapest_flight['priceBreakdown']['total'].get('currencyCode', 'USD')} {cheapest_price:.2f}",
75
- 'departure': {
76
- 'from': cheapest_flight['segments'][0]['departureAirport'].get('cityName', 'Unknown'),
77
- 'time': cheapest_flight['segments'][0].get('departureTime', 'Unknown')
78
- },
79
- 'arrival': {
80
- 'to': cheapest_flight['segments'][0]['arrivalAirport'].get('cityName', 'Unknown'),
81
- 'time': cheapest_flight['segments'][0].get('arrivalTime', 'Unknown')
82
- },
83
- 'airline': cheapest_flight['segments'][0]['legs'][0]['carriersData'][0].get('name', 'Unknown')
84
- }
85
- return result
86
- except (KeyError, IndexError):
87
- return None
88
- return None
89
-
90
- except Exception:
91
- return None
92
-
93
- if __name__ == "__main__":
94
-
95
- tool = GetCheapestFlightTool()
96
-
97
- departureId = "BOM"
98
- arrivalId = "DEL"
99
- departureDate = '2025-03-16'
100
-
101
- cheapest = tool.get_flight(departureId, arrivalId, departureDate)
102
- print(f"""
103
- Cheapest Flight Details:
104
- Price: {cheapest['price']}
105
- From: {cheapest['departure']['from']} at {cheapest['departure']['time']}
106
- To: {cheapest['arrival']['to']} at {cheapest['arrival']['time']}
107
- Airline: {cheapest['airline']}
108
- """
109
- )
 
1
+ import http.client
2
+ import pandas as pd
3
+ import numpy as np
4
+ import json
5
+ from smolagents.tools import Tool
6
+
7
+
8
+
9
+ def get_flight(departureId, arrivalId, departureDate):
10
+
11
+ conn = http.client.HTTPSConnection("booking-com15.p.rapidapi.com")
12
+
13
+ headers = {
14
+ 'x-rapidapi-key': "RAPIDAPI_KEY", #Replace with your own RapidAPI key
15
+ 'x-rapidapi-host': "booking-com15.p.rapidapi.com"
16
+ }
17
+
18
+ conn.request("GET", f"/api/v1/flights/searchFlights?fromId={departureId}.AIRPORT&toId={arrivalId}.AIRPORT&departDate={departureDate}&currency_code=BRL", headers=headers)
19
+
20
+ res = conn.getresponse()
21
+ data = res.read()
22
+ json_data = json.loads(data.decode("utf-8"))
23
+
24
+ try:
25
+ # Get all flight offers with validation
26
+ if not json_data or 'data' not in json_data or 'flightOffers' not in json_data['data']:
27
+ return None
28
+
29
+ flight_offers = json_data['data']['flightOffers']
30
+
31
+ if not flight_offers:
32
+ return None
33
+
34
+ # Initialize variables to track cheapest flight
35
+ cheapest_price = float('inf')
36
+ cheapest_flight = None
37
+
38
+ # Loop through each flight offer
39
+ for offer in flight_offers:
40
+ try:
41
+ # Validate price breakdown structure
42
+ if ('priceBreakdown' not in offer or
43
+ 'total' not in offer['priceBreakdown'] or
44
+ 'units' not in offer['priceBreakdown']['total']):
45
+ print('a estrutura está correta')
46
+ continue
47
+ # Get total price in units
48
+ price = float(offer['priceBreakdown']['total']['units'])
49
+ # Add nanos (decimal part) if present
50
+ if 'nanos' in offer['priceBreakdown']['total']:
51
+ price += float(offer['priceBreakdown']['total']['nanos']) / 1000000000
52
+ # Update cheapest if current price is lower
53
+ if price < cheapest_price:
54
+ cheapest_price = price
55
+ cheapest_flight = offer
56
+ except (ValueError, TypeError):
57
+ continue
58
+
59
+ # Extract relevant info from cheapest flight
60
+ if cheapest_flight:
61
+ try:
62
+ result = {
63
+ 'price': f"{cheapest_flight['priceBreakdown']['total'].get('currencyCode', 'USD')} {cheapest_price:.2f}",
64
+ 'departure': {
65
+ 'from': cheapest_flight['segments'][0]['departureAirport'].get('cityName', 'Unknown'),
66
+ 'time': cheapest_flight['segments'][0].get('departureTime', 'Unknown')
67
+ },
68
+ 'arrival': {
69
+ 'to': cheapest_flight['segments'][0]['arrivalAirport'].get('cityName', 'Unknown'),
70
+ 'time': cheapest_flight['segments'][0].get('arrivalTime', 'Unknown')
71
+ },
72
+ 'airline': cheapest_flight['segments'][0]['legs'][0]['carriersData'][0].get('name', 'Unknown')
73
+ }
74
+ return result
75
+ except (KeyError, IndexError):
76
+ return None
77
+ return None
78
+ except Exception:
79
+ return None