Build a Voice Agent with Analytics

Step-by-step guide to building an AI voice agent with analytics using VideoSDK.

Introduction to AI Voice Agents in Voice Agent Analytics

What is an AI Voice Agent?

An AI Voice Agent is a software application designed to interact with users through voice commands. It processes spoken language, interprets it, and responds in a conversational manner. These agents leverage technologies such as Speech-to-Text (STT), Language Models (LLM), and Text-to-Speech (TTS) to facilitate seamless communication.

Why are they important for the voice agent analytics industry?

In the voice agent analytics industry, AI Voice Agents play a crucial role by providing insights into user interactions. They help businesses understand user behavior, measure engagement, and improve service delivery. Use cases include customer support, virtual assistants, and interactive voice response systems.

Core Components of a Voice Agent

  • STT (Speech-to-Text): Converts spoken language into text.
  • LLM (Language Model): Interprets and processes the text to generate a response.
  • TTS (Text-to-Speech): Converts the text response back into spoken language.

What You'll Build in This Tutorial

In this tutorial, you will build a voice agent capable of providing analytics insights. You will learn to set up the environment, construct the agent, and test its functionality using the VideoSDK framework. For a comprehensive 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, starting with capturing user speech, processing it through various components, and finally generating a response. A key part of this architecture is the

Cascading pipeline in AI voice Agents

, which ensures efficient data flow.
Diagram

Understanding Key Concepts in the VideoSDK Framework

Setting Up the Development Environment

Prerequisites

To get started, ensure you have Python 3.11+ installed. You will also need a VideoSDK account, which you can create at app.videosdk.live.

Step 1: Create a Virtual Environment

Create a virtual environment to manage your dependencies:
1python -m venv voice-agent-env
2source voice-agent-env/bin/activate  # On Windows use `voice-agent-env\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 in your project directory and add your VideoSDK API keys:
1VIDEOSDK_API_KEY=your_api_key_here
2

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

Here is the complete code for the 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 a 'Voice Agent Analytics Specialist', designed to assist users in understanding and utilizing voice agent analytics effectively. Your primary role is to provide insights into voice agent performance metrics, guide users on setting up analytics dashboards, and offer tips on optimizing voice agent interactions based on data analysis.\n\nCapabilities:\n1. Explain key performance indicators (KPIs) related to voice agent analytics, such as response time, user engagement, and accuracy.\n2. Assist users in setting up and configuring analytics tools to monitor voice agent performance.\n3. Provide data-driven recommendations for improving voice agent interactions and user satisfaction.\n4. Answer questions about common analytics platforms and tools used in voice agent analytics.\n\nConstraints and Limitations:\n1. You are not a data scientist and should not provide in-depth statistical analysis or predictions.\n2. Always remind users to verify analytics data with their internal data teams for critical decision-making.\n3. You cannot access or manipulate users' personal data or analytics dashboards directly.\n4. Ensure users are aware of privacy and data protection regulations when discussing analytics data."
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 generate a meeting ID, use the following curl command:
1curl -X POST "https://api.videosdk.live/v1/meetings" \
2-H "Authorization: Bearer YOUR_API_KEY" \
3-H "Content-Type: application/json"
4

Step 4.2: Creating the Custom Agent Class

The MyVoiceAgent class is where you define the behavior of your voice agent. This class inherits from the Agent class and implements methods such as on_enter and on_exit to handle session start and end events.
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 central to processing audio data. It connects the STT, LLM, and TTS components, allowing seamless data flow. For TTS, consider using the

ElevenLabs TTS Plugin for voice agent

, and for STT, the

Deepgram STT Plugin for voice agent

is recommended.
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 manages the agent session lifecycle, ensuring the agent connects and runs correctly.
1async def start_session(context: JobContext):
2    agent = MyVoiceAgent()
3    conversation_flow = ConversationFlow(agent)
4    pipeline = CascadingPipeline(
5        stt=DeepgramSTT(model="nova-2", language="en"),
6        llm=OpenAILLM(model="gpt-4o"),
7        tts=ElevenLabsTTS(model="eleven_flash_v2_5"),
8        vad=SileroVAD(threshold=0.35),
9        turn_detector=TurnDetector(threshold=0.8)
10    )
11    session = AgentSession(
12        agent=agent,
13        pipeline=pipeline,
14        conversation_flow=conversation_flow
15    )
16    try:
17        await context.connect()
18        await session.start()
19        await asyncio.Event().wait()
20    finally:
21        await session.close()
22        await context.shutdown()
23

Running and Testing the Agent

Step 5.1: Running the Python Script

Run the script using Python:
1python main.py
2

Step 5.2: Interacting with the Agent in the Playground

Once the script is running, find the playground link in the console output. Use this link to join the session and interact with your voice agent. For detailed session metrics, refer to

AI voice Agent Session Analytics

.

Advanced Features and Customizations

Extending Functionality with Custom Tools

You can extend the agent's functionality by integrating custom tools using the function_tool concept in the VideoSDK framework.

Exploring Other Plugins

The VideoSDK framework supports various plugins for STT, LLM, and TTS. Consider exploring other options to enhance your agent's capabilities, such as the

OpenAI LLM Plugin for voice agent

.

Troubleshooting Common Issues

API Key and Authentication Errors

Ensure your API key is correctly configured in the .env file. Double-check for typos and ensure your account is active.

Audio Input/Output Problems

Verify your microphone and speaker settings. Ensure they are correctly configured and accessible by the application.

Dependency and Version Conflicts

Ensure all dependencies are up-to-date and compatible with Python 3.11+. Use a virtual environment to manage packages effectively.

Conclusion

Summary of What You've Built

In this tutorial, you've built a fully functional AI Voice Agent capable of providing analytics insights. You've learned to set up the environment, construct the agent, and test its functionality.

Next Steps and Further Learning

Explore advanced features and customizations to enhance your agent. Consider integrating more complex analytics tools and expanding the agent's capabilities.

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