Site icon Efficient Coder

Build an AI Travel Agent in 30 Minutes: Weather, Budget, Itineraries with Streamlit & LangChain

Last week, I helped a friend plan a trip to Thailand—and between comparing Bangkok hotel prices, checking real-time weather, converting USD to THB, I had 6 browser tabs open. By the end, I still miscalculated the total budget. If you’ve ever felt like “trip planning is more tiring than working,” you’re not alone. But here’s the game-changer: with Streamlit and LangChain, you can build an AI travel agent that takes 3 seconds to generate a complete plan (weather, hotels, itineraries, even travel videos) when you type something like “5-day Thailand trip, $800 budget.”

This isn’t just a dry API tutorial—it’s a from-zero-to-deployment hands-on guide. Whether you want to solve your own trip-planning headaches or practice building AI apps, you’ll walk away with a working tool.

Prologue: The Old Pain of Trip Planning & AI’s New Solution

Trip planning usually involves three frustrating tasks: switching to a weather app for forecasts, jumping to a hotel platform to compare prices, and manually calculating budgets with a calculator—only to miss key attractions. Information is scattered, budgets slip through the cracks, and a “simple” plan can take hours.

This AI travel agent fixes that by wrapping everything into one tool: it pulls real-time weather from OpenWeatherMap, scrapes live hotel prices via Google Serper, auto-calculates budgets with LangChain, and displays results in a clean web interface using Streamlit. The tech stack is surprisingly accessible:

  • LangChain handles “when to call which tool” (e.g., weather vs. hotel search),
  • Streamlit turns AI outputs into a user-friendly interface,
  • OpenAI GPT-4 understands natural language requests (like “convert $800 to Indian Rupees”).

For everyday users, it’s a time-saving travel tool. For developers, it’s a perfect example of AI + niche use cases—you don’t need to train complex models to build something useful; you just need to combine existing tools.

Intuition: What Can This AI Agent Actually Do?

Before writing code, let’s break down its capabilities. If you type: “3-day Bangkok trip, $500 budget (convert to INR), check weather, find budget hotels, and share travel videos,” here’s what you’ll get back:

  1. Real-Time Weather: Bangkok’s current temperature, humidity, and even a note like “Thunderstorms expected today—bring an umbrella” (data from OpenWeatherMap, as reliable as your phone’s weather app).
  2. Hotel Recommendations: 3 hotels priced at 40/night, complete with addresses, ratings, and total 3-day costs (e.g., 105, or ~₹8,750 INR).
  3. Day-by-Day Itinerary: Planned activities with prices—Day 1: Grand Palace (15); Day 2: Siam Square (free) + street food ($5/meal).
  4. Travel Videos: 3 YouTube links for titles like “2025 Bangkok Travel Guide” or “Bangkok Street Food Tour”—curated to match your destination.
  5. Budget Breakdown: Total spend (~120) for flexible expenses.

The key difference from traditional travel apps (like Ctrip or Booking.com) is dynamic calculation: instead of dumping a list of hotels for you to sift through, it filters options based on your budget and even avoids “low-price traps” (e.g., hotels with hidden fees) by scraping user reviews.

Hands-On: Set Up Your Development Environment (3 Steps)

Let’s get practical. Whether you’re on Windows or macOS, follow these steps to get started. You’ll need three things first: a GitHub account (for storing code), three API keys (OpenAI, Google Serper, OpenWeatherMap), and Python 3.8+ installed.

Step 1: Clone the Repo & Navigate to the Directory

Open your terminal (PowerShell for Windows, Terminal for macOS) and run this command to clone the project. Replace yourusername with your GitHub handle (create an empty repo first if you haven’t already):

git clone https://github.com/yourusername/ai-travel-agent.git
cd ai-travel-agent

Step 2: Create a Virtual Environment & Install Dependencies

Virtual environments prevent dependency conflicts. Run these commands:

# Create a virtual environment
python -m venv venv

# Activate on macOS/Linux
source venv/bin/activate

# Activate on Windows
venv\Scripts\activate

You’ll see (venv) in your terminal when activated. Next, install dependencies:

pip install -r requirements.txt

The requirements.txt file includes Streamlit, LangChain, OpenAI, and other needed libraries. If you’re on Python 3.12+, you might see a warning for python-dotenv—ignore it; it won’t affect functionality.

Step 3: Configure API Keys (Critical—Avoid These Pitfalls)

