Skip to content

Commit 71371e9

Browse files
author
RobuRishabh
committed
FlightQueryBot_Version1
1 parent 0c6bc59 commit 71371e9

File tree

5 files changed

+181
-278
lines changed

5 files changed

+181
-278
lines changed

app.py

Lines changed: 39 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,75 +1,69 @@
11
"""
2-
UI using Streamlit
2+
Flight Information Chatbot UI using Streamlit
33
"""
44
import streamlit as st
55
from query_handler import process_query
66
from ollama_api import check_ollama_availability, generate_response
77

8-
# Set page config
8+
# Set Streamlit page config
99
st.set_page_config(
1010
page_title="Flight Information Assistant",
11-
page_icon="✈️"
11+
page_icon="✈️",
1212
)
1313

14-
# Initialize session state for chat history
14+
# Initialize chat history in session state
1515
if "messages" not in st.session_state:
1616
st.session_state.messages = []
1717

18-
# ✅ Check Ollama server availability
19-
ollama_available, ollama_message = check_ollama_availability()
20-
2118
def display_chat_message(role, content):
22-
"""
23-
Display messages in the chat interface.
24-
25-
Args:
26-
role (str): Role of the message sender (user or assistant).
27-
content (str): Message content.
28-
"""
19+
"""Display a chat message in Streamlit UI."""
2920
with st.chat_message(role):
3021
st.markdown(content)
3122

32-
# ✅ Main UI
23+
# Display the title
3324
st.title("✈️ Flight Information Assistant")
3425

35-
# ✅ Display Ollama server availability message
36-
if not ollama_available:
37-
st.warning(f"⚠️ {ollama_message}\nUsing simplified responses until Ollama becomes available.")
26+
# Check Ollama server availability
27+
ollama_status, ollama_message = check_ollama_availability()
28+
if not ollama_status:
29+
st.warning("⚠️ Ollama server is unavailable. Responses will be simplified.")
3830

39-
# ✅ Instructions for the user
31+
# Show instructions
4032
st.markdown("""
41-
**Ask me about flights!** Try questions like:
42-
- What flights are available from New York to London?
43-
- Show me flight NY100.
44-
- Are there any flights from Chicago?
33+
### **Ask me about flights!**
34+
Try questions like:
35+
- ✈️ What flights are available from New York to London?
36+
- 🔍 Show me flight NY100.
37+
- 📍 Are there any flights from Chicago?
4538
""")
4639

47-
# Display chat history
40+
# Display chat history
4841
for message in st.session_state.messages:
4942
display_chat_message(message["role"], message["content"])
5043

51-
# ✅ Chat input handling
52-
if prompt := st.chat_input("Ask about flights..."):
53-
# ✅ Store and display user message
54-
st.session_state.messages.append({"role": "user", "content": prompt})
55-
display_chat_message("user", prompt)
44+
# Chat input handling
45+
user_input = st.chat_input("Ask about flights...")
46+
47+
if user_input:
48+
# Add user query to chat history
49+
st.session_state.messages.append({"role": "user", "content": user_input})
50+
display_chat_message("user", user_input)
5651

57-
try:
58-
# ✅ Process user query
59-
success, message, flights = process_query(prompt)
52+
# Process query
53+
with st.spinner("Searching for flights..."):
54+
try:
55+
success, message, flights = process_query(user_input)
6056

61-
if not success:
62-
st.error(message) # Show error message in UI
63-
response = "⚠️ I couldn't process your request. Try rephrasing your question."
64-
else:
65-
# ✅ Generate assistant response
66-
response = generate_response(prompt, flights)
57+
if not success:
58+
response = f"⚠️ {message}"
59+
else:
60+
response = generate_response(user_input, flights)
6761

68-
# ✅ Store and display assistant response
69-
st.session_state.messages.append({"role": "assistant", "content": response})
70-
display_chat_message("assistant", response)
62+
except ValueError as ve:
63+
response = f"❌ Invalid input: {str(ve)}"
64+
except Exception as e:
65+
response = f"❌ An unexpected error occurred: {str(e)}"
7166

72-
except Exception as e:
73-
error_message = f"❌ An error occurred: {str(e)}"
74-
st.session_state.messages.append({"role": "assistant", "content": error_message})
75-
display_chat_message("assistant", error_message)
67+
# Add assistant response to chat history
68+
st.session_state.messages.append({"role": "assistant", "content": response})
69+
display_chat_message("assistant", response)

mock_database.py

Lines changed: 31 additions & 112 deletions
Original file line numberDiff line numberDiff line change
@@ -1,121 +1,40 @@
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
443
def 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

Comments
 (0)