Building a Generative AI Voice Agent

Step-by-step guide to building a generative AI voice agent using VideoSDK. Includes code examples and testing instructions.

Introduction to AI Voice Agents in Generative AI for Voice

What is an AI

Voice Agent

?

An AI

Voice Agent

is a software system designed to interact with users through voice commands. It processes spoken language, understands the intent, and responds appropriately. These agents utilize 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 generative AI for voice industry?

AI Voice Agents play a crucial role in the generative AI for voice industry by enabling natural and dynamic interactions. They are used in various applications such as virtual assistants, customer support, and content creation. These agents enhance user experience by providing instant responses and personalized interactions.

Core Components of a

Voice Agent

  • Speech-to-Text (STT): Converts spoken language into text.
  • Large Language Model (LLM): Understands and generates human-like text based on input.
  • Text-to-Speech (TTS): Converts text back into spoken language.

What You'll Build in This Tutorial

In this tutorial, you will build a generative AI

voice agent

using the VideoSDK framework. The agent will engage in conversations, answer questions, and provide voice feedback in real-time.

Architecture and Core Concepts

High-Level Architecture Overview

The AI

Voice Agent

architecture involves a flow where user speech is captured and processed through various stages to generate a response. The flow typically starts with voice input, which is converted to text using STT. The text is then processed by an LLM to generate a response, which is finally converted back to speech using TTS.

Sequence Diagram

Diagram

Understanding Key Concepts in the VideoSDK Framework

  • Agent: The core class representing your bot. It manages interactions and responses.
  • Cascading Pipeline in AI voice Agents

    :
    Defines the flow of audio processing through STT, LLM, and TTS.
  • VAD & TurnDetector: Used to detect when the agent should listen or speak.

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:
1python3 -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 asyncio
3

Step 3: Configure API Keys

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

Here is the complete code for building 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 = "{\n  \"persona\": \"Generative AI Voice Assistant\",\n  \"capabilities\": [\n    \"Engage in natural and dynamic conversations using generative AI techniques.\",\n    \"Provide information and answer questions on a wide range of topics, including technology, entertainment, and general knowledge.\",\n    \"Assist users in generating creative content such as stories, poems, and dialogues.\",\n    \"Facilitate voice-based interactions and provide voice feedback in real-time.\",\n    \"Adapt conversational style based on user preferences and context.\"\n  ],\n  \"constraints\": [\n    \"You are not a human and should not provide personal opinions or emotions.\",\n    \"Avoid providing medical, legal, or financial advice. Always recommend consulting a professional for such matters.\",\n    \"Ensure user privacy and data security by not storing or sharing personal information.\",\n    \"Maintain a neutral tone and avoid engaging in controversial or sensitive topics.\",\n    \"Limit interactions to voice-based communication and do not attempt to access or control external devices or systems.\"\n  ]\n}"
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=[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 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
This command creates a new meeting and returns a meeting ID that can be used to connect your agent.

Step 4.2: Creating the Custom Agent Class

The MyVoiceAgent class extends the Agent class. It defines the behavior of your voice agent. The on_enter and on_exit methods provide initial and final interactions with the user.

Step 4.3: Defining the Core Pipeline

The CascadingPipeline is the backbone of the agent's processing logic. It integrates:
  • DeepgramSTT: Converts speech to text.
  • OpenAILLM: Processes text and generates responses.
  • ElevenLabsTTS: Converts text responses back to speech.
  • SileroVAD & TurnDetector: Manage when the agent listens and responds.

Step 4.4: Managing the Session and Startup Logic

The start_session function initializes the agent and manages the session lifecycle. The make_context function sets up the environment for the agent, including room options. The if __name__ == "__main__": block ensures the script runs as intended.

Running and Testing the Agent

Step 5.1: Running the Python Script

Run the script using the command:
1python main.py
2
This will start the agent and output a playground link in the console.

Step 5.2: Interacting with the Agent in the Playground

Use the playground link to join the session and interact with the agent. Speak into your microphone and listen to the agent's responses.

Advanced Features and Customizations

Extending Functionality with Custom Tools

You can extend the agent's capabilities by integrating custom tools using the function_tool concept. This allows for adding new features and functionalities.

Exploring Other Plugins

Explore other plugins for STT, LLM, and TTS to customize your agent further. Options include Cartesia for STT, Google Gemini for LLM, and Deepgram for TTS.

Troubleshooting Common Issues

API Key and Authentication Errors

Ensure your API key is correctly configured in the .env file. Check for typos or missing keys.

Audio Input/Output Problems

Verify your microphone and speaker settings. Ensure the correct input and output devices are selected.

Dependency and Version Conflicts

Check your package versions and ensure compatibility. Use a virtual environment to manage dependencies.

Conclusion

Summary of What You've Built

You have successfully built a generative AI voice agent capable of engaging in dynamic conversations. The agent uses VideoSDK to integrate STT, LLM, and TTS technologies.

Next Steps and Further Learning

Explore more advanced features and customizations to enhance your agent. Consider integrating additional plugins and tools to expand its 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