Introduction to AI Voice Agents in how to build ai voice agents for call centre
What is an AI Voice Agent?
AI Voice Agents are sophisticated software systems designed to interact with humans through voice commands. They leverage advanced technologies such as Speech-to-Text (STT), Language Learning Models (LLM), and Text-to-Speech (TTS) to understand and respond to user queries in natural language. These agents are capable of performing a wide range of tasks, from answering simple questions to managing complex customer interactions.
Why are they important for the how to build ai voice agents for call centre industry?
In the call centre industry, AI Voice Agents play a crucial role in enhancing customer service efficiency and reducing operational costs. They can handle a large volume of calls simultaneously, provide 24/7 support, and free up human agents for more complex tasks. By automating routine inquiries, AI Voice Agents help improve customer satisfaction and streamline call centre operations.
Core Components of a Voice Agent
The core components of a Voice Agent include:
- Speech-to-Text (STT): Converts spoken language into text.
- Language Learning Model (LLM): Processes the text to understand and generate appropriate responses.
- Text-to-Speech (TTS): Converts the generated text responses back into speech.
What You'll Build in This Tutorial
In this tutorial, you will learn how to build an AI Voice Agent using the VideoSDK AI Agents framework. We will guide you through setting up the environment, creating a custom agent, and testing it in a simulated call centre environment. For a detailed setup, refer to the
Voice Agent Quick Start Guide
.Architecture and Core Concepts
High-Level Architecture Overview
The architecture of an AI Voice Agent involves several stages, from capturing user speech to delivering a response. Here’s a high-level overview of the data flow:
1sequenceDiagram
2 participant User
3 participant VoiceAgent
4 participant STT
5 participant LLM
6 participant TTS
7 User->>VoiceAgent: Speaks
8 VoiceAgent->>STT: Convert Speech to Text
9 STT->>LLM: Process Text
10 LLM->>TTS: Generate Response
11 TTS->>VoiceAgent: Convert Text to Speech
12 VoiceAgent->>User: Responds
13Understanding Key Concepts in the VideoSDK Framework
- Agent: Represents the core of your AI Voice Agent. It handles interactions and manages the conversation flow.
- CascadingPipeline: Manages the sequence of audio processing, including STT, LLM, and TTS. Learn more about the
Cascading pipeline in AI voice Agents
. - VAD & TurnDetector: Voice Activity Detection (VAD) and Turn Detection are crucial for determining when the agent should listen and respond.
Setting Up the Development Environment
Prerequisites
Before you begin, ensure you have Python 3.11+ installed and create an account on VideoSDK at app.videosdk.live.
Step 1: Create a Virtual Environment
To keep dependencies organized, create a virtual environment:
1python -m venv venv
2source venv/bin/activate # On Windows use `venv\\Scripts\\activate`
3Step 2: Install Required Packages
Install the necessary packages using pip:
1pip install videosdk
2pip install python-dotenv
3Step 3: Configure API Keys in a .env file
Create a
.env file in your project directory to store your API keys securely:1VIDEOSDK_API_KEY=your_api_key_here
2Building the AI Voice Agent: A Step-by-Step Guide
Here is the complete, runnable code for our AI Voice Agent:
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 an AI Voice Agent designed specifically for call centers. Your primary role is to assist customers by providing accurate information and resolving common inquiries efficiently. You are a friendly and professional virtual assistant who can handle a wide range of tasks, including answering frequently asked questions, processing simple transactions, and directing calls to the appropriate human agents when necessary. Your capabilities include understanding and responding to customer queries in natural language, accessing and updating customer account information, and providing real-time support. However, you must adhere to the following constraints: you cannot make decisions that require human judgment, you must always maintain customer privacy and data security, and you should clearly state when a task is beyond your capabilities and escalate it to a human agent. Additionally, you are not authorized to provide legal, financial, or medical advice, and you must always include a disclaimer to consult a professional for such matters."
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()
63Step 4.1: Generating a VideoSDK Meeting ID
To interact with the agent, you need a meeting ID. You can generate one using the VideoSDK API. Here’s an example using
curl:1curl -X POST https://api.videosdk.live/v1/meetings -H "Authorization: YOUR_API_KEY"
2This will return a JSON response with a
meetingId which you will use in your agent setup.Step 4.2: Creating the Custom Agent Class
The
MyVoiceAgent class extends the Agent class from the VideoSDK framework. It defines the agent’s behavior when 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!")
6This class is initialized with specific instructions tailored for a call centre environment.
Step 4.3: Defining the Core Pipeline
The
CascadingPipeline is the backbone of the voice agent, managing the flow of audio processing. Here’s how it’s set up: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)
8Each component is responsible for a specific task: STT converts speech to text, LLM processes the text, and TTS converts the response back to speech. VAD and Turn Detector manage when the agent listens and responds. For more details on the
Deepgram STT Plugin for voice agent
,OpenAI LLM Plugin for voice agent
, andElevenLabs TTS Plugin for voice agent
, refer to their respective documentation.Step 4.4: Managing the Session and Startup Logic
The session management and startup logic are handled in the
start_session function and the make_context function:1async def start_session(context: JobContext):
2 # Create agent and conversation flow
3 agent = MyVoiceAgent()
4 conversation_flow = ConversationFlow(agent)
5
6 # Create pipeline
7 pipeline = CascadingPipeline(...)
8
9 session = AgentSession(
10 agent=agent,
11 pipeline=pipeline,
12 conversation_flow=conversation_flow
13 )
14
15 try:
16 await context.connect()
17 await session.start()
18 # Keep the session running until manually terminated
19 await asyncio.Event().wait()
20 finally:
21 # Clean up resources when done
22 await session.close()
23 await context.shutdown()
24The
make_context function sets up the room options for the agent:1def make_context() -> JobContext:
2 room_options = RoomOptions(
3 name="VideoSDK Cascaded Agent",
4 playground=True
5 )
6 return JobContext(room_options=room_options)
7The main entry point starts the agent session:
1if __name__ == "__main__":
2 job = WorkerJob(entrypoint=start_session, jobctx=make_context)
3 job.start()
4Running and Testing the Agent
Step 5.1: Running the Python Script
To run your AI Voice Agent, execute the Python script:
1python main.py
2This will start the agent and display a playground link in the console.
Step 5.2: Interacting with the Agent in the Playground
Visit the playground link to interact with your agent. You can test various scenarios and see how the agent responds in real-time. For a comprehensive understanding of the
AI voice Agent core components overview
, refer to the documentation.Advanced Features and Customizations
Extending Functionality with Custom Tools
The VideoSDK framework allows you to extend your agent’s capabilities with custom tools, known as
function_tool. These tools can be used to integrate additional functionalities specific to your needs.Exploring Other Plugins
While this tutorial uses specific plugins for STT, LLM, and TTS, the VideoSDK framework supports various other options. You can explore different plugins to optimize performance and cost. For example, the
Silero Voice Activity Detection
andTurn detector for AI voice Agents
are crucial for managing audio input.Troubleshooting Common Issues
API Key and Authentication Errors
Ensure that 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. Ensure that the correct devices are selected and that they are functioning properly.
Dependency and Version Conflicts
Make sure all dependencies are installed with compatible versions. Use a virtual environment to manage dependencies effectively.
Conclusion
Summary of What You've Built
In this tutorial, you have built a functional AI Voice Agent for call centres using the VideoSDK framework. You’ve learned how to set up the environment, create a custom agent, and test it in a simulated environment.
Next Steps and Further Learning
To further enhance your AI Voice Agent, consider exploring additional plugins and customizing the agent’s capabilities to better suit your specific needs. Continue learning about AI technologies to stay ahead in the rapidly evolving field of customer service automation. For more detailed sessions, refer to
AI voice Agent Sessions
.Want to level-up your learning? Subscribe now
Subscribe to our newsletter for more tech based insights
FAQ