arnabbumba077's picture
Update app.py
6b37c01 verified
import os
import streamlit as st
from dotenv import load_dotenv
from langchain_core.messages import AIMessage, HumanMessage
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_groq import ChatGroq
import folium
from streamlit_folium import st_folium
from geopy.geocoders import Nominatim
# Load environment variables
load_dotenv()
groq_api_key = os.getenv("GROQ_API_KEY")
# Streamlit configuration
st.set_page_config(page_title="Travel Planner.AI", page_icon="🌍")
st.title("Travel Planner.AI ✈️")
# Prompt template
template = """
You are a travel assistant chatbot named Travel Planner.AI designed to help users plan their trips and provide travel-related information. Here are some scenarios you should be able to handle:
1. Booking Flights: Assist users with booking flights to their desired destinations. Ask for departure city, destination city, travel dates, and any specific preferences (e.g., direct flights, airline preferences). Check available airlines and book the tickets accordingly.
2. Booking Hotels, Hostels etc: Help users find and book accommodations. Inquire about city or region, check-in/check-out dates, number of guests, and accommodation preferences (e.g., budget, amenities).
3. Booking Rental Cars: Facilitate the booking of rental cars for travel convenience. Gather details such as pickup/drop-off locations, dates, car preferences (e.g., size, type), and any additional requirements.
4. Destination Information: Provide information about popular travel destinations. Offer insights on attractions, local cuisine, cultural highlights, weather conditions, and best times to visit.
5. Travel Tips: Offer practical travel tips and advice. Topics may include packing essentials, visa requirements, currency exchange, local customs, and safety tips.
6. Weather Updates: Give current weather updates for specific destinations or regions. Include temperature forecasts, precipitation chances, and any weather advisories.
7. Local Attractions and Hidden Gems: Suggest local attractions and points of interest based on the user's destination. Highlight must-see landmarks, museums, parks, and recreational activities. Also give some hidden gem locations which tourists don’t go to but are awesome.
8. Customer Service: Address customer service inquiries and provide assistance with travel-related issues. Handle queries about bookings, cancellations, refunds, and general support.
Please ensure responses are informative, accurate, and tailored to the user's queries and preferences. Use natural language to engage users and provide a seamless experience throughout their travel planning journey.
Chat history:
{chat_history}
User question:
{user_question}
"""
prompt = ChatPromptTemplate.from_template(template)
# GROQ LLM response
def get_response(user_query, chat_history):
llm = ChatGroq(
groq_api_key=groq_api_key,
model_name="llama-3.3-70b-versatile"
)
chain = prompt | llm | StrOutputParser()
response = chain.invoke({"chat_history": chat_history, "user_question": user_query})
return response
# Initialize chat history
if "chat_history" not in st.session_state:
st.session_state.chat_history = [AIMessage(content="Hello, I am Travel Planner.AI. How can I help you?")]
# Geolocator setup
geolocator = Nominatim(user_agent="travel_planner")
def get_place_name(lat, lon):
location = geolocator.reverse((lat, lon), language='en')
return location.address if location else "Unknown location"
# Display map
st.subheader("Select Your Travel Route")
m = folium.Map(location=[20, 0], zoom_start=2, tiles="CartoDB Positron")
# Initialize session state for locations
if "departure_location" not in st.session_state:
st.session_state.departure_location = None
if "destination_location" not in st.session_state:
st.session_state.destination_location = None
# Departure selection
st.write("Select your departure location:")
departure = st_folium(m, height=350, width=700, key="departure")
if departure and departure['last_clicked']:
lat, lon = departure['last_clicked']['lat'], departure['last_clicked']['lng']
location = get_place_name(lat, lon)
st.session_state.departure_location = location
st.write(f"Departure Location: {location}")
# Destination selection
st.write("Select your destination location:")
destination = st_folium(m, height=350, width=700, key="destination")
if destination and destination['last_clicked']:
lat, lon = destination['last_clicked']['lat'], destination['last_clicked']['lng']
location = get_place_name(lat, lon)
st.session_state.destination_location = location
st.write(f"Destination Location: {location}")
# Display previous messages
for message in st.session_state.chat_history:
with st.chat_message("AI" if isinstance(message, AIMessage) else "Human"):
st.write(message.content)
# Chat input
user_query = st.chat_input("Type your message here...")
if user_query:
# Attach location context to query
if st.session_state.departure_location and st.session_state.destination_location:
user_query = f"From: {st.session_state.departure_location}\nTo: {st.session_state.destination_location}\n{user_query}"
st.session_state.chat_history.append(HumanMessage(content=user_query))
with st.chat_message("Human"):
st.markdown(user_query)
response = get_response(user_query, st.session_state.chat_history)
response = response.replace("AI response:", "").strip()
with st.chat_message("AI"):
st.write(response)
st.session_state.chat_history.append(AIMessage(content=response))