avatarGul Jabeen

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

4683

Abstract

="hljs-string">"type"</span>: <span class="hljs-string">"object"</span>, <span class="hljs-string">"properties"</span>: { <span class="hljs-string">"first_name"</span>: {<span class="hljs-string">"type"</span>: <span class="hljs-string">"string"</span>, <span class="hljs-string">"description"</span>: <span class="hljs-string">"First name of the person."</span>}, <span class="hljs-string">"last_name"</span>: {<span class="hljs-string">"type"</span>: <span class="hljs-string">"string"</span>, <span class="hljs-string">"description"</span>: <span class="hljs-string">"Last name of the person."</span>}, <span class="hljs-string">"phone_number"</span>: {<span class="hljs-string">"type"</span>: <span class="hljs-string">"string"</span>, <span class="hljs-string">"description"</span>: <span class="hljs-string">"Phone number of the person."</span>}, <span class="hljs-string">"email"</span>: {<span class="hljs-string">"type"</span>: <span class="hljs-string">"string"</span>, <span class="hljs-string">"description"</span>: <span class="hljs-string">"Email address of the person."</span>} } } } ]</pre></div><p id="662a">Each function has a name, a description, and a set of parameters that it accepts.</p><h1 id="9967">Implementing the Custom Functions</h1><p id="eead">Next, let’s implement the custom functions. Here are the implementations for two of them:</p><h2 id="f6b7">look_for_flight Function</h2><p id="c113">This function generates a Google Flights URL based on the provided search parameters:</p><div id="e6aa"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">look_for_flight</span>(<span class="hljs-params">params</span>): <span class="hljs-string">""" 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.
"""</span>
origin = params.get(<span class="hljs-string">"origin"</span>)
destination = params.get(<span class="hljs-string">"destination"</span>)
departure_date = params.get(<span class="hljs-string">"departure_date"</span>)
return_date = params.get(<span class="hljs-string">"return_date"</span>)

<span class="hljs-comment"># Construct a URL to Google Flights</span>
google_flights_url = <span class="hljs-string">f"https://www.google.com/travel/flights?hl=en#search;f=<span class="hljs-subst">{origin}</span>;t=<span class="hljs-subst">{destination}</span>;d=<span class="hljs-subst">{departure_date}</span>"</span>

<span class="hljs-keyword">if</span> return_date:
    google_flights_url += <span class="hljs-string">f";r=<span class="hljs-subst">{return_date}</span>"</span>

<span class="hljs-keyword">return</span> <span class="hljs-string">f"You can visit the following Google Flights URL for real flight options:\n<span class="hljs-subst">{google_flights_url}</span>"</span></pre></div><h2 id="bfc5">`book_flight` Function</h2><p id="e2d4">The `book_flight` function simulates the process of booking a flight based on the given flight details and passenger information:</p><div id="bf74"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">book_flight</span>(<span class="hljs-params">params</span>):
<span class="hljs-string">"""
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).
"""</span>
flight_id = params.get(<span class="hljs-string">"flight_id"</span>)
passenger_info = params.get(<span class="hljs-string">"passenger_info"</span>)

<span class="hljs-comment"># Simulate booking a flight (replace with actual booking logic)</span>
confirmation_code = <span class="hljs-string">"ABC123"</span>  <span class="hljs-comment"># Simulated confirmation code</span>

<span class="hljs-keyword">return</span> <span class="hljs-string">f"Your flight with ID <span class="hljs-subst">{flight_id}</span> has been booked. Confirmation code: <span class="hljs-subst">{confirmation_code}</span>."</span></pre></div><p id="bf5a">You can replace the simulation logic with actual booking functionality if desired.</p><h2 id="11f8">`get_user_info` Function</h2><p id="1234">The `get_user_info` function extracts form information from a J

Options

SON response:</p><div id="8069"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">get_user_info</span>(<span class="hljs-params">json_response</span>): <span class="hljs-string">''' 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.
'''</span>

form_info = {
    <span class="hljs-string">"First name"</span>: json_response.get(<span class="hljs-string">'first_name'</span>, <span class="hljs-string">''</span>),
    <span class="hljs-string">"Last name"</span>: json_response.get(<span class="hljs-string">'last_name'</span>, <span class="hljs-string">''</span>),
    <span class="hljs-string">"Phone#"</span>: json_response.get(<span class="hljs-string">'birth_date'</span>, <span class="hljs-string">''</span>),
    <span class="hljs-string">"Email"</span>: json_response.get(<span class="hljs-string">'place_of_birth'</span>, <span class="hljs-string">''</span>),
}

<span class="hljs-keyword">return</span> form_info</pre></div><h1 id="32de">Creating the Chatbot</h1><p id="4bcb">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.</p><div id="9747"><pre><span class="hljs-comment"># Define instructions for user</span>

instructions = <span class="hljs-string">'''

  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. '''</span></pre></div><div id="8f7e"><pre><span class="hljs-comment"># Main loop for conversation with the user</span> <span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>: <span class="hljs-comment"># Initialize the conversation with a user query</span> user_input = <span class="hljs-built_in">input</span>(<span class="hljs-string">"User: "</span>) conversation = [ {<span class="hljs-string">"role"</span>: <span class="hljs-string">"system"</span>, <span class="hljs-string">"content"</span>: <span class="hljs-string">f"You are a helpful travel assistant. Use these instructions: <span class="hljs-subst">{instructions}</span>"</span>}, {<span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: user_input}, ]

    <span class="hljs-comment"># Make a chatbot interaction request</span> openai_response = openai.ChatCompletion.create( model=<span class="hljs-string">"gpt-3.5-turbo"</span>, messages=conversation, functions=custom_functions, function_call=<span class="hljs-string">"auto"</span>, )

    <span class="hljs-comment"># Extract and print the chatbot's response</span> assistant_response = openai_response[<span class="hljs-string">"choices"</span>][<span class="hljs-number">0</span>][<span class="hljs-string">"message"</span>][<span class="hljs-string">"function_call"</span>][<span class="hljs-string">"arguments"</span>] <span class="hljs-built_in">print</span>(<span class="hljs-string">"Assistant:"</span>, assistant_response)</pre></div><p id="168d">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.</p><h1 id="d1e6">Conclusion</h1><p id="7990">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.</p><p id="db4d">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.</p><p id="2e3e">Happy coding and safe travels!</p><blockquote id="386a"><p>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.</p></blockquote></article></body>

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_info

Creating 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.

ChatGPT
OpenAI
Openai Function Calling
AI
Recommended from ReadMedium