1- import ollama
2- import numpy as np
3- from sklearn .metrics .pairwise import cosine_similarity
1+ import requests
42
5- flights = [
6- {
7- "flight_number" : "NY100" ,
8- "origin" : "New York" ,
9- "destination" : "London" ,
10- "time" : "2025-05-01 08:00" ,
11- "airline" : "Global Airways"
12- },
13- {
14- "flight_number" : "LA200" ,
15- "origin" : "Los Angeles" ,
16- "destination" : "Tokyo" ,
17- "time" : "2025-05-01 10:30" ,
18- "airline" : "Pacific Routes"
19- },
20- {
21- "flight_number" : "CH300" ,
22- "origin" : "Chicago" ,
23- "destination" : "Paris" ,
24- "time" : "2025-05-01 15:45" ,
25- "airline" : "Euro Connect"
26- },
27- {
28- "flight_number" : "SF400" ,
29- "origin" : "San Francisco" ,
30- "destination" : "Sydney" ,
31- "time" : "2025-05-01 23:15" ,
32- "airline" : "Ocean Pacific"
33- },
34- {
35- "flight_number" : "MI500" ,
36- "origin" : "Miami" ,
37- "destination" : "Rio de Janeiro" ,
38- "time" : "2025-05-02 07:30" ,
39- "airline" : "South American Airways"
40- }
41- ]
42-
43- ### ✅ Check if Ollama is Running Before Sending API Calls
443def check_ollama_availability ():
45- """
46- Check if Ollama server is available.
47- Returns: True if available, False otherwise.
48- """
49- import requests
4+ """Check if the Ollama server is available."""
505 try :
516 response = requests .get ("http://localhost:11434/api/tags" , timeout = 3 )
527 return response .status_code == 200
53- except requests .exceptions .RequestException :
8+ except requests .RequestException :
9+ print ("⚠️ Ollama server is not available." )
5410 return False
5511
56- OLLAMA_AVAILABLE = check_ollama_availability ()
57-
58- ### ✅ Lazy Embedding Generation with Error Handling
59- flight_embeddings = {}
60-
61- def generate_embedding (text ):
62- """
63- Generate text embeddings using Ollama's LLaMA2 API.
64- Only calls Ollama if the server is running.
65- """
66- if not OLLAMA_AVAILABLE :
67- print ("⚠️ Ollama server is not available. Using fallback search." )
68- return None
69-
70- try :
71- response = ollama .embeddings (model = "llama2:latest" , prompt = text )
72- return np .array (response ["embedding" ])
73- except Exception as e :
74- print (f"⚠️ Ollama embedding failed: { e } " )
75- return None
76-
77- def get_flight_embedding (flight_number ):
78- """
79- Retrieve or generate an embedding for a flight.
80- """
81- if flight_number in flight_embeddings :
82- return flight_embeddings [flight_number ]
83-
84- # Get flight details
85- flight = next ((f for f in flights if f ["flight_number" ] == flight_number ), None )
86- if not flight :
87- return None
88-
89- text = f"{ flight ['origin' ]} { flight ['destination' ]} { flight ['airline' ]} { flight ['time' ]} "
90- embedding = generate_embedding (text )
91- if embedding is not None :
92- flight_embeddings [flight_number ] = embedding
93- return embedding
9412
95- def search_flights_semantic (query ):
96- """
97- Perform semantic search on flight records using cosine similarity.
98- """
99- print (f"🟢 Searching flights for: { query } " ) # Debug print
100-
101- try :
102- query_embedding = generate_embedding (query )
103-
104- similarities = {}
105- for flight in flights :
106- flight_num = flight ["flight_number" ]
107- flight_embedding = get_flight_embedding (flight_num )
108-
109- if flight_embedding is not None :
110- similarity_score = cosine_similarity ([query_embedding ], [flight_embedding ])[0 ][0 ]
111- similarities [flight_num ] = similarity_score
112-
113- matching_flights = [flight for flight in flights if similarities .get (flight ["flight_number" ], 0 ) > 0.6 ]
114-
115- print (f"🟢 Flights Found: { matching_flights } " ) # Debug print
116-
117- return matching_flights
13+ # Mock database: list of flights
14+ flights = [
15+ {"flight_number" : "NY100" , "origin" : "New York" , "destination" : "London" , "time" : "2025-05-01 08:00" , "airline" : "Global Airways" },
16+ {"flight_number" : "LA200" , "origin" : "Los Angeles" , "destination" : "Tokyo" , "time" : "2025-05-01 10:30" , "airline" : "Pacific Routes" },
17+ {"flight_number" : "CH300" , "origin" : "Chicago" , "destination" : "Paris" , "time" : "2025-05-01 15:45" , "airline" : "Euro Connect" },
18+ {"flight_number" : "SF400" , "origin" : "San Francisco" , "destination" : "Sydney" , "time" : "2025-05-01 23:15" , "airline" : "Ocean Pacific" },
19+ {"flight_number" : "MI500" , "origin" : "Miami" , "destination" : "Rio de Janeiro" , "time" : "2025-05-02 07:30" , "airline" : "South American Airways" }
20+ ]
11821
119- except Exception as e :
120- print (f"❌ Error in search_flights_semantic: { str (e )} " ) # Debug print
121- return []
22+ def search_flights (query ):
23+ """Search for flights based on keywords in the query."""
24+ query_lower = query .lower ()
25+
26+ # Match flights by checking if the query is present in any flight attribute
27+ matches = [
28+ flight for flight in flights
29+ if query_lower in flight ["origin" ].lower ()
30+ or query_lower in flight ["destination" ].lower ()
31+ or query_lower in flight ["flight_number" ].lower ()
32+ or query_lower in flight ["airline" ].lower ()
33+ ]
34+
35+ return matches
36+
37+ if __name__ == "__main__" :
38+ # Example search
39+ result = search_flights ("Chicago" )
40+ print (result )
0 commit comments