You need three API keys to make the agent work. Get them here:

  • OpenAI API: For understanding natural language (get it here).
  • Google Serper API: For scraping hotels, exchange rates, and attraction prices (get it here).
  • OpenWeatherMap API: For real-time weather (get it here).

Create a .env file in your project root (note the leading dot) and paste your keys like this:

OPENAI_API_KEY=your-openai-key-here
SERPER_API_KEY=your-google-serper-key-here
OPENWEATHERMAP_API_KEY=your-openweathermap-key-here

Critical Pitfall Alert: Don’t add spaces after the =! I once wasted 30 minutes debugging “invalid API key” errors—turns out a stray space was the culprit. Also, never commit .env to GitHub: the included .gitignore file already excludes it, so you’re safe.

A Quick Project Structure Overview

Your folder should now look like this:

ai-travel-agent/
├── app.py          # Core: Streamlit UI & logic
├── Assignment.ipynb # Backup Jupyter notebook (optional)
├── requirements.txt # Dependencies list
├── .env            # Your API keys (local only)
└── .streamlit/     # Streamlit config (for custom themes)
    └── config.toml

Focus on app.py—it’s where all UI and AI logic lives. The .streamlit/config.toml file lets you customize the interface (e.g., change colors later).

Hands-On: Launch Your First AI Travel Agent (5 Minutes)

Now let’s fire up the app and see it in action.

Three Ways to Run the App

The basic command to start the app is:

streamlit run app.py

Your terminal will say “Your app is running” and open a browser window at http://localhost:8501 (Streamlit’s default port).

If port 8501 is occupied (e.g., by another Streamlit app), use a different port:

# Run on port 8502 instead
streamlit run app.py --server.port 8502

For development (auto-refresh when you edit app.py), add --server.runOnSave true:

streamlit run app.py --server.runOnSave true

Troubleshooting First-Run Errors

If you see “API key error” in your browser, check two things:

  1. Are your keys correct in .env? (Double-check for typos or missing characters.)
  2. Is your virtual environment activated? (Look for (venv) in your terminal—without it, Python can’t find the python-dotenv library to read .env.)

If you get “Failed to connect to OpenAI,” it’s likely a network issue. Try switching Wi-Fi or checking your OpenAI API quota (free users get $5 in credits—plenty for testing).

Minimal Working Example: Test a Bangkok Itinerary

In the browser’s input box, paste this request:

3-day Bangkok trip, $500 budget (convert to INR). Check current weather, find hotels under $40/night, calculate total costs, and share travel video links.

Click “Submit”—you’ll see a loading animation for 3–5 seconds (depending on your internet speed).

Expected Outcome:

  • Top section: Bangkok’s weather (e.g., “28°C, Partly Cloudy, 65% Humidity”).
  • Hotels: 3 options with prices, ratings, and total 3-day costs (e.g., “105 ~ ₹8,750″).
  • Itinerary: Daily activities with prices (e.g., “Day 1: Grand Palace (5)”).
  • Videos: 3 YouTube links for Bangkok travel guides.
  • Budget Summary: Total spend (~180).

If you see this, congratulations—your AI travel agent is working! Now you can test other destinations (e.g., Tokyo, Paris) or adjust budgets.

Hands-On: Break Down Core Features (How It Works)

Let’s demystify the agent’s key features—this will help you add new tools (like flight searches) later.

1. Weather Search: How It Gets Real-Time Data

When you ask for weather, the get_weather(city) function in app.py kicks in. It sends a request to OpenWeatherMap’s API, parses the JSON response, and returns a human-readable string. Here’s a simplified version of the code:

def get_weather(city):
    api_key = os.getenv("OPENWEATHERMAP_API_KEY")
    url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
    response = requests.get(url)
    data = response.json()
    return f"Current weather in {city}: {data['main']['temp']}°C, {data['weather'][0]['description']}"

The units=metric parameter uses Celsius (change to imperial for Fahrenheit).

2. Budget Calculation: Where Real-Time Exchange Rates Come From

When you ask to convert currencies (e.g., USD to INR), the AI calls the search_google tool. This tool scrapes Google for the latest exchange rate (e.g., “1 USD = 83 INR”) and uses LangChain’s built-in addition/multiply tools to calculate totals.

For example: 105 × 83 = ₹8,715. No manual math required!

