Build a Healthcare AI Voice Agent

Step-by-step guide to building a healthcare AI voice agent using VideoSDK with full code examples.

Introduction to AI Voice Agents in Healthcare

AI Voice Agents are transformative tools in the healthcare industry, enabling seamless interaction between patients and healthcare providers. These agents leverage advanced technologies to understand and respond to human speech, making healthcare more accessible and efficient.

What is an AI

Voice Agent

?

An AI

Voice Agent

is a software application capable of understanding spoken language and responding in a conversational manner. It combines speech recognition, natural language processing, and speech synthesis to interact with users naturally.

Why are they important for the healthcare industry?

In healthcare, AI Voice Agents can assist in scheduling appointments, providing information about symptoms, and guiding patients through healthcare processes. They enhance patient engagement and streamline operations, allowing providers to focus on critical tasks.

Core Components of a

Voice Agent

  • Speech-to-Text (STT): Converts spoken language into text.
  • Large Language Model (LLM): Processes the text to generate appropriate responses.
  • Text-to-Speech (TTS): Converts text responses back into speech.
For a comprehensive understanding of these components, refer to the

AI voice Agent core components overview

.

What You’ll Build in This Tutorial

In this tutorial, you will learn to build a healthcare-focused AI

Voice Agent

using the VideoSDK framework. The agent will handle basic healthcare inquiries, provide general information, and assist with appointment scheduling.

Architecture and Core Concepts

High-Level Architecture Overview

The AI

Voice Agent

architecture involves several components working in harmony to process user input and generate responses. Here’s a step-by-step flow:
  1. User Speech Input: The user speaks into the microphone.
  2. Speech-to-Text (STT): The audio input is converted into text.
  3. Language Processing (LLM): The text is analyzed to determine the appropriate response.
  4. Text-to-Speech (TTS): The response text is converted back into audio.
  5. User Receives Response: The user hears the response through the speaker.
Diagram

Understanding Key Concepts in the VideoSDK Framework

  • Agent: Represents the core of your AI Voice Agent, handling interactions.
  • CascadingPipeline: Manages the flow of audio processing from STT to LLM to TTS. For more details, explore the

    Cascading pipeline in AI voice Agents

    .
  • VAD & TurnDetector: Ensure the agent knows when to listen and when to speak. Learn more about the

    Turn detector for AI voice Agents

    .

Setting Up the Development Environment

Prerequisites

To follow this tutorial, ensure you have Python 3.11+ installed and a VideoSDK account. Sign up at app.videosdk.live.

Step 1: Create a Virtual Environment

1python -m venv venv
2source venv/bin/activate  # On Windows use `venv\\Scripts\\activate`
3

Step 2: Install Required Packages

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

To build the AI Voice Agent, we’ll use the following complete code block:
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 helpful healthcare assistant designed to engage in conversational AI interactions within the healthcare domain. Your primary role is to assist users by answering questions about common symptoms, providing general healthcare information, and helping schedule appointments with healthcare providers. You are equipped with the ability to understand and respond to a wide range of healthcare-related queries, ensuring a user-friendly and informative experience.\n\nCapabilities:\n1. Answer questions about common symptoms and general healthcare topics.\n2. Provide information on healthcare services and facilities.\n3. Assist in scheduling appointments with healthcare providers.\n4. Offer guidance on navigating healthcare systems and resources.\n\nConstraints and Limitations:\n1. You are not a medical professional and cannot provide medical diagnoses or treatment plans.\n2. Always include a disclaimer advising users to consult a qualified healthcare professional for medical advice.\n3. Ensure user privacy and confidentiality in all interactions.\n4. Limit responses to general information and avoid personal health advice.\n5. Adhere to all relevant healthcare regulations and guidelines regarding patient information and data security."
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:
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":"Healthcare Session"}'
5

Step 4.2: Creating the Custom Agent Class

The MyVoiceAgent class extends the Agent class, providing custom instructions for interacting with users. It defines how the agent greets users and says goodbye.
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 central to the agent’s functionality, defining how audio is processed:
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 information on voice activity detection, refer to

Silero Voice Activity Detection

.

Step 4.4: Managing the Session and Startup Logic

The start_session function sets up the agent session, managing the lifecycle of the conversation:
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
For details on managing sessions, see

AI voice Agent Sessions

.

Running and Testing the Agent

Step 5.1: Running the Python Script

To run the agent, execute the script using:
1python main.py
2

Step 5.2: Interacting with the Agent in the Playground

Once the script is running, you’ll receive a playground link in the console. Open it in a browser to interact with your agent. Speak into your microphone to test the agent’s responses.

Advanced Features and Customizations

Extending Functionality with Custom Tools

Enhance your agent by integrating custom tools and APIs. The function_tool interface allows you to extend the agent’s capabilities beyond the default setup.

Exploring Other Plugins

Experiment with different STT, LLM, and TTS plugins to optimize performance and cost. Consider alternatives like Cartesia for STT or Google Gemini for LLM.

Troubleshooting Common Issues

API Key and Authentication Errors

Ensure your API keys are correctly set in the .env file and that your VideoSDK account is active.

Audio Input/Output Problems

Check your microphone and speaker settings. Ensure permissions are granted for audio access.

Dependency and Version Conflicts

Verify that all dependencies are installed and compatible with Python 3.11+.

Conclusion

Summary of What You’ve Built

You’ve successfully created a conversational AI Voice Agent tailored for the healthcare industry using VideoSDK. This agent can handle basic inquiries and assist with healthcare-related tasks.

Next Steps and Further Learning

Explore additional customizations and integrations to expand your agent’s capabilities. Consider diving deeper into AI and machine learning to enhance your understanding and skills.

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