In in the present day’s fast-paced world, automated methods have gotten more and more in style for simplifying duties and bettering productiveness. Luckily, developments in AI and automation have paved the best way for progressive options that streamline this course of.
OpenAI’s perform name function revolutionizes the best way we work together with AI fashions. It permits builders to make direct API calls, producing dynamic responses based mostly on consumer inputs. By using this highly effective performance of ChatGPT, we are going to create an appointment reserving chatbot that may interact in pure and significant conversations, offering customers with a customized and interactive expertise.
On this weblog put up, we are going to discover methods to create a chatbot utilizing OpenAI’s function calling feature which we are going to combine with the Google Calendar API, permitting customers to effortlessly guide appointments with out the necessity for guide intervention. Let’s dive in and uncover the journey of constructing an clever appointment reserving chatbot, harnessing the facility of ChatGPT and OpenAI’s perform calling function built-in with the Google Calendar API.
In case you’re unfamiliar with OpenAI’s perform calling function, we advocate referring to our weblog put up titled OpenAI Function Calling With External API Examples. This complete information gives a step-by-step overview of methods to use this highly effective performance. It covers the utilization of OpenAI’s perform calling function and its integration with Google Calendar API, providing detailed explanations and sensible examples. The script will permit us to effortlessly guide, reschedule, delete, and verify the provision of appointments.
Step 1:
To make the most of the Google Calendar API for appointment scheduling, it’s important to arrange your surroundings appropriately. You’ll be able to carry out this setup by following the directions supplied within the following hyperlink: https://developers.google.com/calendar/api/quickstart/python#set_up_your_environment
That you must observe every step, together with enabling the API, configuring the OAuth consent screen, authorizing credentials for a desktop application, and installing the necessary Google client library for organising the API appropriately.
Step 2:
After finishing the setup course of, you will need to specify the suitable edit scope in your software. On the desktop, you’ll be able to navigate to the “Edit App” part which is positioned subsequent to the identify of your app. From there, Go to the scopes part and embrace the “https://www.googleapis.com/auth/calendar” scope inside your “Your delicate scopes” settings. As soon as added, keep in mind to save lots of the adjustments to make sure that your software has the mandatory permissions to work together with the Google Calendar API successfully.
Step 3:
Subsequent, we are going to configure the pattern instance. To do that, you will want to create a file named “quickstart.py” in your working listing. Copy and paste the supplied code snippet into this file. Ensure you have “credentials.json” file in your working listing.
from __future__ import print_function
import datetime
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.movement import InstalledAppFlow
from googleapiclient.discovery import construct
from googleapiclient.errors import HttpError
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/calendar']
def primary():
"""Reveals fundamental utilization of the Google Calendar API.
Prints the beginning and identify of the subsequent 10 occasions on the consumer's calendar.
"""
creds = None
# The file token.json shops the consumer's entry and refresh tokens, and is
# created routinely when the authorization movement completes for the primary
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are not any (legitimate) credentials obtainable, let the consumer log in.
if not creds or not creds.legitimate:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
movement = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = movement.run_local_server(port=0)
# Save the credentials for the subsequent run
with open('token.json', 'w') as token:
token.write(creds.to_json())
strive:
service = construct('calendar', 'v3', credentials=creds)
# Name the Calendar API
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' signifies UTC time
print('Getting the upcoming 10 occasions')
events_result = service.occasions().record(calendarId='main', timeMin=now,
maxResults=10, singleEvents=True,
orderBy='startTime').execute()
occasions = events_result.get('gadgets', [])
if not occasions:
print('No upcoming occasions discovered.')
return
# Prints the beginning and identify of the subsequent 10 occasions
for occasion in occasions:
begin = occasion['start'].get('dateTime', occasion['start'].get('date'))
print(begin, occasion['summary'])
besides HttpError as error:
print('An error occurred: %s' % error)
if __name__ == '__main__':
primary()
Once you run “quickstart.py” for the primary time, it is going to immediate you to grant entry to the applying. If in case you have a number of Google accounts, you’ll be able to select the specified account and click on on the “Settle for” button.
This step will create “token.json” file in your working listing. This file will function the authorization token used to authenticate and authorize entry when declaring the desired scope.
Step 4:
We will now proceed to develop a Python script to create an appointment reserving chatbot that leverages OpenAI’s perform calling function to schedule, reschedule, delete, and verify appointments with the mixing of the Google Calendar API.
First, we have to import the required libraries.
import json
import requests
from datetime import date, datetime, timedelta
from time import time
from googleapiclient.discovery import construct
from google.oauth2.credentials import Credentials
import pytz
Step 5:
Subsequent, we have to specify the scope for accessing and managing calendar-related knowledge by way of the Google Calendar API. Then, we create an occasion of the Credentials object utilizing the approved consumer data saved within the “token.json” file. Lastly, we move the credentials object to construct a service object, which permits us to work together with the Google Calendar API. To do that, you must add beneath strains of code in your script.
Just be sure you have a “token.json” file in your working listing.
SCOPES = ['https://www.googleapis.com/auth/calendar']
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
service = construct('calendar', 'v3', credentials=creds)
Step 6:
GPT_MODEL = "gpt-3.5-turbo-0613"
openai_api_key = "<Your_OpenAI_key>"
def chat_completion_request(messages, capabilities=None, function_call=None, mannequin=GPT_MODEL):
headers = {
"Content material-Sort": "software/json",
"Authorization": "Bearer " + openai_api_key,
}
json_data = {"mannequin": mannequin, "messages": messages}
if capabilities is just not None:
json_data.replace({"capabilities": capabilities})
if function_call is just not None:
json_data.replace({"function_call": function_call})
strive:
response = requests.put up(
"https://api.openai.com/v1/chat/completions",
headers=headers,
json=json_data,
)
return response
besides Exception as e:
print("Unable to generate ChatCompletion response")
print(f"Exception: {e}")
return e
Step 7:
Let’s create a perform for appointment reserving that extracts the mandatory parameters from the argument object returned because the response from the ChatGPT perform name.
The consumer will probably be requested to supply the beginning date, begin time, and electronic mail tackle. The beginning date and time will probably be merged to type a single parameter, which will probably be handed to the Google Calendar API name because the designated begin time for the assembly. By default, the ending time of the assembly will probably be set to 2 hours after the beginning time. The supplied electronic mail tackle will probably be assigned because the attendee of the assembly. The occasion JSON, containing these particulars, will probably be handed as a parameter to the insert occasion within the Google Calendar API to guide an appointment.
limit1 = datetime.strptime("10:00:00", "%H:%M:%S").time()
limit2 = datetime.strptime("17:00:00", "%H:%M:%S").time()
limit3 = datetime.strptime("12:00:00", "%H:%M:%S").time()
def appointment_booking(arguments):
strive:
provided_date = str(datetime.strptime(json.hundreds(arguments)['date'], "%Y-%m-%d").date())
provided_time = str(datetime.strptime(json.hundreds(arguments)['time'].substitute("PM","").substitute("AM","").strip(), "%H:%M:%S").time())
start_date_time = provided_date + " " + provided_time
timezone = pytz.timezone('Asia/Kolkata')
start_date_time = timezone.localize(datetime.strptime(start_date_time, "%Y-%m-%d %H:%M:%S"))
email_address = json.hundreds(arguments)['email_address']
end_date_time = start_date_time + timedelta(hours=2)
if provided_date and provided_time and email_address:
slot_checking = appointment_checking(arguments)
if slot_checking == "Slot is on the market for appointment. Would you wish to proceed?":
if start_date_time < datetime.now(timezone):
return "Please enter legitimate date and time."
else:
if day_list[start_date_time.date().weekday()] == "Saturday":
if start_date_time.time() >= limit1 and start_date_time.time() <= limit3:
occasion = {
'abstract': "Appointment reserving Chatbot utilizing OpenAI's perform calling function",
'location': "Ahmedabad",
'description': "This appointment has been scheduled because the demo of the appointment reserving chatbot utilizing OpenAI perform calling function by Pragnakalp Techlabs.",
'begin': {
'dateTime': start_date_time.strftime("%Y-%m-%dTpercentH:%M:%S"),
'timeZone': 'Asia/Kolkata',
},
'finish': {
'dateTime': end_date_time.strftime("%Y-%m-%dTpercentH:%M:%S"),
'timeZone': 'Asia/Kolkata',
},
'attendees': [
{'email': email_address},
],
'reminders': {
'useDefault': False,
'overrides': [
{'method': 'email', 'minutes': 24 * 60},
{'method': 'popup', 'minutes': 10},
],
},
}
service.occasions().insert(calendarId='main', physique=occasion).execute()
return "Appointment added efficiently."
else:
return "Please attempt to guide an appointment into working hours, which is 10 AM to 2 PM at saturday."
else:
if start_date_time.time() >= limit1 and start_date_time.time() <= limit2:
occasion = {
'abstract': "Appointment reserving Chatbot utilizing OpenAI's perform calling function",
'location': "Ahmedabad",
'description': "This appointment has been scheduled because the demo of the appointment reserving chatbot utilizing OpenAI perform calling function by Pragnakalp Techlabs.",
'begin': {
'dateTime': start_date_time.strftime("%Y-%m-%dTpercentH:%M:%S"),
'timeZone': 'Asia/Kolkata',
},
'finish': {
'dateTime': end_date_time.strftime("%Y-%m-%dTpercentH:%M:%S"),
'timeZone': 'Asia/Kolkata',
},
'attendees': [
{'email': email_address},
],
'reminders': {
'useDefault': False,
'overrides': [
{'method': 'email', 'minutes': 24 * 60},
{'method': 'popup', 'minutes': 10},
],
},
}
service.occasions().insert(calendarId='main', physique=occasion).execute()
return "Appointment added efficiently."
else:
return "Please attempt to guide an appointment into working hours, which is 10 AM to 7 PM."
else:
return slot_checking
else:
return "Please present all vital particulars: Begin date, Finish date and E mail tackle."
besides:
return "We face an error whereas processing your request. Please strive once more."
Step 8:
Now, we are going to outline a perform that helps in rescheduling appointments. In the course of the rescheduling course of, the consumer will probably be requested to supply a brand new date, new time, and electronic mail ID for identification functions. Subsequently, the beginning time of the occasion will probably be generated by merging the supplied begin time and date.
The perform begins by fetching the occasion object of the appointment that must be rescheduled. It then proceeds to replace the beginning and finish instances of the occasion. Lastly, the up to date occasion object is handed as a parameter to the Google Calendar API’s replace occasion.
def appointment_reschedule(arguments):
strive:
provided_date = str(datetime.strptime(json.hundreds(arguments)['date'], "%Y-%m-%d").date())
provided_time = str(datetime.strptime(json.hundreds(arguments)['time'].substitute("PM","").substitute("AM","").strip(), "%H:%M:%S").time())
start_date_time = provided_date + " " + provided_time
timezone = pytz.timezone('Asia/Kolkata')
start_date_time = timezone.localize(datetime.strptime(start_date_time, "%Y-%m-%d %H:%M:%S"))
email_address = json.hundreds(arguments)['email_address']
if provided_date and provided_time and email_address:
if start_date_time < datetime.now(timezone):
return "Please enter legitimate date and time."
else:
if day_list[start_date_time.date().weekday()] == "Saturday":
if start_date_time.time() >= limit1 and start_date_time.time() <= limit3:
end_date_time = start_date_time + timedelta(hours=2)
occasions = service.occasions().record(calendarId="main").execute()
id = ""
final_event = None
for occasion in occasions['items']:
if occasion['attendees'][0]['email'] == email_address:
id = occasion['id']
final_event = occasion
if final_event:
if appointment_checking(arguments) == "Slot is on the market for appointment. Would you wish to proceed?":
final_event['start']['dateTime'] = start_date_time.strftime("%Y-%m-%dTpercentH:%M:%S")
final_event['end']['dateTime'] = end_date_time.strftime("%Y-%m-%dTpercentH:%M:%S")
service.occasions().replace(calendarId='main', eventId=id, physique=final_event).execute()
return "Appointment rescheduled."
else:
return "Sorry, slot is just not obtainable presently, please strive a special time."
else:
return "No registered occasion discovered in your id."
else:
return "Please attempt to guide an appointment into working hours, which is 10 AM to 2 PM at saturday."
else:
if start_date_time.time() >= limit1 and start_date_time.time() <= limit2:
end_date_time = start_date_time + timedelta(hours=2)
occasions = service.occasions().record(calendarId="main").execute()
id = ""
final_event = None
for occasion in occasions['items']:
if occasion['attendees'][0]['email'] == email_address:
id = occasion['id']
final_event = occasion
if final_event:
if appointment_checking(arguments) == "Slot is on the market for appointment. Would you wish to proceed?":
final_event['start']['dateTime'] = start_date_time.strftime("%Y-%m-%dTpercentH:%M:%S")
final_event['end']['dateTime'] = end_date_time.strftime("%Y-%m-%dTpercentH:%M:%S")
service.occasions().replace(calendarId='main', eventId=id, physique=final_event).execute()
return "Appointment rescheduled."
else:
return "Sorry, slot is just not obtainable presently, please strive a special time."
else:
return "No registered occasion discovered in your id."
else:
return "Please attempt to guide an appointment into working hours, which is 10 AM to 7 PM."
else:
return "Please present all vital particulars: Begin date, Finish date and E mail tackle."
besides:
return "We're unable to course of, please strive once more."
Step 9:
Shifting ahead, we are going to add the performance of appointment deletion. Throughout this course of, the consumer will probably be requested to supply a date, time, and electronic mail tackle. Then, we are going to verify if any registered occasion is scheduled beneath the supplied electronic mail tackle. If an occasion is discovered, it is going to be deleted utilizing the delete occasion supplied by the Google Calendar API.
To implement the appointment deletion performance, please embrace the next strains of code:
def appointment_delete(arguments):
strive:
provided_date = str(datetime.strptime(json.hundreds(arguments)['date'], "%Y-%m-%d").date())
provided_time = str(datetime.strptime(json.hundreds(arguments)['time'].substitute("PM","").substitute("AM","").strip(), "%H:%M:%S").time())
email_address = json.hundreds(arguments)['email_address']
if provided_date and provided_time and email_address:
start_date_time = provided_date + " " + provided_time
timezone = pytz.timezone('Asia/Kolkata')
start_date_time = timezone.localize(datetime.strptime(start_date_time, "%Y-%m-%d %H:%M:%S"))
if start_date_time < datetime.now(timezone):
return "Please enter legitimate date and time."
else:
occasions = service.occasions().record(calendarId="main").execute()
id = ""
for occasion in occasions['items']:
if occasion['attendees'][0]['email'] == email_address:
if datetime.fromisoformat(str(occasion['start']['dateTime'])) == datetime.fromisoformat(str(start_date_time)):
id = occasion['id']
if id:
service.occasions().delete(calendarId='main', eventId=id).execute()
return "Appointment deleted efficiently."
else:
return "No registered occasion discovered in your id."
else:
return "Please present all vital particulars: Begin date, Finish date and E mail tackle."
besides:
return "We're unable to course of, please strive once more."
Step 10:
For our final performance, we are going to implement the appointment checking performance. Customers will probably be prompted to enter their desired date and time for the slot verify. To confirm the provision, we are going to make the most of the “record” occasion from the Google Calendar API.
Please add the beneath strains of code to implement appointment checking performance.
def appointment_checking(arguments):
strive:
provided_date = str(datetime.strptime(json.hundreds(arguments)['date'], "%Y-%m-%d").date())
provided_time = str(datetime.strptime(json.hundreds(arguments)['time'].substitute("PM","").substitute("AM","").strip(), "%H:%M:%S").time())
start_date_time = provided_date + " " + provided_time
timezone = pytz.timezone('Asia/Kolkata')
start_date_time = timezone.localize(datetime.strptime(start_date_time, "%Y-%m-%d %H:%M:%S"))
if start_date_time < datetime.now(timezone):
return "Please enter legitimate date and time."
else:
if day_list[start_date_time.date().weekday()] == "Saturday":
if start_date_time.time() >= limit1 and start_date_time.time() <= limit3:
end_date_time = start_date_time + timedelta(hours=2)
events_result = service.occasions().record(calendarId='main', timeMin=start_date_time.isoformat(), timeMax=end_date_time.isoformat()).execute()
if events_result['items']:
return "Sorry slot is just not obtainable."
else:
return "Slot is on the market for appointment. Would you wish to proceed?"
else:
return "Please attempt to verify an appointment inside working hours, which is 10 AM to 2 PM at saturday."
else:
if start_date_time.time() >= limit1 and start_date_time.time() <= limit2:
end_date_time = start_date_time + timedelta(hours=2)
events_result = service.occasions().record(calendarId='main', timeMin=start_date_time.isoformat(), timeMax=end_date_time.isoformat()).execute()
if events_result['items']:
return "Sorry slot is just not obtainable."
else:
return "Slot is on the market for appointment. Would you wish to proceed?"
else:
return "Please attempt to verify an appointment inside working hours, which is 10 AM to 7 PM."
besides:
return "We're unable to course of, please strive once more."
Step 11:
Following that, we are going to outline a perform specification that defines all our functionalities, together with appointment insertion, updation, deletion, and checking. This perform specification will describe the aim of the perform and its parameters, and the worth of every parameter. When the consumer gives enter, the ChatGPT mannequin will decide which perform must be invoked and extract the related parameters to be handed as arguments.
To explain the perform specification, you must add beneath strains of code:
capabilities = [
{
"name": "appointment_booking",
"description": "When user want to book appointment, then this function should be called.",
"parameters": {
"type": "object",
"properties": {
"date": {
"type": "string",
"format": "date",
"example":"2023-07-23",
"description": "Date, when the user wants to book an appointment. The date must be in the format of YYYY-MM-DD.",
},
"time": {
"type": "string",
"example": "20:12:45",
"description": "time, on which user wants to book an appointment on a specified date. Time must be in %H:%M:%S format.",
},
"email_address": {
"type": "string",
"description": "email_address of the user gives for identification.",
}
},
"required": ["date","time","email_address"],
},
},
{
"identify": "appointment_reschedule",
"description": "When consumer need to reschedule appointment, then this perform must be referred to as.",
"parameters": {
"kind": "object",
"properties": {
"date": {
"kind": "string",
"format": "date",
"instance":"2023-07-23",
"description": "It's the date on which the consumer desires to reschedule the appointment. The date have to be within the format of YYYY-MM-DD.",
},
"time": {
"kind": "string",
"description": "It's the time on which consumer desires to reschedule the appointment. Time have to be in %H:%M:%S format.",
},
"email_address": {
"kind": "string",
"description": "email_address of the consumer provides for identification.",
}
},
"required": ["date","time","email_address"],
},
},
{
"identify": "appointment_delete",
"description": "When consumer need to delete appointment, then this perform must be referred to as.",
"parameters": {
"kind": "object",
"properties": {
"date": {
"kind": "string",
"format": "date",
"instance":"2023-07-23",
"description": "Date, on which consumer has appointment and desires to delete it. The date have to be within the format of YYYY-MM-DD.",
},
"time": {
"kind": "string",
"description": "time, on which consumer has an appointment and desires to delete it. Time have to be in %H:%M:%S format.",
},
"email_address": {
"kind": "string",
"description": "email_address of the consumer provides for identification.",
}
},
"required": ["date","time","email_address"],
},
},
{
"identify": "appointment_checking",
"description": "When consumer desires to verify if appointment is on the market or not, then this perform must be referred to as.",
"parameters": {
"kind": "object",
"properties": {
"date": {
"kind": "string",
"format": "date",
"instance":"2023-07-23",
"description": "Date, when the consumer desires to guide an appointment. The date have to be within the format of YYYY-MM-DD.",
},
"time": {
"kind": "string",
"instance": "20:12:45",
"description": "time, on which consumer desires to guide an appointment on a specified date. Time have to be in %H:%M:%S format.",
}
},
"required": ["date","time"],
},
}]
Step 12:
Within the closing step, we are going to provoke the testing section for our appointment reserving chatbot. On offering the precise necessities as enter, the ChatGPT mannequin will routinely interpret the suitable perform to be invoked, together with the corresponding parameters. It’ll then return the perform identify and its arguments, permitting us to execute the perform and fulfill our necessities.
To conduct the testing, please embrace the next strains of code:
day_list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
messages = [{"role": "system", "content": f"""You are an expert in booking appointments. You need to ask the user for the appointment date, appointment time, and email ID. The user can book the appointment from 10 AM to 7 PM from Monday to Friday, and from 10 AM to 2 PM on Saturdays. You need to remember that today's date is {date.today()} and day is {day_list[date.today().weekday()]}. Verify if the time supplied by the consumer is throughout the working hours then solely you'll proceed.
Directions:
- Do not make assumptions about what values to plug into capabilities, if the consumer doesn't present any of the required parameters then you have to must ask for clarification.
- Be sure the e-mail Id is legitimate and never empty.
- If a consumer request is ambiguous, then additionally you must ask for clarification.
- When a consumer asks for a rescheduling date or time of the present appointment, then you have to ask for the brand new appointment particulars solely.
- If a consumer did not specify "ante meridiem (AM)" or "put up meridiem (PM)" whereas offering the time, then you have to must ask for clarification. If the consumer did not present day, month, and 12 months whereas giving the time then you have to must ask for clarification.
Be sure to observe the directions rigorously whereas processing the request.
"""}]
user_input = enter("Please enter your query right here: (if you wish to exit then write 'exit' or 'bye'.) ")
whereas user_input.strip().decrease() != "exit" and user_input.strip().decrease() != "bye":
messages.append({"function": "consumer", "content material": user_input})
# calling chat_completion_request to name ChatGPT completion endpoint
chat_response = chat_completion_request(
messages, capabilities=capabilities
)
# fetch response of ChatGPT and name the perform
assistant_message = chat_response.json()["choices"][0]["message"]
if assistant_message['content']:
print("Response is: ", assistant_message['content'])
messages.append({"function": "assistant", "content material": assistant_message['content']})
else:
fn_name = assistant_message["function_call"]["name"]
arguments = assistant_message["function_call"]["arguments"]
perform = locals()[fn_name]
outcome = perform(arguments)
print("Response is: ", outcome)
user_input = enter("Please enter your query right here: ")
Testing Outcomes:
Appointment checking:
Appointment reserving:
Appointment rescheduling:
Appointment deletion:
We’ve got realized methods to create an appointment reserving chatbot utilizing OpenAI’s perform calling function and the Google Calendar API. We’ve got seen how can we use ChatGPT to create closed area chatbots utilizing the perform calling function. You’ll be able to create extra such closed area chatbots utilizing ChatGPT and in addition can combine any exterior APIs.