Build an AI Voice Agent for BFSI

Step-by-step guide to building an AI Voice Agent for the BFSI industry using VideoSDK. Includes complete code and testing instructions.

Introduction to AI Voice Agents in BFSI Industry

AI Voice Agents are transforming how industries interact with customers by providing automated, intelligent responses to user queries. In the BFSI (Banking, Financial Services, and Insurance) sector, these agents play a crucial role in enhancing customer service, providing instant responses to common queries, and assisting with tasks like balance inquiries, transaction histories, and more.

What is an AI

Voice Agent

?

An AI

Voice Agent

is a software application that uses voice recognition, natural language processing, and speech synthesis to interact with users through spoken language. These agents can understand user queries, process them, and provide relevant responses, making them an invaluable tool for customer service automation.

Why are they important for the BFSI industry?

In the BFSI industry, AI Voice Agents can handle a wide range of tasks, from answering frequently asked questions to guiding users through complex processes like loan applications or insurance claims. They help reduce call center workloads and improve customer satisfaction by providing quick and accurate responses.

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 the response text back into spoken language.
For a more detailed understanding, refer to the

AI voice Agent core components overview

.

What You'll Build in This Tutorial

In this tutorial, you will build an AI

Voice Agent

tailored for the BFSI industry using the VideoSDK framework. This agent will be capable of understanding and responding to various banking and financial queries.

Architecture and Core Concepts

High-Level Architecture Overview

The AI

Voice Agent

processes user input through a series of steps: capturing audio input, converting it to text, processing the text with an LLM, and finally converting the response back to speech.
Diagram

Understanding Key Concepts in the VideoSDK Framework

  • Agent: The main class representing your AI Voice Agent.
  • CascadingPipeline: Manages the flow of data through STT, LLM, and TTS components. Learn more about the

    Cascading pipeline in AI voice Agents

    .
  • VAD & TurnDetector: These components help the agent know when to listen and when to respond.

Setting Up the Development Environment

Prerequisites

To get started, 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

Create a virtual environment to manage your project's dependencies.
1python -m venv venv
2source venv/bin/activate  # On Windows use `venv\Scripts\activate`
3

Step 2: Install Required Packages

Install the necessary Python packages using pip.
1pip install videosdk-agents videosdk-plugins
2

Step 3: Configure API Keys in a .env file

Create a .env file to store your API keys securely. You'll need keys for VideoSDK and any other services you plan to use, like OpenAI or ElevenLabs.

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 an AI Voice Agent specialized in the BFSI (Banking, Financial Services, and Insurance) industry. Your primary role is to assist users by providing information and guidance on various BFSI-related topics. You can answer questions about banking services, financial products, insurance policies, and investment options. Additionally, you can help users understand complex financial terms and processes in a simplified manner. However, you are not a certified financial advisor, and you must always include a disclaimer advising users to consult with a professional for personalized financial advice. You should also ensure user data privacy and comply with industry regulations such as GDPR and CCPA. Your responses should be concise, informative, and user-friendly, aiming to enhance the user's understanding and experience in the BFSI sector."
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 interact with the agent, you need a meeting ID. You can generate this using a simple curl command:
1curl -X POST https://api.videosdk.live/v1/meetings -H "Authorization: YOUR_API_KEY"
2

Step 4.2: Creating the Custom Agent Class

The MyVoiceAgent class extends the Agent class, providing custom behavior for entering and exiting conversations.
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 defines how audio is processed through various stages.
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
For more details on voice activity detection, explore

Silero Voice Activity Detection

.

Step 4.4: Managing the Session and Startup Logic

This section manages the agent's lifecycle, including starting and stopping the session.
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
31def make_context() -> JobContext:
32    room_options = RoomOptions(
33    #  room_id="YOUR_MEETING_ID",  # Set to join a pre-created room; omit to auto-create
34        name="VideoSDK Cascaded Agent",
35        playground=True
36    )
37
38    return JobContext(room_options=room_options)
39
40if __name__ == "__main__":
41    job = WorkerJob(entrypoint=start_session, jobctx=make_context)
42    job.start()
43

Running and Testing the Agent

Step 5.1: Running the Python Script

To start the agent, run the script using the following command:
1python main.py
2

Step 5.2: Interacting with the Agent in the Playground

Once the agent is running, you can interact with it via the VideoSDK

AI Agent playground

. Look for the playground link in the console output and join the meeting to start interacting with your AI Voice Agent.

Advanced Features and Customizations

Extending Functionality with Custom Tools

The VideoSDK framework allows you to extend the agent's capabilities by integrating custom tools and plugins to handle specific tasks or data processing.

Exploring Other Plugins

While this tutorial uses specific plugins for STT, LLM, and TTS, you can explore other options available in the VideoSDK framework to suit your needs.

Troubleshooting Common Issues

API Key and Authentication Errors

Ensure your API keys are correctly set up 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 correctly configured and accessible by the application.

Dependency and Version Conflicts

Ensure all dependencies are installed with compatible versions, and use a virtual environment to manage them.

Conclusion

Summary of What You've Built

You have successfully built an AI Voice Agent for the BFSI industry using the VideoSDK framework, capable of understanding and responding to various financial queries.

Next Steps and Further Learning

Explore additional plugins and customization options in the VideoSDK framework to enhance your agent's capabilities and tailor it further to your specific use cases.

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