Building a Travel Assistant Chatbot with OpenAI GPT-3.5 and Python
In today’s fast-paced world, technology continues to reshape the way we travel. One of the latest trends in travel technology is the use of chatbots to assist travelers in various aspects of their journey. These virtual travel assistants can help users find flights, book hotels, and access valuable information about their destinations. In this article, we’ll walk through the process of building a travel assistant chatbot using Python and OpenAI’s GPT-3.5 model.
Introduction
The travel assistant we’re building will have three main functions:
1. Look for Flights: This function allows users to search for available flights based on their departure city or airport, destination, and travel dates.
2. Book a Flight: Users can simulate the process of booking a flight by providing flight details and passenger information.
3. Get User Info: The chatbot can also gather personal information such as a user’s first name, last name, phone number, and email address.
Prerequisites
Before we dive into the code, make sure you have the following prerequisites:
- Python installed on your computer.
- An OpenAI GPT-3.5 API key. You can obtain this key from the OpenAI platform.
Setting Up the Custom Functions
We’ll start by defining custom functions for our travel assistant. These functions will be used to perform specific tasks based on user requests. Here’s a snippet of the custom functions:
import openai
# Define custom functions
custom_functions = [
{
"name": "look_for_flight",
"description": "Search for available flights on Booking.com.",
"parameters": {
"type": "object",
"properties": {
"origin": {"type": "string", "description": "Departure city or airport."},
"destination": {"type": "string", "description": "Arrival city or airport."},
"departure_date": {"type": "string", "description": "Departure date."},
"return_date": {"type": "string", "description": "Return date (optional)."},
},
},
},
{
"name": "book_flight",
"description": "Book a flight on Booking.com.",
"parameters": {
"type": "object",
"properties": {
"flight_id": {"type": "string", "description": "ID of the selected flight."},
"passenger_info": {"type": "object", "description": "Passenger information."},
},
},
},
{
"name": "get_user_info",
"description": "Get user information (e.g., name, email, etc.).",
"parameters": {
"type": "object",
"properties": {
"first_name": {"type": "string", "description": "First name of the person."},
"last_name": {"type": "string", "description": "Last name of the person."},
"phone_number": {"type": "string", "description": "Phone number of the person."},
"email": {"type": "string", "description": "Email address of the person."}
}
}
}
]Each function has a name, a description, and a set of parameters that it accepts.
Implementing the Custom Functions
Next, let’s implement the custom functions. Here are the implementations for two of them:
`look_for_flight` Function
This function generates a Google Flights URL based on the provided search parameters:
def look_for_flight(params):
"""
Generate a Google Flights URL based on the provided search parameters.
Parameters:
- params (dict): A dictionary containing the search parameters, such as origin, destination,
departure_date, and return_date.
Returns:
- str: A message with a Google Flights URL for the user to visit.
"""
origin = params.get("origin")
destination = params.get("destination")
departure_date = params.get("departure_date")
return_date = params.get("return_date")
# Construct a URL to Google Flights
google_flights_url = f"https://www.google.com/travel/flights?hl=en#search;f={origin};t={destination};d={departure_date}"
if return_date:
google_flights_url += f";r={return_date}"
return f"You can visit the following Google Flights URL for real flight options:\n{google_flights_url}"`book_flight` Function
The `book_flight` function simulates the process of booking a flight based on the given flight details and passenger information:
def book_flight(params):
"""
Simulate booking a flight based on the given parameters.
Parameters:
- params (dict): A dictionary containing flight details and passenger information.
Returns:
- str: A confirmation message indicating that the flight was booked (simulated).
"""
flight_id = params.get("flight_id")
passenger_info = params.get("passenger_info")
# Simulate booking a flight (replace with actual booking logic)
confirmation_code = "ABC123" # Simulated confirmation code
return f"Your flight with ID {flight_id} has been booked. Confirmation code: {confirmation_code}."You can replace the simulation logic with actual booking functionality if desired.
`get_user_info` Function
The `get_user_info` function extracts form information from a JSON response:
def get_user_info(json_response):
'''
Create a dictionary containing form information from a JSON response.
Inputs:
- json_response (dict): The JSON response containing extracted information.
Returns:
- dict: A dictionary containing the form information.
'''
form_info = {
"First name": json_response.get('first_name', ''),
"Last name": json_response.get('last_name', ''),
"Phone#": json_response.get('birth_date', ''),
"Email": json_response.get('place_of_birth', ''),
}
return form_infoCreating the Chatbot
Now that we have defined our custom functions, we can create the main chatbot. The chatbot uses the OpenAI GPT-3.5 model to interact with users based on their queries and instructions.
# Define instructions for user
instructions = '''
1. If the user asks to see flights online, choose look_for_flight.
2. If the user wants to book a flight, choose book_flight.
3. If the user adds a name, phone number, or email, choose get_user_info.
'''# Main loop for conversation with the user
while True:
# Initialize the conversation with a user query
user_input = input("User: ")
conversation = [
{"role": "system", "content": f"You are a helpful travel assistant. Use these instructions: {instructions}"},
{"role": "user", "content": user_input},
]
# Make a chatbot interaction request
openai_response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=conversation,
functions=custom_functions,
function_call="auto",
)
# Extract and print the chatbot's response
assistant_response = openai_response["choices"][0]["message"]["function_call"]["arguments"]
print("Assistant:", assistant_response)This loop continuously takes user input, processes it using the GPT-3.5 model, and provides responses based on the defined custom functions and instructions.
Conclusion
In this article, we’ve explored how to build a travel assistant chatbot using Python and OpenAI’s GPT-3.5 model. This chatbot can assist users in searching for flights, booking flights, and collecting user information. With further development, you can expand its capabilities to include other travel-related tasks and provide even more value to travelers.
Building chatbots like this can greatly enhance the travel experience by providing quick and convenient access to information and services. As technology continues to advance, we can expect to see more innovative applications of chatbots in the travel industry and beyond.
Happy coding and safe travels!
Building a travel assistant chatbot can be a valuable addition to travel-related websites and applications, providing users with a seamless and personalized experience. OpenAI’s GPT-3.5 model, combined with Python, makes it relatively easy to develop such a chatbot with the capability to handle a range of tasks.
