June 25, 2024 No Comments

What is VapiAI?

Vapi is the Voice AI platform designed specifically for developers, streamlining the process of creating voice AI agents. With Vapi, developers can build, test, and deploy voice AI applications in mere minutes instead of the typical months. This platform addresses the fundamental challenges inherent in voice AI development, offering a robust and efficient solution for bringing voice AI projects to life quickly and effectively.

Why are we using VapiAI?

We chose Vapi for building our voice bot(appointment booking chatbot) due to several key advantages that enhance both performance and development efficiency. First, Vapi provides low latency in voice responses, ensuring our users experience quick and seamless interactions. Additionally, Vapi supports both inbound and outbound calls, expanding our chatbot’s functionality and versatility. The platform is designed for fast and easy development, significantly reducing the time and effort required to build, test, and deploy our solution. With these features, Vapi enables us to deliver a high-quality, responsive, and versatile appointment-booking chatbot, overcoming the typical technical challenges of voice AI development.

Setup the Flask app

To get started, create a file named ‘app.py’ and add the following code snippet to it. Before running the application, ensure you set up a virtual environment and install the required dependencies using the following commands:

				
					
pip install Flask
pip install openai==0.28.0
				
			
app.py
				
					from flask import Flask, request, jsonify, Response
import openai, json
from datetime import date
from time import time

app = Flask(__name__)
openai.api_key = ""  # Replace with your actual OpenAI API key

@app.route("/chat/completions", methods=["POST"])
def chat_completions():
   try:
       request_data = request.get_json()

       # Define a list of days for reference
       day_list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

       # Initial message with system instructions
       messages = [
           {"role": "system", "content": f'''
           You are an expert in booking appointments. When a user asks to book, cancel, or reschedule an appointment, ask for their mobile number first and confirm it to ensure it is correct. Once confirmed, proceed to check for any booked appointments associated with that number. You need to ask the user for their name, appointment date, and appointment time. After that, ask the user for their mobile number. Appointments can be booked from 10 AM to 7 PM, Monday to Friday, and from 10 AM to 2 PM on Saturdays. Today's date is {date.today()} and today is {day_list[date.today().weekday()]}. Check if the time provided by the user is within the working hours before proceeding.

           Instructions:

           - Whenever the user provides a mobile number, confirm it with them.
           - Don't make assumptions about what values to plug into functions. If the user does not provide any of the required parameters, ask for clarification.
           - If a user request is ambiguous, ask for clarification.
           - When a user asks to reschedule, request the new appointment details only.
           - If the user did not specify "AM" or "PM" when providing the time, ask for clarification. If the user did not provide the day, month, and year when giving the time, ask for clarification.

           Make sure to follow the instructions carefully while processing the request.
           '''}
       ]

       # Extend initial messages with user-provided messages if any
       message_data = request_data.get("messages", "")
       messages.extend(message_data)
       print("User's Response: ",message_data[-1]['content'])
       # Send messages to OpenAI for processing
       response = openai.ChatCompletion.create(
           model="gpt-3.5-turbo",
           messages=messages
       )

       # Format OpenAI response according to a specified structure
       messages = response['choices'][0]['message']['content']
       print("Bot's Response: ", messages)
       data_chunks = [{
           'id': response['id'],
           'object': response['object'],
           'created': response['created'],
           'model': response['model'],
           'system_fingerprint': response['system_fingerprint'],
           'choices': [
               {
                   'index': response['choices'][0]['index'],
                   'delta': {'content': messages},
                   'logprobs': response['choices'][0]['logprobs'],
                   'finish_reason': response['choices'][0]['finish_reason'],
               },
           ],
       }]

       # Function to generate Server-Sent Events (SSE)
       def generate():
           for chunk in data_chunks:
               yield f"data: {json.dumps(chunk)}\n\n"
           yield "data: [DONE]\n\n"

       # Create a formatted SSE response
       formatted_response = Response(generate(), content_type='text/event-stream')
       formatted_response.headers['Cache-Control'] = 'no-cache'
       formatted_response.headers['Connection'] = 'keep-alive'

       return formatted_response

   except Exception as e:
       print(e)  # Log any exceptions for debugging
       return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
   app.run(debug=False, use_reloader=False, port=5000)
				
			

Once dependencies are installed, run your Flask application and then start NGROK to expose it on port 5000.

Note: We are using OpenAI’s “gpt-3.5-turbo” for the custom LLM model.

This setup will allow you to seamlessly integrate and interact with the functionalities provided by Flask and OpenAI. 

Configure the VapiAI dashboard

To begin, navigate to the VapiAI dashboard (if you haven’t signed up, please do so first). Create a new assistant and set the initial message(you can set it according to your bot) to:

“Hello, this is Mittal from Pragnakalp Techlabs Appointment Booking Service. How can I assist you today?”

Ensure your settings match those shown in the screenshot. Paste your ngrok URL into the ‘Custom LLM URL’ field, publish your assistant, and now time to initiate a call to test the voice bot. 

Test voice bot by Web call

To test your setup, VapiAI provides a web call service. After you have completed the setup and published your voice assistant, click on the ‘Talk with <your bot name>’ button (as shown in the screenshot). This will connect you to your voice bot over a call. Ensure your Flask app and ngrok are running correctly before making the call.

Test voice bot by call

To test the voice bot via call, first set up your phone number in the “Phone Number” section. You can buy a phone number from VapiAI if you’ve already provided card details, or you can add a number from Twilio or Vonage account. For Twilio or Vonage, provide the necessary details and import your number. Once your number is set up, you can test your voice bot by making calls. You can generate both inbound and outbound calls. Below is a screenshot of the UI for your reference.

When you initiate the booking process on the call, you will see logs on the Flask app. These logs will display the conversation between the user and the bot, allowing you to monitor and debug the interaction.

Conclusion

In this blog, we explored how VapiAI offers a streamlined and efficient platform for developers to create, test, and deploy voice AI applications rapidly. By integrating VapiAI with a Flask application and OpenAI’s GPT-3.5-turbo, developers can build a robust appointment booking chatbot with minimal latency and high performance. 

If you want to connect this appointment booking bot with Google Calendar, please follow this blog: How To Use OpenAI Function Calling To Create Appointment Booking Chatbot.

If you want to connect this appointment booking bot with Google Calendar, please follow this blog: Appointment Booking Chatbot Using OpenAI Function Calling And GoHighLevel Calendar.

Write a comment

Your email address will not be published. Required fields are marked *

Want to talk to an Expert Developer?

Our experts in Generative AI, Python Programming, and Chatbot Development can help you build innovative solutions and scale your business faster.