paulofroes commited on
Commit
3ec4242
·
verified ·
1 Parent(s): ae7a494

Upload cheapest_flight.py

Browse files
Files changed (1) hide show
  1. tools/cheapest_flight.py +109 -0
tools/cheapest_flight.py ADDED
@@ -0,0 +1,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
+ 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
+ )