Build an AI Voice Agent with Open Source STT

Step-by-step guide to building an AI Voice Agent using open source STT engines with VideoSDK.

Introduction to AI Voice Agents in Open Source STT Engine

What is an AI

Voice Agent

?

An AI

Voice Agent

is a software application designed to interact with users through voice commands. These agents can understand and respond to spoken language, making them ideal for applications like virtual assistants, customer service bots, and more. They utilize technologies like Speech-to-Text (STT), Text-to-Speech (TTS), and language models to process and generate human-like responses.

Why are they important for the open source STT engine industry?

AI Voice Agents play a crucial role in the open source STT engine industry by making speech technology more accessible and customizable. They enable developers to integrate voice capabilities into their applications without relying on proprietary solutions, fostering innovation and collaboration within the community.

Core Components of a

Voice Agent

  • Speech-to-Text (STT): Converts spoken language into text.
  • Language Model (LLM): Processes the text to understand and generate responses.
  • Text-to-Speech (TTS): Converts text back into spoken language for the user.

What You'll Build in This Tutorial

In this tutorial, you will learn to build an AI

Voice Agent

using open source STT engines with the VideoSDK framework. We'll guide you through setting up the environment, creating the agent, and testing it in a

playground

.

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 using STT, generating a response with a language model, and finally converting the response back to speech using TTS. This flow ensures seamless interaction between the user and the agent.
Diagram

Understanding Key Concepts in the VideoSDK Framework

  • Agent: The core class representing your bot, responsible for handling user interactions.
  • Cascading Pipeline

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

Setting Up the Development Environment

Prerequisites

To get started, you'll need Python 3.11+ and a VideoSDK account, which you can create at app.videosdk.live.

Step 1: Create a Virtual Environment

Create a virtual environment to manage your project 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
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

Here is the complete, runnable 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 an AI Voice Agent specializing in providing information and guidance on open source speech-to-text (STT) engines. Your persona is that of a knowledgeable and friendly tech assistant. Your primary capabilities include:
14
151. Explaining the features and benefits of various open source STT engines.
162. Providing guidance on how to integrate these engines into different applications.
173. Offering troubleshooting tips for common issues encountered with open source STT engines.
184. Recommending resources and documentation for further learning.
19
20Constraints and limitations:
21
221. You are not a software developer, so you cannot provide custom code solutions.
232. You must always encourage users to verify information with official documentation or consult with a professional for complex integration tasks.
243. You cannot endorse any specific product or service; your role is to provide unbiased information."
25
26class MyVoiceAgent(Agent):
27    def __init__(self):
28        super().__init__(instructions=agent_instructions)
29    async def on_enter(self): await self.session.say("Hello! How can I help?")
30    async def on_exit(self): await self.session.say("Goodbye!")
31
32async def start_session(context: JobContext):
33    # Create agent and conversation flow
34    agent = MyVoiceAgent()
35    conversation_flow = ConversationFlow(agent)
36
37    # Create pipeline
38    pipeline = CascadingPipeline(
39        stt=DeepgramSTT(model="nova-2", language="en"),
40        llm=OpenAILLM(model="gpt-4o"),
41        tts=ElevenLabsTTS(model="eleven_flash_v2_5"),
42        vad=[Silero Voice Activity Detection](https://docs.videosdk.live/ai_agents/plugins/silero-vad)(threshold=0.35),
43        turn_detector=[Turn detector for AI voice Agents](https://docs.videosdk.live/ai_agents/plugins/turn-detector)(threshold=0.8)
44    )
45
46    session = [AI voice Agent Sessions](https://docs.videosdk.live/ai_agents/core-components/agent-session)(
47        agent=agent,
48        pipeline=pipeline,
49        conversation_flow=conversation_flow
50    )
51
52    try:
53        await context.connect()
54        await session.start()
55        # Keep the session running until manually terminated
56        await asyncio.Event().wait()
57    finally:
58        # Clean up resources when done
59        await session.close()
60        await context.shutdown()
61
62def make_context() -> JobContext:
63    room_options = RoomOptions(
64    #  room_id="YOUR_MEETING_ID",  # Set to join a pre-created room; omit to auto-create
65        name="VideoSDK Cascaded Agent",
66        playground=True
67    )
68
69    return JobContext(room_options=room_options)
70
71if __name__ == "__main__":
72    job = WorkerJob(entrypoint=start_session, jobctx=make_context)
73    job.start()
74

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/rooms" \
2-H "Authorization: Bearer YOUR_VIDEOSDK_API_KEY" \
3-H "Content-Type: application/json" \
4-d '{"name": "My Meeting Room"}'
5

Step 4.2: Creating the Custom Agent Class

The MyVoiceAgent class extends the Agent class, providing custom behavior for entering and exiting conversations. This class defines how the agent greets users and says goodbye, setting the tone for interactions.

Step 4.3: Defining the Core Pipeline

The CascadingPipeline is the heart of the voice agent, connecting STT, LLM, and TTS plugins. Each plugin plays a specific role:
  • DeepgramSTT: Converts speech to text using the "nova-2" model.
  • OpenAILLM: Processes text using the "gpt-4o" model to generate responses.
  • ElevenLabsTTS: Converts text responses back to speech.
  • SileroVAD: Detects voice activity to manage when the agent listens.
  • TurnDetector: Helps manage conversation flow by detecting when a user has finished speaking.

Step 4.4: Managing the Session and Startup Logic

The start_session function initializes the agent session, connecting the agent, pipeline, and conversation flow. The make_context function sets up the room options, enabling the playground for testing. Finally, the if __name__ == "__main__": block starts the agent, allowing it to run continuously until manually stopped.

Running and Testing the Agent

Step 5.1: Running the Python Script

Run the script using:
1python main.py
2

Step 5.2: Interacting with the Agent in the Playground

After running the script, find the playground link in the console. Use this link to join the session and interact with your AI Voice Agent. You can test its capabilities by speaking to it and observing its responses.

Advanced Features and Customizations

Extending Functionality with Custom Tools

You can enhance your agent by integrating custom tools, allowing it to perform additional tasks or access external data sources.

Exploring Other Plugins

The VideoSDK framework supports various STT, LLM, and TTS plugins, providing flexibility to choose the best tools for your needs.

Troubleshooting Common Issues

API Key and Authentication Errors

Ensure your API key is correctly set in the .env file and that you have the necessary permissions.

Audio Input/Output Problems

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

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 Agent using open source STT engines and the VideoSDK framework. This agent can understand and respond to user queries, providing a foundation for more advanced applications.

Next Steps and Further Learning

Explore additional plugins and customizations to extend your agent's capabilities. Consider integrating it into real-world applications to enhance user experiences.

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