Build an AI Voice Assistant for Booking

Step-by-step guide to building an AI voice assistant for appointment booking using VideoSDK.

Introduction to AI Voice Agents in How to Build AI Voice Assistant for Appointment Booking

AI Voice Agents are sophisticated systems designed to interpret human speech, process the information, and respond in a human-like manner. These agents are increasingly becoming integral in industries like healthcare, where they can streamline processes such as appointment booking.

What is an AI

Voice Agent

?

An AI

Voice Agent

is a software application that uses artificial intelligence to interact with users through voice commands. It leverages technologies like Speech-to-Text (STT), Language Learning Models (LLM), and Text-to-Speech (TTS) to understand and respond to user queries.

Why are they important for the Appointment Booking Industry?

In the healthcare industry, AI Voice Agents can significantly reduce the workload on administrative staff by automating appointment scheduling, rescheduling, and cancellations. This not only improves efficiency but also enhances patient experience by providing 24/7 assistance.

Core Components of a

Voice Agent

  • STT (Speech-to-Text): Converts spoken language into text.
  • LLM (Language Learning Model): Processes the text to understand context and intent.
  • TTS (Text-to-Speech): Converts the processed text back into speech.
For a detailed

AI voice Agent core components overview

, you can explore how these elements interact to form a cohesive system.

What You'll Build in This Tutorial

In this guide, we will build a voice assistant capable of booking appointments using the VideoSDK framework. We will cover everything from setting up your environment to running and testing your agent.

Architecture and Core Concepts

High-Level Architecture Overview

The architecture of an AI

Voice Agent

involves several components that work together to process user input and generate responses. The process begins with capturing user speech, which is then converted to text, processed for understanding, and finally converted back to speech for the response.
Diagram

Understanding Key Concepts in the VideoSDK Framework

  • Agent: The core class representing your bot. It handles interactions and manages the conversation flow.
  • CascadingPipeline: A sequence of processing steps that handle audio input and output, including STT, LLM, and TTS. Learn more about the

    Cascading pipeline in AI voice Agents

    .
  • VAD & TurnDetector: These components help the agent determine when to listen and when to speak, ensuring smooth interaction.

Setting Up the Development Environment

Prerequisites

To follow this tutorial, ensure you have Python 3.11+ installed and a VideoSDK account, which you can create at app.videosdk.live.

Step 1: Create a Virtual Environment

Run the following command to create a virtual environment:
1python -m venv venv
2source venv/bin/activate  # On Windows use `venv\Scripts\activate`
3

Step 2: Install Required Packages

Install the necessary packages using pip:
1pip install videosdk
2pip install python-dotenv
3

Step 3: Configure API Keys in a .env file

Create a .env file in your project directory and add your VideoSDK API key:
1VIDEOSDK_API_KEY=your_api_key_here
2

Building the AI Voice Agent: A Step-by-Step Guide

Below is the complete code for our AI Voice Assistant. We will break it down into smaller parts to explain each component.
1import asyncio, os
2from videosdk.agents import Agent, AgentSession, CascadingPipeline, JobContext, RoomOptions, WorkerJob, ConversationFlow
3from videosdk.plugins.silero import SileroVAD
4from videosdk.plugins.turn_detector import TurnDetector, pre_download_model
5from videosdk.plugins.deepgram import DeepgramSTT
6from videosdk.plugins.openai import OpenAILLM
7from videosdk.plugins.elevenlabs import ElevenLabsTTS
8from typing import AsyncIterator
9
10# Pre-downloading the Turn Detector model
11pre_download_model()
12
13agent_instructions = "You are a helpful healthcare assistant AI Voice Agent designed to assist users in booking appointments. Your primary role is to facilitate the scheduling of appointments by understanding user requests and interacting with the appointment booking system. You can answer questions related to available time slots, rescheduling, and cancellations. However, you are not a medical professional and must include a disclaimer advising users to consult a doctor for medical advice. You should ensure user privacy and data security at all times, and you must not store any personal information beyond the session. Your responses should be clear, concise, and user-friendly, guiding users through the appointment booking process efficiently."
14
15class MyVoiceAgent(Agent):
16    def __init__(self):
17        super().__init__(instructions=agent_instructions)
18    async def on_enter(self): await self.session.say("Hello! How can I help?")
19    async def on_exit(self): await self.session.say("Goodbye!")
20
21async def start_session(context: JobContext):
22    # Create agent and conversation flow
23    agent = MyVoiceAgent()
24    conversation_flow = ConversationFlow(agent)
25
26    # Create pipeline
27    pipeline = CascadingPipeline(
28        stt=DeepgramSTT(model="nova-2", language="en"),
29        llm=OpenAILLM(model="gpt-4o"),
30        tts=ElevenLabsTTS(model="eleven_flash_v2_5"),
31        vad=SileroVAD(threshold=0.35),
32        turn_detector=TurnDetector(threshold=0.8)
33    )
34
35    session = AgentSession(
36        agent=agent,
37        pipeline=pipeline,
38        conversation_flow=conversation_flow
39    )
40
41    try:
42        await context.connect()
43        await session.start()
44        # Keep the session running until manually terminated
45        await asyncio.Event().wait()
46    finally:
47        # Clean up resources when done
48        await session.close()
49        await context.shutdown()
50
51def make_context() -> JobContext:
52    room_options = RoomOptions(
53    #  room_id="YOUR_MEETING_ID",  # Set to join a pre-created room; omit to auto-create
54        name="VideoSDK Cascaded Agent",
55        playground=True
56    )
57
58    return JobContext(room_options=room_options)
59
60if __name__ == "__main__":
61    job = WorkerJob(entrypoint=start_session, jobctx=make_context)
62    job.start()
63