3. Travel Videos: How It Finds Relevant YouTube Links

The youtube_search function uses YouTube’s search API to find videos matching your destination. It takes your query (e.g., “Bangkok travel guide”) as a keyword and returns the 3 most recent results. To get more videos, edit the max_results parameter in app.py (e.g., change max_results=3 to max_results=5).

Advanced: Deploy to the Cloud (Share with Friends)

Once it works locally, deploy it to the cloud so you can access it anywhere. We’ll use Streamlit Cloud—it’s free, easy, and requires no server knowledge.

Deploy to Streamlit Cloud (10 Minutes)

  1. Push Code to GitHub: First, sync your local code to GitHub. Run these commands in your terminal:

    # Initialize Git (if not already done)
    git init
    # Add all files
    git add .
    # Commit changes
    git commit -m "Initial commit: AI Travel Agent"
    # Link to your GitHub repo (replace with your repo URL)
    git remote add origin https://github.com/yourusername/ai-travel-agent.git
    # Push to GitHub
    git push -u origin main
    

    Remember: .env won’t be pushed (thanks to .gitignore), so you’ll reconfigure keys in the cloud.

  2. Connect to Streamlit Cloud: Go to Streamlit Cloud and log in with GitHub. Click “New app” and fill in:

    • Repository: Select yourusername/ai-travel-agent.
    • Branch: Choose main.
    • Main file path: Enter app.py.
      Click “Deploy”—wait 1–2 minutes for deployment.
  3. Add Cloud API Keys: After deployment, click “Manage app” → “Secrets”. Paste your keys like this:

    OPENAI_API_KEY = "your-openai-key-here"
    SERPER_API_KEY = "your-google-serper-key-here"
    OPENWEATHERMAP_API_KEY = "your-openweathermap-key-here"
    

    Click “Save”—the app will restart. Your AI travel agent is now live at https://your-app-name.streamlit.app (share the link with friends!).

Other Deployment Options

If you need more traffic or customization, try these alternatives:

  • Heroku: Requires a Procfile and setup.sh to configure ports. Free tier includes 550 hours/month.
  • Railway: No config files needed—connect GitHub and deploy automatically. Free tier has usage limits.

Streamlit Cloud works for most users, but check the official docs for Heroku/Railway if you need more control.

Advanced: 3 Tips to Improve Your Agent

Running and deploying is just the start—these tweaks will make your agent faster and more user-friendly.

1. Cache API Calls (Save Money & Speed Things Up)

Every API call costs money (e.g., OpenAI charges ~$0.03 per GPT-4 call) and slows down the app. Use Streamlit’s @st.cache_data decorator to cache results for repeated queries. For example:

@st.cache_data(ttl=600)  # Cache for 10 minutes (600 seconds)
def get_weather(city):
    # Original function logic remains unchanged

Add this decorator to search_google and youtube_search too. For real-time data (like exchange rates), set ttl=3600 (1 hour) to keep results fresh.

2. Customize the UI Theme (Add a “Travel Vibe”)

The default Streamlit interface is white—spice it up with a light blue theme (evokes sky/travel). Edit .streamlit/config.toml:

[theme]
primaryColor = "#4A90E2"  # Light blue (main color)
backgroundColor = "#F5F7FA"  # Light gray (background)
secondaryBackgroundColor = "#E8F0FE"  # Paler blue (secondary background)
textColor = "#333333"  # Dark gray (text)
[server]
runOnSave = true  # Auto-refresh on save

Restart the app—your UI will now match a travel-focused aesthetic. Search “Streamlit theme color codes” for more palettes.

3. Save Chat History (No More Repeating Queries)

By default, the app forgets your queries when you refresh. Use Streamlit’s session_state to save chat history. Add this code to app.py:

# Initialize session state (if not exists)
if "messages" not in st.session_state:
    st.session_state.messages = []

# Show past messages
for msg in st.session_state.messages:
    st.chat_message(msg["role"]).write(msg["content"])

# Handle new input
if prompt := st.chat_input("Enter your travel request..."):
    # Add user input to session state
    st.session_state.messages.append({"role": "user", "content": prompt})
    # Call AI to generate a response (original logic here)
    response = react_graph.invoke({"input": prompt})
    # Add AI response to session state
    st.session_state.messages.append({"role": "assistant", "content": response})

Now your past queries and responses stay visible—perfect for refining itineraries.

