Build an AI Voice Assistant for BFSI

Step-by-step guide to building an AI voice assistant for the BFSI industry using VideoSDK.

Introduction to AI Voice Agents in the BFSI Industry

AI Voice Agents are sophisticated software systems that can understand and respond to human speech. They leverage technologies like Speech-to-Text (STT), Natural Language Processing (NLP), and Text-to-Speech (TTS) to interact with users in a conversational manner. In the Banking, Financial Services, and Insurance (BFSI) industry, these agents play a crucial role in enhancing customer service by providing instant assistance, answering queries, and guiding users through various processes.

Why are they important for the BFSI industry?

In the BFSI sector, AI Voice Agents can handle a variety of tasks such as answering customer inquiries about account balances, providing information on loan options, assisting with insurance claims, and even offering investment advice. They help reduce the workload on human agents, improve response times, and ensure a consistent customer experience.

Core Components of a

Voice Agent

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

What You'll Build in This Tutorial

In this tutorial, you will learn how to build a fully functional AI Voice Assistant tailored for the BFSI industry using the VideoSDK framework. We will guide you through setting up the development environment, building the agent, and testing it in a live environment.

Architecture and Core Concepts

High-Level Architecture Overview

The architecture of an AI

Voice Agent

involves several components working together to process user input and generate responses. The data flow begins with the user speaking into a microphone. This audio input is captured and processed by the

Deepgram STT Plugin for voice agent

, which converts it into text. The text is then analyzed by a

OpenAI LLM Plugin for voice agent

to generate a response, which is subsequently converted back into speech by the

ElevenLabs TTS Plugin for voice agent

.
Diagram

Understanding Key Concepts in the VideoSDK Framework

  • Agent: This is the core class that represents your voice assistant. It handles the interaction with users and manages the conversation flow.
  • Cascading Pipeline in AI voice Agents

    : This component defines the sequence of audio processing tasks, from STT to LLM to TTS.
  • VAD &

    Turn Detector for AI voice Agents

    : Voice Activity Detection (VAD) and Turn Detection are crucial for determining when the agent should listen and when it should speak.

Setting Up the Development Environment

Prerequisites

To get started, ensure you have Python 3.11+ installed on your system. 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 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 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 knowledgeable and efficient AI Voice Assistant specialized in the BFSI (Banking, Financial Services, and Insurance) industry. Your primary role is to assist users by providing accurate information and guidance related to banking services, financial products, and insurance policies. You can answer questions about account management, loan options, investment opportunities, and insurance coverage. You are capable of guiding users through basic troubleshooting steps for common issues and providing updates on financial news and trends. However, you are not a licensed financial advisor and must include a disclaimer advising users to consult with a certified financial professional for personalized advice. You must ensure user data privacy and comply with industry regulations such as GDPR and CCPA. You should not engage in any transactions or handle sensitive financial information directly."
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](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 interact with your AI Voice Agent, you need a meeting ID. You can generate one using 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 extends the base Agent class. It initializes with specific instructions tailored for the BFSI industry. The on_enter and on_exit methods define what the agent says when a session starts and ends.
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 the heart of the voice agent, connecting STT, LLM, and TTS plugins. Each plugin plays a specific role in processing audio and generating responses.
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 lifecycle of the agent session. It initializes the agent, sets up the conversation flow, and starts the session. The make_context function configures the session environment, including room options.
1async def start_session(context: JobContext):
2    agent = MyVoiceAgent()
3    conversation_flow = ConversationFlow(agent)
4
5    pipeline = CascadingPipeline(
6        stt=DeepgramSTT(model="nova-2", language="en"),
7        llm=OpenAILLM(model="gpt-4o"),
8        tts=ElevenLabsTTS(model="eleven_flash_v2_5"),
9        vad=SileroVAD(threshold=0.35),
10        turn_detector=TurnDetector(threshold=0.8)
11    )
12
13    session = AgentSession(
14        agent=agent,
15        pipeline=pipeline,
16        conversation_flow=conversation_flow
17    )
18
19    try:
20        await context.connect()
21        await session.start()
22        await asyncio.Event().wait()
23    finally:
24        await session.close()
25        await context.shutdown()
26
27def make_context() -> JobContext:
28    room_options = RoomOptions(
29        name="VideoSDK Cascaded Agent",
30        playground=True
31    )
32
33    return JobContext(room_options=room_options)
34
35if __name__ == "__main__":
36    job = WorkerJob(entrypoint=start_session, jobctx=make_context)
37    job.start()
38

Running and Testing the Agent

Step 5.1: Running the Python Script

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

Step 5.2: Interacting with the Agent in the Playground

Once the script is running, check the console for the playground link. Open it in a browser to interact with your AI Voice Agent. You can speak into the microphone and receive responses from the agent.

Advanced Features and Customizations

Extending Functionality with Custom Tools

You can extend the agent's capabilities by integrating custom tools using the function_tool feature. This allows you to add specialized functions tailored to your needs.

Exploring Other Plugins

Experiment with 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 set in the .env file and that you have the necessary permissions in your VideoSDK account.

Audio Input/Output Problems

Check your microphone and speaker settings. Ensure the correct devices are selected in your system settings.

Dependency and Version Conflicts

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

Conclusion

Summary of What You've Built

You have successfully built an AI Voice Assistant tailored for the BFSI industry using the VideoSDK framework. This agent can interact with users, providing information and assistance related to banking, financial services, and insurance.

Next Steps and Further Learning

Explore additional plugins and features to enhance your agent's capabilities. Consider integrating more advanced NLP models or adding support for multiple languages.

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