Build your AI Travel Agent with GPT-4o using Python
Tags: ai, beginners, python, programming
Published: 2024-06-13 23:10:00

Imagine planning your dream vacation, but instead of spending hours searching online, an intelligent assistant arranges everything for you. Sounds like a fantasy, right? What if I said you could build this AI travel agent with just a few lines of [Python](https://www.python.org/) code? Yes, it's that simple. In this guide, we'll walk you through the process step-by-step, so you can have your travel assistant ready to help with your next adventure.

You'll use some amazing tools to make this happen. [Streamlit](https://streamlit.io/) will help you create a friendly and interactive interface; [Phidata](https://pypi.org/project/phidata/) will handle your data; [OpenAI's](https://pypi.org/project/openai/0.26.5/) GPT-4 will provide smart conversational abilities; and [Google Search-Results](https://pypi.org/project/google-search-results/) will fetch the best travel options. Together, these tools will allow you to build smart, responsive AI to plan your trips as if you had a personal travel guardian.

So, are you ready to dive in? It doesn’t matter if you are starting with programming; this project is designed to be easy and fun. By the end, you'll understand how these technologies work together and have a functional AI assist with your travel plans. Let's start this exciting journey and see how quickly you can become your travel guardian.

## Setting up the Environment

Think of it as laying out all the ingredients before baking a cake.  All your tools and software should be in place to run your code smoothly.

When working in [Visual Studio Code](https://code.visualstudio.com/) (VS Code), always create a new Python file for your project.

It's helpful to have separate files for different parts of your project.

To do this, you can start by opening your [VS Code](https://code.visualstudio.com/) and creating a new folder:

### Step 1
Open [VS Code](https://code.visualstudio.com/) 

![Vs Code Home page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9h91xy65zqbuxozdayrs.png)

### Step 2

Create new folder

![New Folder on Vs Code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8gmdp57jqiu7pprbc0ug.png)

### Step 3
Name your new file `travel_agent.py` or stick with the default name provided.

![new file on vs code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pzl3uirvda6j5qus2rf4.png)

## Install the Necessary Python Libraries

First, you install some libraries for your project. Libraries are like extra tools that help your code do more things. To install them, you run these commands in your terminal:

```python
pip install streamlit
pip install phidata
pip install openai
pip install google-search-results
```

Here’s what each library does:

- [Streamlit](https://streamlit.io/)-**helps you create interactive web apps without a backend server.**


- [Phidata](https://pypi.org/project/phidata/)-**helps build AI agents and tools.**


- [OpenAI](https://pypi.org/project/openai/0.26.5/)-**allows you to use GPT-4, a powerful AI language model.**


- [SerpAPI](https://pypi.org/project/google-search-results/)-**helps you get search engine results from platforms like Google, Bing, or Yahoo! in a structured format.**

## Import Necessary Libraries

These libraries are special tools that help you do specific tasks in your Python code. Here, you import the necessary libraries for your project:

```python
from textwrap import dedent
from phi.assistant import Assistant
from phi.tools.serpapi_tools import SerpApiTools
import streamlit as st
from phi.llm.openai import OpenAIChat
```

## Set Up the Streamlit Application

Here, you lay the groundwork for your AI travel agent. You'll create a user-friendly interface where users can input their travel preferences and see the AI's suggestions in real time.

### Adding a Title to Our App

Think of it like naming a book or a movie. The title is the first thing people see, it sets the stage for what they can expect. You can do this by using `st.title()`:

```python
st.title("AI Travel Planner ✈️")
```

### App Description

Creating an app description helps users understand the value of your app quickly. It explains the main features and benefits and encourages people to use it. You do this by using `st.caption()`:

```python
st.caption("Plan your next adventure with AI Travel Planner by researching and planning a personalized itinerary on autopilot using GPT-4o.")
```

## Getting User Input for API Keys

Before our AI can plan your dream vacation, it needs special keys to unlock its full potential. API keys act like secret passwords that allow your AI Travel Agent to access powerful services like `OpenAI` and `Google`. These keys are unique to each user and ensure the services are used securely and responsibly.

You are creating two text input fields in the Streamlit app:
the `OpenAI API key` and the `SerpAPI key`.

```python
openai_api_key = st.text_input("Enter OpenAI API Key to access GPT-4o", type="password")
serp_api_key = st.text_input("Enter Serp API Key for Search functionality", type="password")
```

The `type="password"` parameter ensures API keys are hidden when the user types them.

## Creating the Researcher and Planner Assistants

Creating the Researcher and Planner assistants is like having two helpful friends for your AI Travel Agent. The Researcher loves to dig through travel websites to find the best flights, hotels, and attractions. The Planner organizes all that information into a neat, easy-to-follow travel plan.

By dividing these tasks, our AI works more efficiently and accurately, just like how different people in a travel agency handle specific tasks. This way, you get well-researched options and a perfectly planned itinerary, making your trip-planning process smooth and enjoyable.

Here, you check if the user has provided both the `OpenAI API` and the `SerpAPI key`. If so, it creates two instances of the Assistant class: one for the researcher and one for the planner.

```python
if openai_api_key and serp_api_key:
    researcher = Assistant("gpt-4o", openai_api_key)
    planner = Assistant("gpt-4o", openai_api_key)
```

The Assistant class is part of the `phi.assistant module` and is used to create AI assistants with specific roles, instructions, and tools. The researcher assistant searches for travel-related information, while the planner assistant generates a draft itinerary based on the research results.

## Getting User Input for the Destination and Number of Days

Before our AI Travel Agent can help plan your trip, it needs to know two important things: 
- Where you want to go.
- How long will you be staying?

Think of it like talking to a human travel agent: you need to tell them your destination and the length of your trip so they can find the best options for you.

By asking for your destination and the number of days, our program gathers the necessary details to search for flights, hotels, and activities that fit your plans. This information is crucial because it helps tailor the travel recommendations to your needs.

Here, you create two input fields in the Streamlit app: 
One for the user to enter the travel destination.
One is for the user to enter the number of days they want to travel.

```python
destination = st.text_input("Where do you want to go?")
num_days = st.number_input("How many days do you want to travel for?", min_value=1, max_value=30, value=7)
```

The `st.number_input` function ensures that the user can only enter a number between 1 and 30, with a default value of 7 days.

## Generating the Itinerary

An itinerary is just a detailed schedule of your trip. This means you'll create a clear plan that tells us exactly what to do and when during our trip. This way, you won't miss any important bookings or exciting experiences. Your AI Travel Agent handles this for you, making your travel planning as easy as chatting with a friend.

You will create a button in the `Streamlit` app that, when clicked, generates the travel itinerary. When you click the button, the code enters a spinner state, indicating that the app is processing the request.

```python
if st.button("Generate Itinerary"):
    with st.spinner("Processing..."):
        response = planner.run(f"{destination} for {num_days} days", stream=False)
        st.write(response)
```

The `planner.run()` method is then called, passing the user's destination and number of days as arguments.

The `stream=False` parameter ensures that the entire response is returned immediately, rather than streaming.

Finally, the response from the planner assistant is displayed on the `Streamlit` app using `st.write()`.

## Conclusion

We've built something cool: a buddy to help you plan your trips using just a bit of code. We kept it simple, so you don't have to worry about complicated stuff.

We used tools like `Streamlit`, `Phidata`, `OpenAI's` GPT-4, and `Google Search Results`. These tools work together to make your travel planning easy.

We started by setting up our coding space and added the tools we need. With `Streamlit`, we made a simple place to type where you want to go and for how long. Our buddy then puts together a plan just for you.

When you click a button, your personalized plan pops up. No more stressing over details; our buddy's got it covered. This code snippet creates a `Streamlit` app that allows users to input their travel preferences, which researchers and planner assistants use to generate a personalized travel itinerary.