Build a Conversational AI Voice Agent for Finance

Step-by-step guide to building a conversational AI voice agent for financial services using VideoSDK.

Introduction to AI Voice Agents in Financial Services

What is an AI

Voice Agent

?

An AI

Voice Agent

is an intelligent system designed to interact with users through natural language voice commands. These agents utilize advanced technologies such as Speech-to-Text (STT), Language Models (LLM), and Text-to-Speech (TTS) to process and respond to user queries. They are capable of understanding and generating human-like responses, making interactions seamless and efficient.

Why are they important for the Financial Industry?

In the financial sector, AI Voice Agents play a crucial role in enhancing customer service, automating routine tasks, and providing real-time financial information. They can assist users with banking inquiries, investment options, and basic financial planning, thereby improving customer satisfaction and operational efficiency.

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 the response text back into speech.

What You'll Build in This Tutorial

In this tutorial, you will build a conversational AI

Voice Agent

tailored for the financial industry using the VideoSDK framework. This agent will be capable of handling financial inquiries and guiding users through basic financial concepts.

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. Here's a simplified flow:
  1. User speaks into the microphone.
  2. The audio is captured and processed by the STT plugin.
  3. The transcribed text is sent to the LLM for understanding and response generation.
  4. The response text is converted back to speech by the TTS plugin.
  5. The agent delivers the spoken response to the user.
Diagram

Understanding Key Concepts in the VideoSDK Framework

  • Agent: The core class representing your bot. It handles interactions and manages the conversation flow.
  • CascadingPipeline: A sequence of audio processing steps (STT -> LLM -> TTS) that defines how data flows through the system. For a detailed understanding, refer to the

    Cascading pipeline in AI voice Agents

    .
  • VAD & TurnDetector: These components help the agent determine when to listen and when to respond, ensuring smooth interactions. Learn more about the

    Turn detector for AI voice Agents

    .

Setting Up the Development Environment

Prerequisites

Before you begin, ensure you have the following:
  • Python 3.11+ installed on your machine.
  • A VideoSDK account. 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 Python 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

Let's start by looking at the complete code for our 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 financial assistant specializing in conversational AI for the financial sector. Your primary role is to assist users with financial inquiries, provide insights on financial products, and guide them through basic financial planning. You can answer questions about banking services, investment options, and financial terminology. However, you are not a certified financial advisor, and you must include a disclaimer advising users to consult with a professional financial advisor for personalized advice. You should maintain a professional and courteous tone, ensuring that all information provided is accurate and up-to-date. You are also capable of directing users to relevant financial resources and tools for further assistance."
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 your agent, you'll need a meeting ID. You can generate one using the VideoSDK API:
1curl -X POST "https://api.videosdk.live/v1/meetings" \
2-H "Authorization: YOUR_API_KEY" \
3-H "Content-Type: application/json"
4

Step 4.2: Creating the Custom Agent Class

The MyVoiceAgent class extends the Agent class provided by VideoSDK. It customizes the agent's behavior on entering and exiting a session:
1class MyVoiceAgent(Agent):
2    def __init__(self):
3        super().__init__(instructions=agent_instructions)
4    async def on_enter(self):
5        await self.session.say("Hello! How can I help?")
6    async def on_exit(self):
7        await self.session.say("Goodbye!")
8

Step 4.3: Defining the Core Pipeline

The CascadingPipeline is the backbone of the agent, connecting various plugins to process audio and text. This includes components like

Silero Voice Activity Detection

to enhance interaction quality.
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 sets up and manages the agent session, while make_context prepares the environment. For a comprehensive understanding of session management, refer to the

AI voice Agent Sessions

.
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    return JobContext(room_options=room_options)
33

Running and Testing the Agent

Step 5.1: Running the Python Script

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

Step 5.2: Interacting with the Agent in the Playground

After running the script, look for the playground link in the console. Open it in a browser to interact with your agent.

Advanced Features and Customizations

Extending Functionality with Custom Tools

You can extend the agent's capabilities by integrating custom tools, allowing it to perform additional tasks or access external data sources.

Exploring Other Plugins

Explore other STT, LLM, and TTS plugins to enhance your agent's performance and 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 to ensure they are configured correctly.

Dependency and Version Conflicts

Ensure all dependencies are installed with compatible versions, as specified in the documentation.

Conclusion

Summary of What You've Built

In this tutorial, you've built a fully functional conversational AI Voice Agent for the financial industry using the VideoSDK framework.

Next Steps and Further Learning

Explore additional plugins and customize your agent further to suit specific financial use cases. For a comprehensive understanding of the components involved, review the

AI voice Agent core components overview

.

Get 10,000 Free Minutes Every Months

No credit card required to start.

Want to level-up your learning? Subscribe now

Subscribe to our newsletter for more tech based insights

FAQ