Build an AI Voice Assistant for Lead Qualification

Step-by-step guide to building an AI voice assistant for lead qualification using VideoSDK.

Introduction to AI Voice Agents in How to Build AI Voice Assistant for Lead Qualification

What is an AI

Voice Agent

?

An AI

Voice Agent

is a software program designed to interact with users through voice. It processes spoken language, understands the intent, and responds appropriately. These agents use technologies like Speech-to-Text (STT), Natural Language Processing (NLP), and Text-to-Speech (TTS) to facilitate seamless communication.

Why are they important for the Lead Qualification Industry?

In the lead qualification industry, AI Voice Agents play a crucial role in automating the initial stages of customer interaction. They can engage potential leads, ask qualifying questions, and gather essential information, thus freeing up human resources for more complex tasks. This automation leads to increased efficiency and better lead management.

Core Components of a

Voice Agent

  • Speech-to-Text (STT): Converts spoken words into text.
  • Large Language Models (LLM): Understands and processes the text to determine the intent.
  • Text-to-Speech (TTS): Converts the processed response back into speech.

What You'll Build in This Tutorial

In this tutorial, you will build an AI Voice Assistant specifically designed for lead qualification using the VideoSDK framework. This guide will take you through setting up your development environment, building the agent, and testing it in a simulated environment.

Architecture and Core Concepts

High-Level Architecture Overview

The AI

Voice Agent

processes user speech through a series of steps: capturing audio, converting it to text, understanding the intent, generating a response, and converting it back to speech. This flow ensures real-time interaction with users.
Diagram

Understanding Key Concepts in the VideoSDK Framework

  • Agent: The core class that represents your bot, handling interactions.
  • Cascading Pipeline in AI voice Agents

    :
    Manages the flow of audio processing from STT to LLM to TTS.
  • VAD & TurnDetector: These components help the agent determine when to listen and when to speak, ensuring smooth conversation flow.

Setting Up the Development Environment

Prerequisites

To get started, ensure you have Python 3.11+ installed and a VideoSDK account. You can sign up at app.videosdk.live.

Step 1: Create a Virtual Environment

Create a virtual environment to manage dependencies:
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
2

Step 3: Configure API Keys in a .env File

Create a .env file to store your API keys securely:
1VIDEOSDK_API_KEY=your_api_key_here
2

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

Below is the complete code for building your AI Voice Agent. We'll break it down into parts for detailed explanations.
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 Assistant specialized in lead qualification for businesses. Your primary role is to engage potential customers in a conversational manner to gather essential information that qualifies them as leads. You should be friendly, professional, and efficient in your interactions.\n\nCapabilities:\n1. Initiate conversations with potential leads using a predefined script.\n2. Ask relevant questions to determine the lead's interest, budget, and timeline.\n3. Record and organize the gathered information for further analysis by the sales team.\n4. Provide basic information about the company's products or services.\n5. Transfer the call to a human sales representative if the lead meets certain criteria or requests further assistance.\n\nConstraints:\n1. You must not provide any personal opinions or advice beyond the scope of the script.\n2. You are not authorized to make any sales offers or commitments.\n3. Always include a disclaimer that the conversation is being recorded for quality and training purposes.\n4. You must adhere to privacy and data protection regulations, ensuring that all personal information is handled securely."
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=[Deepgram STT Plugin for voice agent](https://docs.videosdk.live/ai_agents/plugins/stt/deepgram)(model="nova-2", language="en"),
29        llm=OpenAILLM(model="gpt-4o"),
30        tts=ElevenLabsTTS(model="eleven_flash_v2_5"),
31        vad=[Silero Voice Activity Detection](https://docs.videosdk.live/ai_agents/plugins/silero-vad)(threshold=0.35),
32        turn_detector=[Turn detector for AI voice Agents](https://docs.videosdk.live/ai_agents/plugins/turn-detector)(threshold=0.8)
33    )
34
35    session = [AI voice Agent Sessions](https://docs.videosdk.live/ai_agents/core-components/agent-session)(
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 generate a meeting ID, use the VideoSDK API. Here's an example using curl:
1curl -X POST "https://api.videosdk.live/v1/meetings" \
2-H "Authorization: Bearer YOUR_API_TOKEN" \
3-H "Content-Type: application/json"
4

Step 4.2: Creating the Custom Agent Class

The MyVoiceAgent class is where we define the behavior of our voice agent. It inherits from the Agent class and uses agent_instructions to guide interactions.
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 crucial as it defines how audio is processed. Each plugin plays a specific role:
  • DeepgramSTT: Converts speech to text using the "nova-2" model.
  • OpenAILLM: Processes the text to understand and generate responses using "gpt-4o".
  • ElevenLabsTTS: Converts the response text back to speech.
  • SileroVAD: Detects voice activity to manage when the agent listens.
  • TurnDetector: Helps manage conversational turns.
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 agent session and starts the conversation flow. The make_context function sets up the room options for the session.
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 run your AI Voice Agent, execute the following command:
1python main.py
2

Step 5.2: Interacting with the Agent in the Playground

Once the script is running, you'll see a playground link in the console. Click the link to join the session and interact with your agent. Use Ctrl+C to gracefully shut down the session.

Advanced Features and Customizations

Extending Functionality with Custom Tools

The VideoSDK framework supports custom tools, allowing you to extend your agent's functionality beyond the default capabilities.

Exploring Other Plugins

Consider experimenting with other STT, LLM, and TTS plugins to enhance your agent's performance and capabilities.

Troubleshooting Common Issues

API Key and Authentication Errors

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

Audio Input/Output Problems

Check your microphone and speaker settings to ensure they are correctly configured and working.

Dependency and Version Conflicts

Ensure all dependencies are installed with compatible versions. Use a virtual environment to manage them effectively.

Conclusion

Summary of What You've Built

You have successfully built an AI Voice Assistant for lead qualification using the VideoSDK framework. This agent can engage with potential leads, gather information, and assist in the qualification process.

Next Steps and Further Learning

Explore additional features and plugins offered by VideoSDK to enhance your agent. Consider integrating with CRM systems for a more comprehensive lead management solution.

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