Conclusion: More Than a Travel Tool—An AI Deployment Blueprint

You now have a working AI travel agent that checks weather, calculates budgets, and generates itineraries. But this project is more than a tool—it’s a blueprint for building AI apps:

  • For non-developers: It solves a real problem (time-consuming trip planning) without requiring technical skills.
  • For developers: It shows how to combine LangChain (tool logic) + Streamlit (UI) to build useful AI products—no model training needed.

Next steps to expand the agent:

  • Add flight searches: Integrate the Skyscanner API to check ticket prices.
  • Add visa reminders: Use embassy APIs to alert users about visa deadlines.
  • Add collaboration: Use Firebase to let multiple people edit the same itinerary.

AI app development doesn’t have to be complex. Focus on a small pain point, combine existing tools, and you’ll build something people actually use.

Frequently Asked Questions (FAQ)

Q: Will frequent API calls cost me money?

A: Yes, but new users get plenty of free credits. OpenAI gives $5 in free credits (enough for ~160 GPT-4 calls), Google Serper offers 100 free searches/month, and OpenWeatherMap allows 60 free calls/day. Upgrade to paid plans only when you need more usage.

Q: My deployed app is slow—how can I speed it up?

A: Two fixes: 1) Use @st.cache_data to cache API results (reduces repeated calls). 2) Deploy to a region closer to you (Streamlit Cloud lets you choose regions like Singapore for Asia-based users).

Q: Can I make the AI recommend off-the-beaten-path attractions instead of popular ones?

A: Yes! Modify the search_google function to add “off-the-beaten-path” to your keywords. For example, change “Bangkok attractions” to “Bangkok off-the-beaten-path attractions 2025″—the AI will scrape results for less touristy spots.

Q: I get a “permission denied” error when activating the virtual environment on Windows—what do I do?

A: Open PowerShell as an administrator and run Set-ExecutionPolicy RemoteSigned. Type “Y” to confirm—this fixes Windows’ default restriction on running scripts.

Engineering Checklist (Copy to GitHub Issues)

  • [ ] Cloned the repo and navigated to the project directory
  • [ ] Created and activated the virtual environment (venv\Scripts\activate or source venv/bin/activate)
  • [ ] Installed all dependencies (pip install -r requirements.txt)
  • [ ] Created a .env file with 3 valid API keys (no extra spaces)
  • [ ] Launched the app locally (streamlit run app.py) and tested a trip query
  • [ ] Pushed code to GitHub (ensured .env is excluded)
  • [ ] Deployed to Streamlit Cloud and added secrets
  • [ ] Optimized performance with @st.cache_data

Thought Questions & Answers

1. Question: How can I add a “flight price search” feature to the AI travel agent?

Answer:
Step 1: Sign up for the Skyscanner API (link) and get your API key.
Step 2: Add the key to your .env file: SKYSCANNER_API_KEY=your-key-here.
Step 3: Create a get_flights(origin, destination, date) function in app.py:

def get_flights(origin, destination, date):
    api_key = os.getenv("SKYSCANNER_API_KEY")
    url = f"https://partners.api.skyscanner.net/apiservices/browsequotes/v1.0/CN/CNY/zh-CN/{origin}/{destination}/{date}"
    params = {"apiKey": api_key}
    response = requests.get(url, params=params)
    data = response.json()
    min_price = data["Quotes"][0]["MinPrice"]
    return f"Cheapest flight from {origin} to {destination} ({date}): ¥{min_price}"

Step 4: Add get_flights to LangChain’s toolset so the AI recognizes “search flights” requests.
Step 5: Add input fields (origin, destination, date) to the Streamlit UI to trigger the flight search.

2. Question: Why must I use environment variables to store API keys instead of hardcoding them?

Answer:
Three critical reasons:

  1. Security Risk: Hardcoding keys in code and pushing to GitHub exposes them publicly. Anyone could steal your keys to make unauthorized API calls—leading to unexpected charges (e.g., a leaked OpenAI key once cost a developer $500 in a day).
  2. Environment Flexibility: You may use different keys for local testing vs. production (e.g., a free OpenAI key locally, a paid one in the cloud). Environment variables let you switch keys without editing code.
  3. Compliance: Most API providers (OpenAI, Google, etc.) ban hardcoding keys in public repos. Violating this rule can get your API access revoked. Environment variables follow industry security best practices.

Exit mobile version