AI Voice Agent Demo API Guide

Step-by-step guide to building an AI Voice Agent using VideoSDK API.

Introduction to AI Voice Agents in ai voice agent demo api

What is an AI Voice Agent?

An AI Voice Agent is a software application that uses artificial intelligence to interact with users through voice commands. These agents can understand natural language, process the information, and respond in a human-like manner. They are designed to assist users in performing tasks, answering questions, and providing information through voice interaction.

Why are they important for the ai voice agent demo api industry?

AI Voice Agents are crucial in the ai voice agent demo api industry as they enhance user experience by providing seamless, hands-free interaction. They can be used in customer service, virtual assistants, and smart devices, offering real-time responses and improving accessibility.

Core Components of a Voice Agent

What You'll Build in This Tutorial

In this tutorial, you will build a simple AI Voice Agent using the VideoSDK API. This agent will demonstrate the integration of various components such as STT, LLM, and TTS, allowing you to interact with it in a simulated environment. For a quick setup, refer to the

Voice Agent Quick Start Guide

.

Architecture and Core Concepts

High-Level Architecture Overview

The AI Voice Agent architecture involves several components working together to process user input and generate responses. The process starts with capturing the user's speech, converting it into text using STT, processing the text with an LLM to determine the appropriate response, and finally using TTS to vocalize the response back to the user.
1sequenceDiagram
2    participant User
3    participant Agent
4    participant STT
5    participant LLM
6    participant TTS
7    User->>Agent: Speak
8    Agent->>STT: Convert Speech to Text
9    STT->>Agent: Text
10    Agent->>LLM: Process Text
11    LLM->>Agent: Response
12    Agent->>TTS: Convert Text to Speech
13    TTS->>User: Speak
14

Understanding Key Concepts in the VideoSDK Framework

Setting Up the Development Environment

Prerequisites

Before you start, ensure you have Python 3.11+ installed and a VideoSDK account, which you can create at app.videosdk.live.

Step 1: Create a Virtual Environment

To manage dependencies, create a virtual environment using the following command:
1python -m venv venv
2
Activate the virtual environment:
  • On Windows: venv\Scripts\activate
  • On macOS/Linux: source venv/bin/activate

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 the root of 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

Below is the complete code for the AI Voice Agent. We'll break it down into smaller parts to understand each component.
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 to demonstrate the capabilities of the VideoSDK API. Your persona is that of a friendly and knowledgeable tech assistant. Your primary role is to showcase how the AI Voice Agent can be integrated and utilized in various applications. You can provide information about the API's features, guide users through basic setup processes, and answer common questions related to the API's usage. However, you are not a developer and cannot provide in-depth technical support or troubleshoot specific code issues. Always encourage users to refer to the official documentation for detailed technical guidance. Remember to maintain a professional and approachable tone throughout the interaction."
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 to interact with the VideoSDK API:
1curl -X POST "https://api.videosdk.live/v1/rooms" 
2-H "Authorization: Bearer YOUR_API_KEY" 
3-H "Content-Type: application/json" 
4-d '{"name":"Demo Room"}'
5

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!")
6

Step 4.3: Defining the Core Pipeline

The CascadingPipeline is responsible for managing the flow of audio processing. It connects the STT, LLM, TTS, VAD, and TurnDetector plugins to create a seamless interaction experience.
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 manages the connection lifecycle. The make_context function sets up the job context, including room options for the playground.
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        stt=DeepgramSTT(model="nova-2", language="en"),
9        llm=OpenAILLM(model="gpt-4o"),
10        tts=ElevenLabsTTS(model="eleven_flash_v2_5"),
11        vad=SileroVAD(threshold=0.35),
12        turn_detector=TurnDetector(threshold=0.8)
13    )
14
15    session = AgentSession(
16        agent=agent,
17        pipeline=pipeline,
18        conversation_flow=conversation_flow
19    )
20
21    try:
22        await context.connect()
23        await session.start()
24        # Keep the session running until manually terminated
25        await asyncio.Event().wait()
26    finally:
27        # Clean up resources when done
28        await session.close()
29        await context.shutdown()
30
The entry point of the script is defined in the if __name__ == "__main__": block, which starts the agent job.
1if __name__ == "__main__":
2    job = WorkerJob(entrypoint=start_session, jobctx=make_context)
3    job.start()
4

Running and Testing the Agent

Step 5.1: Running the Python Script

To run the agent, execute the Python script:
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. Open the link in your browser to interact with the agent. You can speak to the agent and receive responses in real-time. For more detailed guidance, refer to the

AI voice Agent Sessions

.

Advanced Features and Customizations

Extending Functionality with Custom Tools

You can extend the agent's functionality by integrating custom tools. This allows the agent to perform specific tasks or access additional data sources.

Exploring Other Plugins

The VideoSDK framework supports various plugins for STT, LLM, and TTS. You can explore options like Cartesia for STT, Google Gemini for LLM, and Deepgram for TTS to customize your agent's capabilities.

Troubleshooting Common Issues

API Key and Authentication Errors

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

Audio Input/Output Problems

Check your microphone and speaker settings. Ensure they are properly configured and accessible by your system.

Dependency and Version Conflicts

Verify that all dependencies are installed with compatible versions. Use a virtual environment to manage package versions effectively.

Conclusion

Summary of What You've Built

In this tutorial, you built a functional AI Voice Agent using the VideoSDK API. This agent can process voice input, generate responses, and interact with users in real-time.

Next Steps and Further Learning

Continue exploring the VideoSDK framework to enhance your agent's capabilities. Consider integrating more advanced features and exploring additional plugins for a more robust 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