Step 4.1: Generating a VideoSDK Meeting ID

To create a meeting ID, use the following curl command:
1curl -X POST https://api.videosdk.live/v1/rooms \
2-H "Authorization: Bearer YOUR_API_KEY" \
3-H "Content-Type: application/json" \
4-d '{"region": "us-west"}'
5

Step 4.2: Creating the Custom Agent Class

The MyVoiceAgent class is where we define the agent's behavior. It inherits from the Agent class and overrides methods to handle entering and exiting a session.
1class MyVoiceAgent(Agent):
2    def __init__(self):
3        super().__init__(instructions=agent_instructions)
4    async def on_enter(self): await self.session.say("Hello! How can I help?")
5    async def on_exit(self): await self.session.say("Goodbye!")
6

Step 4.3: Defining the Core Pipeline

The CascadingPipeline is a crucial part of the agent, managing the flow of audio processing using STT, LLM, and TTS plugins. The

Deepgram STT Plugin for voice agent

and

OpenAI LLM Plugin for voice agent

are integral to this setup.
1pipeline = CascadingPipeline(
2    stt=DeepgramSTT(model="nova-2", language="en"),
3    llm=OpenAILLM(model="gpt-4o"),
4    tts=ElevenLabsTTS(model="eleven_flash_v2_5"),
5    vad=SileroVAD(threshold=0.35),
6    turn_detector=TurnDetector(threshold=0.8)
7)
8

Step 4.4: Managing the Session and Startup Logic

The start_session function initializes the session and manages the lifecycle of the agent. The

AI voice Agent Sessions

are crucial for maintaining the interaction flow.
1def make_context() -> JobContext:
2    room_options = RoomOptions(
3    #  room_id="YOUR_MEETING_ID",  # Set to join a pre-created room; omit to auto-create
4        name="VideoSDK Cascaded Agent",
5        playground=True
6    )
7
8    return JobContext(room_options=room_options)
9
10if __name__ == "__main__":
11    job = WorkerJob(entrypoint=start_session, jobctx=make_context)
12    job.start()
13

Running and Testing the Agent

Step 5.1: Running the Python Script

To start the agent, run the following command in your terminal:
1python main.py
2

Step 5.2: Interacting with the Agent in the Playground

After starting the script, look for the

AI Agent playground

link in your console. Use this link to join the session and interact with your voice agent.

Advanced Features and Customizations

Extending Functionality with Custom Tools

You can extend the functionality of your voice agent by integrating custom tools or APIs to handle specific tasks.

Exploring Other Plugins

The VideoSDK framework supports various STT, LLM, and TTS plugins. You can explore alternatives based on your specific needs.

Troubleshooting Common Issues

API Key and Authentication Errors

Ensure your API keys are correctly set in the .env file and that they have the necessary permissions.

Audio Input/Output Problems

Check your microphone and speaker settings, and ensure your system permissions allow audio access.

Dependency and Version Conflicts

Verify that all dependencies are installed and compatible with your Python version.

Conclusion

Summary of What You've Built

In this tutorial, you've built a fully functional AI Voice Assistant capable of booking appointments using the VideoSDK framework.

Next Steps and Further Learning

Consider exploring additional plugins and customizations to enhance your agent's capabilities and learn more about the VideoSDK framework.

Start Building With Free $20 Balance

No credit card required to start.

Want to level-up your learning? Subscribe now

Subscribe to our newsletter for more tech based insights

FAQ